diff --git a/README.md b/README.md index 63580c2..180b258 100644 --- a/README.md +++ b/README.md @@ -9,6 +9,7 @@ - 支持普通响应和 SSE 流式响应 - 支持文本、图片、thinking/reasoning、工具定义、工具调用和工具结果转换 - 分离配置 Zen key 池与 Zen Go key 池 +- 支持无需上游 key 的 Zen 匿名模式,免费模型优先按代理出口 IP 轮换并可回退 Zen key - 模型同时存在于两个上游时按 `prefer` 配置优先使用 Go 或 Zen(默认 Go) - 支持直连、HTTP、HTTPS、SOCKS5 和 SOCKS5H 代理 - 支持从文本文件读取代理池,并与配置内的代理合并、去重 @@ -33,7 +34,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.refresh_seconds` 的两倍,且不低于 60 秒。刚启动时短暂返回 `503 starting` 属于正常现象,模型列表首次刷新成功后会变为 `200 ok`。 @@ -102,6 +103,7 @@ cp config.example.json config.json "server_keys": ["change-this-local-key"], "zen_keys": ["sk-your-zen-key"], "go_keys": [], + "anonymous": false, "prefer": "go", "proxyfile": "", "proxies": ["direct"], @@ -147,11 +149,20 @@ cp config.example.json config.json | `server_keys` | 调用本代理时使用的本地 API key 列表。它们只用于本地鉴权,不会发送给 OpenCode。 | | `zen_keys` | OpenCode Zen API key 池。允许配置多个 key。 | | `go_keys` | OpenCode Zen Go API key 池。没有 Go key 时可以使用空数组。 | +| `anonymous` | 是否启用 Zen 匿名模式,默认 `false`。启用后模型 ID 包含 `free` 时优先使用 OpenCode 的 `public` 凭证。 | | `prefer` | 模型同时存在于 Zen 与 Go 时优先使用的上游,值为 `go` 或 `zen`,默认 `go`。仅存在于某一池时不受影响。 | | `proxyfile` | 可选代理池文件路径。相对路径以 `config.json` 所在目录为基准;内容会追加到 `proxies` 并去重。 | | `proxies` | 上游代理列表。支持 `direct`、`http://`、`https://`、`socks5://` 和 `socks5h://`。URL 可以包含代理用户名和密码。 | -`server_keys` 至少需要一个值;`zen_keys` 和 `go_keys` 至少有一个池不能为空。 +`server_keys` 至少需要一个值。`anonymous` 为 `false` 时,`zen_keys` 和 `go_keys` 至少有一个池不能为空;启用匿名模式后两个上游 key 池可以同时为空。 + +### Zen 匿名模式 + +OpenCode 客户端在没有配置 Zen key 时使用固定的 `public` 凭证;Zen 服务端将它转换为匿名请求,并按出口 IP 对允许匿名访问的模型限流。本项目使用相同协议:OpenAI/Responses 上游请求发送 `Authorization: Bearer public`,Anthropic 上游请求发送 `x-api-key: public`。 + +启用 `anonymous` 后,模型 ID 大小写不敏感地包含 `free` 时优先走匿名 Zen。遇到网络错误、401、403、429 或 5xx 会切换到下一个健康 proxy;429 的 `Retry-After` 只冷却对应 proxy 的匿名通道。匿名阶段最多尝试 `retry.max_attempts` 个不同 proxy,全部失败后若存在真实 `zen_keys`,再以独立的重试预算回退 Zen key 池。其他 4xx 属于确定性的请求错误,不切换 proxy 或 key。 + +`/v1/models` 保持现有模型目录行为,不会因为启用匿名模式而只保留免费模型。匿名模式本身只能为名称包含 `free` 的 Zen 模型建立无 key 路由;其他模型仍需要真实 Zen/Go key。 ### key 与代理分配规则 @@ -206,7 +217,7 @@ socks5://127.0.0.1:1080 # 备用代理 | 字段 | 含义 | | --- | --- | -| `retry.max_attempts` | 单个请求的最大尝试次数,包含第一次请求。网络错误、认证失败、限流和 5xx 会切换节点;其他 4xx 属于确定性的请求错误,会直接返回而不轮换 key。 | +| `retry.max_attempts` | 每个请求阶段的最大尝试次数,包含第一次请求。网络错误、认证失败、限流和 5xx 会切换节点;其他 4xx 属于确定性的请求错误,会直接返回而不轮换 key。匿名阶段和随后的 Zen key 回退阶段各自使用该预算。 | | `retry.timeout_seconds` | 单个客户端请求的总超时时间,同时用于限制上游响应头等待时间。 | 流式响应一旦已经向客户端输出数据,就不会切换节点重新生成,避免拼接两个不同的响应。 diff --git a/admin.go b/admin.go index 333cc1b..4ec6e3f 100644 --- a/admin.go +++ b/admin.go @@ -230,6 +230,7 @@ type ConfigView struct { 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 UpstreamConfig `json:"upstream"` @@ -266,6 +267,7 @@ type ConfigUpdate struct { 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 UpstreamConfig `json:"upstream"` @@ -310,7 +312,7 @@ func (a *AdminServer) handlePutConfig(w http.ResponseWriter, r *http.Request) { return } candidate := Config{ - Listen: update.Listen, ServerKeys: serverKeys, ZenKeys: zenKeys, GoKeys: goKeys, Proxies: proxies, ProxyFile: update.ProxyFile, + 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, WebUI: WebUIConfig{Enabled: update.WebUI.Enabled, Listen: update.WebUI.Listen, Username: current.WebUI.Username, PasswordHash: current.WebUI.PasswordHash, SessionTTLMinutes: update.WebUI.SessionTTLMinutes}, } @@ -465,7 +467,7 @@ func (a *AdminServer) 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), + 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, WebUI: WebUIView{Enabled: cfg.WebUI.Enabled, Listen: cfg.WebUI.Listen, Username: cfg.WebUI.Username, SessionTTLMinutes: cfg.WebUI.SessionTTLMinutes}, diff --git a/config.example.json b/config.example.json index f780eb6..5ef3f51 100644 --- a/config.example.json +++ b/config.example.json @@ -3,6 +3,7 @@ "server_keys": ["change-this-local-key"], "zen_keys": ["sk-your-zen-key"], "go_keys": [], + "anonymous": false, "prefer": "go", "proxyfile": "", "proxies": ["direct"], diff --git a/config.go b/config.go index 3f741fa..be50ab7 100644 --- a/config.go +++ b/config.go @@ -19,6 +19,7 @@ type Config struct { ServerKeys []string `json:"server_keys"` 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"` @@ -119,8 +120,8 @@ func NormalizeConfig(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 len(cfg.ZenKeys) == 0 && len(cfg.GoKeys) == 0 { - return Config{}, errors.New("zen_keys or go_keys must contain at least one upstream 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 cfg.Retry.MaxAttempts < 1 { return Config{}, errors.New("retry.max_attempts must be at least 1") diff --git a/docker-entrypoint.sh b/docker-entrypoint.sh index 7220294..6a3c38d 100644 --- a/docker-entrypoint.sh +++ b/docker-entrypoint.sh @@ -19,7 +19,7 @@ else cp "$app_dir/config.example.json" "$generated_config" fi active_config=$generated_config - printf '%s\n' "config.json not found; using a persistent generated copy. Set real API keys and change the WebUI password before use." + printf '%s\n' "config.json not found; using a persistent generated copy. Set real API keys or enable anonymous mode, and change the WebUI password before use." fi source_fingerprint() { diff --git a/gateway.go b/gateway.go index 69bc4c4..7aaa901 100644 --- a/gateway.go +++ b/gateway.go @@ -17,6 +17,8 @@ import ( const maxRequestBody = 32 << 20 +const anonymousZenKey = "public" + const ( proxyHealthCheckURL = "https://cloudflare.com/cdn-cgi/trace" proxyHealthCheckInterval = 15 * time.Minute @@ -29,6 +31,7 @@ type Gateway struct { transports *transportPool zenNodes *nodePool goNodes *nodePool + anonymous *anonymousPool catalog *modelCatalog monitor *Monitor } @@ -54,9 +57,10 @@ type healthModels struct { } type healthKeys struct { - Zen int `json:"zen"` - Go int `json:"go"` - Total int `json:"total"` + Zen int `json:"zen"` + Go int `json:"go"` + Total int `json:"total"` + Anonymous bool `json:"anonymous"` } type healthProxies struct { @@ -85,6 +89,7 @@ func NewGateway(cfg Config, logger *slog.Logger, monitor *Monitor) (*Gateway, er transports: transports, zenNodes: zenNodes, goNodes: goNodes, + anonymous: newAnonymousPool(cfg.Anonymous, transports, cooldown), catalog: newModelCatalog(cfg.Prefer, cfg.Models.Protocols), monitor: monitor, }, nil @@ -123,7 +128,7 @@ func (g *Gateway) handleHealth(w http.ResponseWriter, _ *http.Request) { issues = append(issues, "model_catalog_stale") } } - if zenKeys+goKeys == 0 { + if zenKeys+goKeys == 0 && !g.cfg.Anonymous { issues = append(issues, "no_upstream_keys") } if proxyHealthy == 0 { @@ -152,7 +157,7 @@ func (g *Gateway) handleHealth(w http.ResponseWriter, _ *http.Request) { LastRefresh: lastRefresh, StaleAfterSeconds: int(staleAfter / time.Second), }, - Keys: healthKeys{Zen: zenKeys, Go: goKeys, Total: zenKeys + goKeys}, + Keys: healthKeys{Zen: zenKeys, Go: goKeys, Total: zenKeys + goKeys, Anonymous: g.cfg.Anonymous}, Proxies: healthProxies{ Total: proxyTotal, Healthy: proxyHealthy, @@ -226,7 +231,7 @@ func (g *Gateway) handleInference(external Protocol) http.HandlerFunc { writeAPIError(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) + route, err := g.catalog.Route(model, len(g.cfg.ZenKeys) > 0, len(g.cfg.GoKeys) > 0, g.cfg.Anonymous) if err != nil { writeAPIError(w, external, http.StatusBadRequest, err.Error(), "invalid_request_error", "model") return @@ -309,6 +314,83 @@ func (g *Gateway) handleInference(external Protocol) http.HandlerFunc { } func (g *Gateway) doUpstream(ctx context.Context, route modelRoute, body []byte, ids requestIDs) (*http.Response, error) { + if !route.Anonymous { + return g.doKeyUpstream(ctx, route, body, ids, 0) + } + resp, err, attempts, exhausted := g.doAnonymousUpstream(ctx, route, body, ids) + if !exhausted || g.zenNodes.Len() == 0 { + return resp, err + } + if resp != nil { + drainAndClose(resp.Body) + } + route.Anonymous = false + g.logger.Debug("anonymous attempts exhausted; falling back to Zen keys", "component", "upstream", "event", "anonymous_fallback", "request_id", ids.Request, "attempts", attempts) + return g.doKeyUpstream(ctx, route, body, ids, attempts) +} + +// doAnonymousUpstream tries each selected proxy at most once. Its retry budget +// is independent from the authenticated Zen-key phase that may follow it. +func (g *Gateway) doAnonymousUpstream(ctx context.Context, route modelRoute, body []byte, ids requestIDs) (*http.Response, error, int, bool) { + var lastResponse *http.Response + var lastErr error + cursor := g.anonymous.CursorFor(ids.Session) + limit := min(g.cfg.Retry.MaxAttempts, g.anonymous.Len()) + attempts := 0 + for attempts < limit { + node := cursor.Next() + if node == nil { + break + } + attempts++ + if meta, _ := ctx.Value(requestMetaKey{}).(*requestMeta); meta != nil { + meta.Attempts = attempts + } + if lastResponse != nil { + drainAndClose(lastResponse.Body) + lastResponse = nil + } + req, err := newUpstreamRequest(ctx, g.cfg.Upstream.Zen, route.Protocol, body, ids, anonymousZenKey) + if err != nil { + return nil, err, attempts, false + } + started := time.Now() + resp, err := node.proxy.client.Do(req) + duration := time.Since(started) + status := 0 + if resp != nil { + status = resp.StatusCode + } + g.syncProxyResult(ctx, node.proxy, status, err) + if err == nil && resp.StatusCode/100 == 2 { + g.anonymous.MarkSuccess(node) + g.logger.Debug("anonymous upstream accepted request", "component", "upstream", "event", "anonymous_attempt_succeeded", "request_id", ids.Request, "attempt", attempts, "tier", TierZen, "proxy", redactURL(node.proxy.name), "status", resp.StatusCode, "duration_ms", duration.Milliseconds()) + return resp, nil, attempts, false + } + if isNonRetryableClientResponse(resp, err) { + g.anonymous.MarkSuccess(node) + g.logger.Debug("anonymous upstream rejected a non-retryable request", "component", "upstream", "event", "anonymous_attempt_rejected", "request_id", ids.Request, "attempt", attempts, "tier", TierZen, "proxy", redactURL(node.proxy.name), "status", resp.StatusCode, "duration_ms", duration.Milliseconds()) + return resp, nil, attempts, false + } + g.anonymous.MarkFailure(node, resp, err) + lastResponse = resp + lastErr = 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", TierZen, "proxy", redactURL(node.proxy.name), "duration_ms", duration.Milliseconds(), "error", err) + } else { + g.logger.Debug("anonymous upstream returned a retryable response", "component", "upstream", "event", "anonymous_attempt_retryable_response", "request_id", ids.Request, "attempt", attempts, "tier", TierZen, "proxy", redactURL(node.proxy.name), "status", resp.StatusCode, "duration_ms", duration.Milliseconds()) + } + } + if lastResponse != nil { + return lastResponse, nil, attempts, true + } + if lastErr == nil { + lastErr = errors.New("no healthy anonymous proxies available") + } + return nil, lastErr, attempts, true +} + +func (g *Gateway) doKeyUpstream(ctx context.Context, route modelRoute, body []byte, ids requestIDs, attemptOffset int) (*http.Response, error) { var lastResponse *http.Response var lastErr error nodes := g.zenNodes @@ -325,7 +407,7 @@ func (g *Gateway) doUpstream(ctx context.Context, route modelRoute, body []byte, // Attempts are exposed only as aggregate request metadata and never // include the selected credential. if meta, _ := ctx.Value(requestMetaKey{}).(*requestMeta); meta != nil { - meta.Attempts = attempt + meta.Attempts = attemptOffset + attempt } node := cursor.Next() if node == nil { @@ -335,8 +417,7 @@ func (g *Gateway) doUpstream(ctx context.Context, route modelRoute, body []byte, drainAndClose(lastResponse.Body) lastResponse = nil } - endpoint := strings.TrimRight(baseURL, "/") + protocolPath(route.Protocol) - req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(body)) + req, err := newUpstreamRequest(ctx, baseURL, route.Protocol, body, ids, node.key) if err != nil { return nil, err } @@ -345,19 +426,6 @@ func (g *Gateway) doUpstream(ctx context.Context, route modelRoute, body []byte, lastErr = errors.New("upstream key has no proxy binding") break } - req.Header.Set("Content-Type", "application/json") - req.Header.Set("Accept", "application/json, text/event-stream") - req.Header.Set("User-Agent", opencodeUserAgent()) - req.Header.Set("x-opencode-client", "cli") - req.Header.Set("x-opencode-session", ids.Session) - req.Header.Set("x-opencode-request", ids.Request) - req.Header.Set("x-opencode-project", ids.Project) - if route.Protocol == ProtocolAnthropic { - req.Header.Set("x-api-key", node.key) - req.Header.Set("anthropic-version", "2023-06-01") - } else { - req.Header.Set("Authorization", "Bearer "+node.key) - } attemptStarted := time.Now() resp, err := proxy.client.Do(req) attemptDuration := time.Since(attemptStarted) @@ -374,7 +442,7 @@ func (g *Gateway) doUpstream(ctx context.Context, route modelRoute, body []byte, // Request-shape errors are deterministic and must be returned to the // caller without rotating through unrelated keys. Authentication, // throttling, server, and transport failures remain retryable. - if err == nil && resp.StatusCode >= 400 && resp.StatusCode < 500 && resp.StatusCode != http.StatusUnauthorized && resp.StatusCode != http.StatusForbidden && resp.StatusCode != http.StatusTooManyRequests { + if isNonRetryableClientResponse(resp, err) { nodes.MarkSuccess(node) g.logger.Debug("upstream rejected a non-retryable request", "component", "upstream", "event", "attempt_rejected", "request_id", ids.Request, "attempt", attempt, "tier", route.Tier, "key_id", secretFingerprint(node.key), "status", resp.StatusCode, "proxy", redactURL(proxy.name), "duration_ms", attemptDuration.Milliseconds()) return resp, nil @@ -400,6 +468,32 @@ func (g *Gateway) doUpstream(ctx context.Context, route modelRoute, body []byte, return nil, lastErr } +func newUpstreamRequest(ctx context.Context, baseURL string, protocol Protocol, body []byte, ids requestIDs, key string) (*http.Request, error) { + endpoint := strings.TrimRight(baseURL, "/") + protocolPath(protocol) + req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(body)) + if err != nil { + return nil, err + } + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Accept", "application/json, text/event-stream") + req.Header.Set("User-Agent", opencodeUserAgent()) + req.Header.Set("x-opencode-client", "cli") + req.Header.Set("x-opencode-session", ids.Session) + req.Header.Set("x-opencode-request", ids.Request) + req.Header.Set("x-opencode-project", ids.Project) + if protocol == ProtocolAnthropic { + req.Header.Set("x-api-key", key) + req.Header.Set("anthropic-version", "2023-06-01") + } else { + req.Header.Set("Authorization", "Bearer "+key) + } + return req, nil +} + +func isNonRetryableClientResponse(resp *http.Response, err error) bool { + return err == nil && resp != nil && resp.StatusCode >= 400 && resp.StatusCode < 500 && resp.StatusCode != http.StatusUnauthorized && resp.StatusCode != http.StatusForbidden && resp.StatusCode != http.StatusTooManyRequests +} + // syncProxyResult updates proxy health from real traffic. Only timeouts and // connection refusals mark a proxy unavailable. Other errors and 4xx/5xx // responses trigger a neutral URL check without being treated as proxy failure. @@ -530,7 +624,7 @@ func (g *Gateway) StartModelRefresh(ctx context.Context) { var zen, goModels []string var wg sync.WaitGroup wg.Add(2) - go func() { defer wg.Done(); zen = g.refreshTier(ctx, g.cfg.Upstream.Zen, g.zenNodes) }() + 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.Wait() if zen != nil || goModels != nil { @@ -553,6 +647,39 @@ func (g *Gateway) StartModelRefresh(ctx context.Context) { }() } +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.Zen) +} + +func (g *Gateway) refreshAnonymousTier(ctx context.Context, base string) []string { + cursor := g.anonymous.CursorFor("") + limit := min(g.cfg.Retry.MaxAttempts, g.anonymous.Len()) + for attempt := 1; attempt <= limit; attempt++ { + node := cursor.Next() + if node == nil { + break + } + refreshCtx, cancel := context.WithTimeout(ctx, 30*time.Second) + models, status, err := fetchModels(refreshCtx, node.proxy.client, base, anonymousZenKey) + g.syncProxyResult(refreshCtx, node.proxy, status, err) + cancel() + if err == nil { + g.anonymous.MarkSuccess(node) + 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", redactURL(base), "attempt", attempt, "proxy", redactURL(node.proxy.name), "error", err) + } + g.logger.Warn("anonymous model catalog refresh failed", "component", "models", "event", "anonymous_refresh_failed", "upstream", 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++ { diff --git a/models.go b/models.go index 77b70d5..099ade4 100644 --- a/models.go +++ b/models.go @@ -33,9 +33,10 @@ const ( ) type modelRoute struct { - ID string - Tier Tier - Protocol Protocol + ID string + Tier Tier + Protocol Protocol + Anonymous bool } type modelCatalog struct { @@ -95,13 +96,18 @@ func (c *modelCatalog) CopyState(source *modelCatalog) { c.mu.Unlock() } -func (c *modelCatalog) Route(model string, hasZenKeys, hasGoKeys bool) (modelRoute, error) { +func (c *modelCatalog) Route(model string, hasZenKeys, hasGoKeys, hasAnonymous bool) (modelRoute, error) { c.mu.RLock() defer c.mu.RUnlock() protocol := c.protocols[model] if protocol == "" { protocol = inferProtocol(model) } + // OpenCode's public credential is a Zen-only lane. Prefer it for free + // models that are known to Zen, or while the initial catalog is pending. + if hasAnonymous && isFreeModel(model) && (c.zen[model] || len(c.zen) == 0 && len(c.goModels) == 0) { + return modelRoute{ID: model, Tier: TierZen, Protocol: protocol, Anonymous: true}, nil + } // When a model exists on both tiers, honor the configured priority. preferGo := c.prefer == TierGo if preferGo && c.goModels[model] && hasGoKeys { @@ -128,6 +134,10 @@ func (c *modelCatalog) Route(model string, hasZenKeys, hasGoKeys bool) (modelRou return modelRoute{}, fmt.Errorf("model %q is not available in the configured Zen or Go pools", model) } +func isFreeModel(model string) bool { + return strings.Contains(strings.ToLower(model), "free") +} + func (c *modelCatalog) List() []string { c.mu.RLock() defer c.mu.RUnlock() diff --git a/pool.go b/pool.go index 90830c6..91ada8e 100644 --- a/pool.go +++ b/pool.go @@ -30,6 +30,102 @@ type transportPool struct { items []*proxyTransport } +// 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. +type anonymousPool struct { + nodes []*anonymousNode + next atomic.Uint64 + cooldown time.Duration +} + +type anonymousNode struct { + proxy *proxyTransport + failures atomic.Uint32 + cooldownUntil atomic.Int64 +} + +type anonymousCursor struct { + pool *anonymousPool + start int + offset int +} + +func newAnonymousPool(enabled bool, transports *transportPool, cooldown time.Duration) *anonymousPool { + pool := &anonymousPool{cooldown: cooldown} + if !enabled || transports == nil { + return pool + } + pool.nodes = make([]*anonymousNode, 0, len(transports.items)) + for _, proxy := range transports.items { + pool.nodes = append(pool.nodes, &anonymousNode{proxy: proxy}) + } + return pool +} + +func (p *anonymousPool) Len() int { + if p == nil { + return 0 + } + return len(p.nodes) +} + +func (p *anonymousPool) CursorFor(affinity string) anonymousCursor { + if p == nil || len(p.nodes) == 0 { + return anonymousCursor{pool: p} + } + start := 0 + if affinity == "" { + start = int((p.next.Add(1) - 1) % uint64(len(p.nodes))) + } else { + hash := fnv.New64a() + _, _ = hash.Write([]byte(affinity)) + start = int(hash.Sum64() % uint64(len(p.nodes))) + } + return anonymousCursor{pool: p, start: start} +} + +// Next visits each healthy, non-cooling proxy at most once per cursor. +func (c *anonymousCursor) Next() *anonymousNode { + if c.pool == nil || len(c.pool.nodes) == 0 { + return nil + } + now := time.Now().UnixNano() + for c.offset < len(c.pool.nodes) { + node := c.pool.nodes[(c.start+c.offset)%len(c.pool.nodes)] + c.offset++ + if node.proxy.healthy.Load() && node.cooldownUntil.Load() <= now { + return node + } + } + return nil +} + +func (p *anonymousPool) MarkSuccess(node *anonymousNode) { + if node == nil { + return + } + node.failures.Store(0) + node.cooldownUntil.Store(0) +} + +func (p *anonymousPool) MarkFailure(node *anonymousNode, resp *http.Response, err error) { + if node == nil { + return + } + 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) + delay := p.cooldown * time.Duration(1< delay { + delay = retryAfter + } + } + node.cooldownUntil.Store(time.Now().Add(delay).UnixNano()) +} + func (p *transportPool) hasHealthy() bool { for _, proxy := range p.items { if proxy.healthy.Load() { diff --git a/runtime.go b/runtime.go index 552951b..3904186 100644 --- a/runtime.go +++ b/runtime.go @@ -220,9 +220,10 @@ func (m *RuntimeManager) Shutdown() { } type ResourceSnapshot struct { - Models modelCatalogSnapshot `json:"models"` - Keys []KeyStatus `json:"keys"` - Proxies []ProxyStatus `json:"proxies"` + Models modelCatalogSnapshot `json:"models"` + Keys []KeyStatus `json:"keys"` + Proxies []ProxyStatus `json:"proxies"` + Anonymous bool `json:"anonymous"` } type KeyStatus struct { @@ -235,12 +236,13 @@ type KeyStatus struct { } 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"` + 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 { @@ -249,7 +251,7 @@ func (m *RuntimeManager) Resources() ResourceSnapshot { return ResourceSnapshot{} } gateway := runtime.gateway - result := ResourceSnapshot{Models: gateway.catalog.Snapshot()} + result := ResourceSnapshot{Models: gateway.catalog.Snapshot(), Anonymous: gateway.cfg.Anonymous} result.Keys = append(result.Keys, keyStatuses("zen", gateway.zenNodes)...) result.Keys = append(result.Keys, keyStatuses("go", gateway.goNodes)...) gateway.zenNodes.bindingsMu.Lock() @@ -259,7 +261,7 @@ func (m *RuntimeManager) Resources() ResourceSnapshot { goBindings := append([]int(nil), gateway.goNodes.bindingCount...) gateway.goNodes.bindingsMu.Unlock() for _, proxy := range gateway.transports.items { - status := ProxyStatus{Index: proxy.index, Address: redactURL(proxy.name), Healthy: proxy.healthy.Load(), Checking: proxy.checking.Load()} + status := ProxyStatus{Index: proxy.index, Address: 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] } diff --git a/webui/index.html b/webui/index.html index 0f06c7a..d6ffa45 100644 --- a/webui/index.html +++ b/webui/index.html @@ -32,7 +32,7 @@