From c4c1f36d61251223bc135673f4fddf8293528f2c Mon Sep 17 00:00:00 2001 From: Jason Xu Date: Sun, 23 Aug 2026 22:06:27 +0800 Subject: [PATCH] fix: sync OpenCode model capabilities dynamically --- README.md | 10 +- admin.go | 35 ++++- config.go | 8 + gateway.go | 154 +++++++++++++++---- ids.go | 22 ++- models.go | 380 ++++++++++++++++++++++++++++++++++++++++++----- observability.go | 4 +- runtime.go | 3 - 8 files changed, 526 insertions(+), 90 deletions(-) diff --git a/README.md b/README.md index 8e5c29d..ae2371d 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,7 @@ - 支持文本、图片、thinking/reasoning、工具定义、工具调用和工具结果转换 - 分离配置 Zen key 池与 Zen Go key 池 - 支持无需上游 key 的 Zen 匿名模式,免费模型先走匿名通道,失败后按 `prefer` 顺序回退 Zen/Go key +- 按配置周期同步 Zen/Go `/v1/models`,并从 OpenCode `models.opencode.ai/api.json` 自动同步每个 Tier 的原生协议与不支持模型;不把模型 ID 硬编码在程序中 - 每 24 小时从 models.dev 更新 OpenCode 成本与弃用信息;models.dev 零成本或名称含 `free` 任一条件即可判定免费 - 模型同时存在于两个上游时按 `prefer` 配置排列 Go/Zen key 的首选与回退顺序(默认 Go) - 支持直连、HTTP、HTTPS、SOCKS5 和 SOCKS5H 代理 @@ -305,8 +306,8 @@ socks5://127.0.0.1:1080 # 备用代理 | 字段 | 含义 | | --- | --- | -| `models.refresh_seconds` | 重新读取 Zen 和 Go 模型列表的间隔秒数。两个列表会并发刷新。 | -| `models.protocols` | 手动指定模型的原生协议。值只能是 `chat`、`responses` 或 `anthropic`。通常保持为空。 | +| `models.refresh_seconds` | 重新读取 Zen 和 Go 模型列表及 OpenCode 能力目录的间隔秒数。两个模型列表与能力目录会并发刷新。 | +| `models.protocols` | 手动指定模型的原生协议。值只能是 `chat`、`responses` 或 `anthropic`,并覆盖自动同步结果。通常保持为空。 | 模型协议覆盖示例: @@ -317,6 +318,8 @@ 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` 可用于上游实验模型。 + 模型同时存在于 Zen 与 Go 时按 `prefer` 配置排列认证 Key 顺序:值为 `go` 时先 Go 后 Zen,值为 `zen` 时先 Zen 后 Go(默认 `go`)。首选 Tier 失败后才回退另一 Tier;仅存在于某一池时只使用该池的 key。免费模型在这条认证顺序之前额外尝试匿名 Zen。 ### Thinking 工具历史兼容 @@ -370,9 +373,10 @@ keys、proxy、上游、重试、模型、性能、优先 tier 和日志级别 代理会为上游添加 OpenCode 使用的 `User-Agent`、`x-opencode-client`、`x-opencode-session`、`x-opencode-request` 和 `x-opencode-project` 请求头。 - 每个请求使用不同的 `x-opencode-request`,同一次请求的重试保持不变。 -- 优先使用客户端提供的 `x-opencode-session`、`x-session-id`、`conversation-id`、`conversation_id` 或 `metadata.session_id` 生成会话 ID。 +- 优先使用客户端提供的 `x-opencode-session`、`x-session-affinity`、`X-Session-Id`、`x-session-id`、`conversation-id`、`conversation_id` 或 `metadata.session_id` 生成会话 ID。 - 没有显式会话标识时,使用第一条用户消息生成稳定会话 ID,使同一段多轮对话保持一致。 - 如果两个独立会话的第一条消息完全相同,建议由客户端发送不同的 `x-session-id`,以确保两个会话严格分离。 +- 上游请求同时发送 `x-session-affinity`、`X-Session-Id` 和可选的 `x-parent-session-id`,以兼容 OpenCode 近期的会话关联要求。 ## 致谢 diff --git a/admin.go b/admin.go index 140b7f2..37574d0 100644 --- a/admin.go +++ b/admin.go @@ -105,6 +105,8 @@ func (a *AdminServer) securityHeaders(next http.Handler) http.Handler { 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) }) } @@ -151,7 +153,7 @@ func (a *AdminServer) handleLogin(w http.ResponseWriter, r *http.Request) { } a.sessions[tokenDigest(token)] = adminSession{Username: cfg.WebUI.Username, AuthVersion: secretFingerprint(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: false}) + 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) writeJSON(w, http.StatusOK, map[string]any{"username": cfg.WebUI.Username, "csrf_token": csrf, "expires_at": expires.UTC()}) @@ -170,7 +172,7 @@ func (a *AdminServer) handleLogout(w http.ResponseWriter, r *http.Request) { 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}) + http.SetCookie(w, &http.Cookie{Name: adminCookieName, Value: "", Path: "/", HttpOnly: true, SameSite: http.SameSiteStrictMode, MaxAge: -1, Secure: requestIsSecure(r)}) w.WriteHeader(http.StatusNoContent) } @@ -219,7 +221,11 @@ func (a *AdminServer) csrf(next http.Handler) http.Handler { } if origin := r.Header.Get("Origin"); origin != "" { parsed, err := url.Parse(origin) - if err != nil || !strings.EqualFold(parsed.Host, r.Host) { + 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 } @@ -388,7 +394,7 @@ func (a *AdminServer) handleAccount(w http.ResponseWriter, r *http.Request) { 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}) + 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)) writeJSON(w, http.StatusOK, map[string]any{"updated": true, "reauthenticate": true}) } @@ -528,7 +534,7 @@ func sanitizeDebugValue(value any, redactor *SecretRedactor) any { result := make(map[string]any, len(current)) for key, item := range current { lower := strings.ToLower(key) - if strings.Contains(lower, "authorization") || strings.Contains(lower, "cookie") || strings.Contains(lower, "password") || strings.Contains(lower, "secret") || strings.Contains(lower, "api_key") || strings.Contains(lower, "api-key") { + if sensitiveDebugKey(lower) { result[key] = "***" continue } @@ -776,6 +782,25 @@ func clientIP(r *http.Request) string { 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") +} + +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 +} + func decodeAdminJSON(w http.ResponseWriter, r *http.Request, target any) error { decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 2<<20)) decoder.DisallowUnknownFields() diff --git a/config.go b/config.go index be50ab7..6cca957 100644 --- a/config.go +++ b/config.go @@ -117,6 +117,14 @@ func NormalizeConfig(path string, cfg Config) (Config, error) { 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) + for name, raw := range map[string]string{"upstream.zen": cfg.Upstream.Zen, "upstream.go": cfg.Upstream.Go} { + 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) + } + } if len(cfg.ServerKeys) == 0 { return Config{}, errors.New("server_keys must contain at least one local key") } diff --git a/gateway.go b/gateway.go index 3582092..cfca461 100644 --- a/gateway.go +++ b/gateway.go @@ -198,10 +198,10 @@ func (g *Gateway) handleModels(w http.ResponseWriter, _ *http.Request) { models := g.catalog.List() data := make([]map[string]any, 0, len(models)) for _, model := range models { - if !supportedModel(model) { + if g.cfg.Anonymous && len(g.cfg.ZenKeys) == 0 && len(g.cfg.GoKeys) == 0 && !g.catalog.anonymousDecision(model).Allowed { continue } - if g.cfg.Anonymous && len(g.cfg.ZenKeys) == 0 && len(g.cfg.GoKeys) == 0 && !g.catalog.anonymousDecision(model).Allowed { + if _, err := g.catalog.Route(model, len(g.cfg.ZenKeys) > 0, len(g.cfg.GoKeys) > 0, g.cfg.Anonymous); err != nil { continue } data = append(data, map[string]any{"id": model, "object": "model", "created": now, "owned_by": "opencode"}) @@ -230,7 +230,7 @@ func (g *Gateway) handleInference(external Protocol) http.HandlerFunc { writeAPIError(w, external, http.StatusBadRequest, "model is required", "invalid_request_error", "model") return } - if !supportedModel(model) { + if !g.catalog.Supported(model) { writeAPIError(w, external, http.StatusBadRequest, "the model uses an upstream protocol that opencode2api does not expose", "invalid_request_error", "model") return } @@ -242,20 +242,11 @@ func (g *Gateway) handleInference(external Protocol) http.HandlerFunc { if meta != nil { meta.Tier = string(route.Tier) } - upstreamURL := g.cfg.Upstream.Zen - if route.Tier == TierGo { - upstreamURL = g.cfg.Upstream.Go - } - upstreamPayload, err := prepareUpstreamRequest(external, route.Protocol, payload, upstreamURL) + bodies, err := g.prepareRouteBodies(external, route, payload) if err != nil { writeAPIError(w, external, http.StatusBadRequest, err.Error(), "invalid_request_error", "") return } - encoded, err := json.Marshal(upstreamPayload) - if err != nil { - writeAPIError(w, external, http.StatusBadRequest, "request contains unsupported JSON values", "invalid_request_error", "") - return - } ids := deriveRequestIDs(r, payload) if meta != nil { meta.Request = ids.Request @@ -263,7 +254,7 @@ func (g *Gateway) handleInference(external Protocol) http.HandlerFunc { stream := boolAt(payload, "stream") requestCtx, cancel := context.WithTimeout(r.Context(), time.Duration(g.cfg.Retry.TimeoutSeconds)*time.Second) defer cancel() - resp, err := g.doUpstream(requestCtx, route, encoded, ids) + resp, upstreamRoute, err := g.doUpstream(requestCtx, route, bodies, ids) if err != nil { finalTier := route.Tier if meta != nil && meta.Tier != "" { @@ -274,6 +265,9 @@ func (g *Gateway) handleInference(external Protocol) http.HandlerFunc { return } defer resp.Body.Close() + if meta != nil { + meta.Tier = string(upstreamRoute.Tier) + } w.Header().Set("x-request-id", ids.Request) if resp.StatusCode/100 != 2 { copyErrorResponse(w, external, resp, ids.Request) @@ -293,13 +287,13 @@ func (g *Gateway) handleInference(external Protocol) http.HandlerFunc { w.WriteHeader(resp.StatusCode) var usage bridgeUsage var usageReported bool - if external == route.Protocol { - observer := newStreamUsageObserver(route.Protocol) + if external == upstreamRoute.Protocol { + observer := newStreamUsageObserver(upstreamRoute.Protocol) _, err = io.Copy(w, io.TeeReader(resp.Body, observer)) usage = observer.Finish() usageReported = observer.Reported() } else { - usage, usageReported, err = transcodeStreamWithUsage(w, resp.Body, route.Protocol, external, model) + usage, usageReported, err = transcodeStreamWithUsage(w, resp.Body, upstreamRoute.Protocol, external, model) } if meta != nil { meta.Usage, meta.UsageReported = usage, usageReported @@ -314,13 +308,13 @@ func (g *Gateway) handleInference(external Protocol) http.HandlerFunc { writeAPIError(w, external, http.StatusBadGateway, "failed to read upstream response", "upstream_error", ids.Request) return } - if usage, reported := extractResponseUsage(route.Protocol, responseBody); meta != nil { + if usage, reported := extractResponseUsage(upstreamRoute.Protocol, responseBody); meta != nil { meta.Usage, meta.UsageReported = usage, reported } - if external != route.Protocol { - responseBody, err = convertResponse(route.Protocol, external, responseBody) + if external != upstreamRoute.Protocol { + responseBody, err = convertResponse(upstreamRoute.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", route.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", upstreamRoute.Protocol, "target_protocol", external, "error", err) writeAPIError(w, external, http.StatusBadGateway, "unsupported upstream response", "upstream_error", ids.Request) return } @@ -331,15 +325,60 @@ func (g *Gateway) handleInference(external Protocol) http.HandlerFunc { } } -func (g *Gateway) doUpstream(ctx context.Context, route modelRoute, body []byte, ids requestIDs) (*http.Response, error) { +func (g *Gateway) prepareRouteBodies(from Protocol, route modelRoute, input map[string]any) (map[Tier][]byte, error) { + tiers := make([]Tier, 0, len(route.KeyTiers)+1) + seen := make(map[Tier]bool, len(route.KeyTiers)+1) + addTier := func(tier Tier) { + if tier != TierZen && tier != TierGo || seen[tier] { + return + } + seen[tier] = true + tiers = append(tiers, tier) + } + addTier(route.Tier) + for _, tier := range route.KeyTiers { + addTier(tier) + } + if len(tiers) == 0 { + return nil, errors.New("no usable upstream tier") + } + bodies := make(map[Tier][]byte, len(tiers)) + for _, tier := range tiers { + protocol := route.ProtocolFor(tier) + baseURL := g.cfg.Upstream.Zen + if tier == TierGo { + baseURL = g.cfg.Upstream.Go + } + upstreamPayload, err := prepareUpstreamRequest(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. + continue + } + return nil, fmt.Errorf("prepare %s upstream request: %w", tier, err) + } + encoded, err := json.Marshal(upstreamPayload) + if err != nil { + return nil, errors.New("request contains unsupported JSON values") + } + bodies[tier] = encoded + } + return bodies, nil +} + +func (g *Gateway) doUpstream(ctx context.Context, route modelRoute, bodies map[Tier][]byte, ids requestIDs) (*http.Response, modelRoute, error) { var lastResponse *http.Response var lastErr error + effectiveRoute := route attempts := 0 if route.Anonymous { - resp, err, used := g.doAnonymousUpstream(ctx, route, body, ids) + resp, err, used := g.doAnonymousUpstream(ctx, route, bodies, ids) attempts += used if err == nil && resp != nil && resp.StatusCode/100 == 2 { - return resp, nil + return resp, route, nil } lastResponse, lastErr = resp, err if len(route.KeyTiers) > 0 { @@ -359,32 +398,38 @@ func (g *Gateway) doUpstream(ctx context.Context, route modelRoute, body []byte, keyRoute := route keyRoute.Tier = tier keyRoute.Anonymous = false - resp, err, used := g.doKeyUpstream(ctx, keyRoute, body, ids, attempts) + 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 { - return resp, nil + return resp, keyRoute, nil } lastResponse, lastErr = resp, err } if lastResponse != nil { - return lastResponse, nil + return lastResponse, effectiveRoute, nil } if lastErr == nil { lastErr = errors.New("no usable upstream route") } - return nil, lastErr + return nil, effectiveRoute, lastErr } // doAnonymousUpstream tries every currently available proxy at most once. Any // failure, including an HTTP error response, advances to the next 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 modelRoute, body []byte, ids requestIDs) (*http.Response, error, int) { +func (g *Gateway) doAnonymousUpstream(ctx context.Context, route modelRoute, bodies map[Tier][]byte, ids requestIDs) (*http.Response, error, int) { var lastResponse *http.Response var lastErr error cursor := g.anonymous.CursorFor(ids.Session) limit := g.anonymous.Len() attempts := 0 + body := bodies[TierZen] + if len(body) == 0 { + return nil, errors.New("no prepared Zen request body"), 0 + } for attempts < limit { node := cursor.Next() if node == nil { @@ -435,7 +480,7 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route modelRoute, bod return nil, lastErr, attempts } -func (g *Gateway) doKeyUpstream(ctx context.Context, route modelRoute, body []byte, ids requestIDs, attemptOffset int) (*http.Response, error, int) { +func (g *Gateway) doKeyUpstream(ctx context.Context, route modelRoute, bodies map[Tier][]byte, ids requestIDs, attemptOffset int) (*http.Response, error, int) { var lastResponse *http.Response var lastErr error nodes := g.zenNodes @@ -449,6 +494,10 @@ func (g *Gateway) doKeyUpstream(ctx context.Context, route modelRoute, body []by 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 + } for attempts < g.cfg.Retry.MaxAttempts { node := cursor.Next() if node == nil { @@ -572,11 +621,20 @@ func newUpstreamRequest(ctx context.Context, baseURL string, protocol Protocol, req.Header.Set("User-Agent", opencodeUserAgent()) req.Header.Set("x-opencode-client", "cli") req.Header.Set("x-opencode-session", ids.Session) + // OpenCode 1.18.x sends these correlation headers to preserve provider-side + // prompt/session affinity. Keep the legacy x-opencode-session header too so + // older Zen deployments continue to recognize the request. + req.Header.Set("x-session-affinity", ids.Session) + req.Header.Set("X-Session-Id", ids.Session) req.Header.Set("x-opencode-request", ids.Request) req.Header.Set("x-opencode-project", ids.Project) + if ids.ParentSession != "" { + req.Header.Set("x-parent-session-id", ids.ParentSession) + } if protocol == ProtocolAnthropic { req.Header.Set("x-api-key", key) 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 { req.Header.Set("Authorization", "Bearer "+key) } @@ -715,13 +773,24 @@ func protocolPath(protocol Protocol) string { func (g *Gateway) StartModelRefresh(ctx context.Context) { refresh := func() { var zen, goModels []string + var capabilities protocolCapabilities + var capabilitiesErr error var wg sync.WaitGroup - wg.Add(2) + 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) }() + go func() { + defer wg.Done() + capabilityCtx, cancel := context.WithTimeout(ctx, 30*time.Second) + defer cancel() + capabilities, capabilitiesErr = g.refreshProtocolCapabilities(capabilityCtx) + }() wg.Wait() + 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.Replace(zen, goModels) + g.catalog.ReplaceWithCapabilities(zen, goModels, capabilities.Protocols, capabilities.Unsupported) g.logger.Info("model catalog refreshed", "component", "models", "event", "catalog_refreshed", "models", len(g.catalog.List())) } } @@ -740,6 +809,27 @@ func (g *Gateway) StartModelRefresh(ctx context.Context) { }() } +func (g *Gateway) refreshProtocolCapabilities(ctx context.Context) (protocolCapabilities, error) { + if g.transports == nil || len(g.transports.items) == 0 { + return fetchProtocolCapabilities(ctx, &http.Client{Timeout: 30 * time.Second}, openCodeCapabilitiesURL) + } + var lastErr error + for _, proxy := range g.transports.items { + if proxy == nil || !proxy.healthy.Load() { + continue + } + capabilities, err := fetchProtocolCapabilities(ctx, proxy.client, openCodeCapabilitiesURL) + if err == nil { + return capabilities, nil + } + lastErr = err + } + if lastErr == nil { + lastErr = errors.New("no healthy proxy available for OpenCode capability catalog") + } + return protocolCapabilities{}, lastErr +} + func (g *Gateway) refreshZen(ctx context.Context) []string { if models := g.refreshTier(ctx, g.cfg.Upstream.Zen, g.zenNodes); models != nil { return models diff --git a/ids.go b/ids.go index f86f508..e6485bb 100644 --- a/ids.go +++ b/ids.go @@ -12,14 +12,17 @@ import ( ) type requestIDs struct { - Session string - Request string - Project string + Session string + Request string + Project string + ParentSession string } func deriveRequestIDs(r *http.Request, body map[string]any) requestIDs { signal := firstString( r.Header.Get("x-opencode-session"), + r.Header.Get("x-session-affinity"), + r.Header.Get("X-Session-Id"), r.Header.Get("x-session-id"), r.Header.Get("conversation-id"), stringAt(body, "conversation_id"), @@ -41,10 +44,15 @@ func deriveRequestIDs(r *http.Request, body map[string]any) requestIDs { if projectSignal == "" { projectSignal = "opencode2api:default-project" } + parentSession := firstString( + r.Header.Get("x-parent-session-id"), + stringAt(body, "metadata", "parent_session_id"), + ) return requestIDs{ - Session: session, - Request: randomID("req", 16), - Project: stableID("prj", projectSignal), + Session: session, + Request: randomID("req", 16), + Project: stableID("prj", projectSignal), + ParentSession: parentSession, } } @@ -90,5 +98,5 @@ func firstString(values ...string) string { } func opencodeUserAgent() string { - return fmt.Sprintf("opencode/1.18.18 (%s %s; %s)", runtime.GOOS, runtime.GOARCH, runtime.Version()) + return fmt.Sprintf("opencode/1.18.21 (%s %s; %s)", runtime.GOOS, runtime.GOARCH, runtime.Version()) } diff --git a/models.go b/models.go index 28e9ad0..93a0e0f 100644 --- a/models.go +++ b/models.go @@ -7,6 +7,7 @@ import ( "fmt" "io" "net/http" + "regexp" "sort" "strings" "sync" @@ -21,6 +22,14 @@ const ( ProtocolAnthropic Protocol = "anthropic" ) +const ( + openCodeCapabilitiesURL = "https://models.opencode.ai/api.json" + openCodeZenDocsURL = "https://raw.githubusercontent.com/anomalyco/opencode/dev/packages/web/src/content/docs/zen.mdx" + openCodeGoDocsURL = "https://raw.githubusercontent.com/anomalyco/opencode/dev/packages/web/src/content/docs/go.mdx" +) + +var protocolDocEndpointPattern = regexp.MustCompile("\\|[^|]+\\|\\s*`?([^|`\\s]+)`?\\s*\\|\\s*`[^`]+/v1/(chat/completions|responses|messages)`") + func validProtocol(p Protocol) bool { return p == ProtocolChat || p == ProtocolResponses || p == ProtocolAnthropic } @@ -33,9 +42,15 @@ const ( ) type modelRoute struct { - ID string - Tier Tier - Protocol Protocol + ID string + Tier Tier + Protocol 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[Tier]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 @@ -47,6 +62,7 @@ type ModelRouteDiagnostic struct { Model string `json:"model"` RequestedProtocol Protocol `json:"requested_protocol,omitempty"` NativeProtocol Protocol `json:"native_protocol"` + NativeProtocols map[Tier]Protocol `json:"native_protocols,omitempty"` ProtocolSource string `json:"protocol_source"` AvailableZen bool `json:"available_zen"` AvailableGo bool `json:"available_go"` @@ -62,9 +78,13 @@ type modelCatalog struct { zen map[string]bool goModels map[string]bool protocols map[string]Protocol - updatedAt time.Time - prefer Tier - metadata *modelMetadataStore + // nativeProtocols is populated from OpenCode's public model capability + // catalog. protocols remains the user-configured override map. + nativeProtocols map[Tier]map[string]Protocol + unsupported map[Tier]map[string]bool + updatedAt time.Time + prefer Tier + metadata *modelMetadataStore } type modelCatalogSnapshot struct { @@ -80,10 +100,18 @@ func newModelCatalog(prefer Tier, overrides map[string]string) *modelCatalog { for model, protocol := range overrides { protocols[model] = Protocol(protocol) } - return &modelCatalog{zen: map[string]bool{}, goModels: map[string]bool{}, protocols: protocols, prefer: prefer} + return &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, + } } func (c *modelCatalog) Replace(zen, goModels []string) { + c.ReplaceWithCapabilities(zen, goModels, nil, nil) +} + +func (c *modelCatalog) ReplaceWithCapabilities(zen, goModels []string, native map[Tier]map[string]Protocol, unsupported map[Tier]map[string]bool) { c.mu.Lock() defer c.mu.Unlock() if zen != nil { @@ -92,6 +120,20 @@ func (c *modelCatalog) Replace(zen, goModels []string) { if goModels != nil { c.goModels = toSet(goModels) } + if native != nil { + for _, tier := range []Tier{TierZen, TierGo} { + if protocols, ok := native[tier]; ok { + c.nativeProtocols[tier] = cloneProtocols(protocols) + } + } + } + if unsupported != nil { + for _, tier := range []Tier{TierZen, TierGo} { + if models, ok := unsupported[tier]; ok { + c.unsupported[tier] = cloneBools(models) + } + } + } c.updatedAt = time.Now() } @@ -108,34 +150,74 @@ func (c *modelCatalog) CopyState(source *modelCatalog) { for model, available := range source.goModels { goModels[model] = available } + native := map[Tier]map[string]Protocol{TierZen: {}, TierGo: {}} + unsupported := map[Tier]map[string]bool{TierZen: {}, TierGo: {}} + for _, tier := range []Tier{TierZen, TierGo} { + for model, protocol := range source.nativeProtocols[tier] { + native[tier][model] = protocol + } + for model, value := range source.unsupported[tier] { + unsupported[tier][model] = value + } + } updatedAt := source.updatedAt source.mu.RUnlock() c.mu.Lock() - c.zen, c.goModels, c.updatedAt = zen, goModels, updatedAt + c.zen, c.goModels, c.nativeProtocols, c.unsupported, c.updatedAt = zen, goModels, native, unsupported, updatedAt c.mu.Unlock() } 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) - } 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 { - return modelRoute{ID: model, Tier: TierZen, Protocol: protocol, Anonymous: true, KeyTiers: keyTiers}, nil + if hasAnonymous && decision.Allowed && (c.protocols[model] != "" || !c.unsupported[TierZen][model]) && + (len(c.zen) == 0 && len(c.goModels) == 0 || c.zen[model] || c.goModels[model]) { + protocols := c.protocolsForLocked(model, keyTiers, true) + return modelRoute{ID: model, Tier: TierZen, Protocol: protocols[TierZen], Protocols: protocols, Anonymous: true, KeyTiers: keyTiers}, nil } if len(keyTiers) > 0 { - return modelRoute{ID: model, Tier: keyTiers[0], Protocol: protocol, KeyTiers: keyTiers}, nil + protocols := c.protocolsForLocked(model, keyTiers, false) + return modelRoute{ID: model, Tier: keyTiers[0], Protocol: protocols[keyTiers[0]], Protocols: protocols, KeyTiers: keyTiers}, nil } return modelRoute{}, fmt.Errorf("model %q is not available in the configured Zen or Go pools", model) } +func (r modelRoute) ProtocolFor(tier Tier) Protocol { + if protocol := r.Protocols[tier]; protocol != "" { + return protocol + } + return r.Protocol +} + +func (c *modelCatalog) protocolsForLocked(model string, keyTiers []Tier, includeZen bool) map[Tier]Protocol { + protocols := make(map[Tier]Protocol, len(keyTiers)+1) + if includeZen { + protocols[TierZen] = c.protocolForLocked(model, TierZen) + } + for _, tier := range keyTiers { + protocols[tier] = c.protocolForLocked(model, tier) + } + return protocols +} + +func (c *modelCatalog) protocolForLocked(model string, tier Tier) 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 ProtocolChat +} + // 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 @@ -145,9 +227,9 @@ func (c *modelCatalog) keyTierOrderLocked(model string, hasZenKeys, hasGoKeys bo available := func(tier Tier) bool { switch tier { case TierZen: - return hasZenKeys && (catalogPending || c.zen[model]) + return hasZenKeys && (catalogPending || c.zen[model]) && c.tierSupportedLocked(model, TierZen) case TierGo: - return hasGoKeys && (catalogPending || c.goModels[model]) + return hasGoKeys && (catalogPending || c.goModels[model]) && c.tierSupportedLocked(model, TierGo) default: return false } @@ -174,16 +256,33 @@ func (c *modelCatalog) anonymousDecision(model string) AnonymousDecision { func (c *modelCatalog) Diagnostic(model string, requested Protocol, hasZenKeys, hasGoKeys, hasAnonymous bool) ModelRouteDiagnostic { c.mu.RLock() - protocol, explicit := c.protocols[model] + configured, explicit := c.protocols[model] zen, goModel := c.zen[model], c.goModels[model] + nativeProtocols := map[Tier]Protocol{ + TierZen: c.protocolForLocked(model, TierZen), + TierGo: c.protocolForLocked(model, TierGo), + } + _, zenKnown := c.nativeProtocols[TierZen][model] + _, goKnown := c.nativeProtocols[TierGo][model] c.mu.RUnlock() source := "configured" if !explicit { - protocol = inferProtocol(model) - source = "inferred" + 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[TierZen] + if c.prefer == TierGo { + protocol = nativeProtocols[TierGo] + } } diagnostic := ModelRouteDiagnostic{ - Model: model, RequestedProtocol: requested, NativeProtocol: protocol, ProtocolSource: source, + 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) @@ -191,6 +290,8 @@ func (c *modelCatalog) Diagnostic(model string, requested Protocol, hasZenKeys, 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([]Tier(nil), route.KeyTiers...) return diagnostic @@ -212,7 +313,9 @@ func (c *modelCatalog) List() []string { } models := make([]string, 0, len(seen)) for model := range seen { - models = append(models, model) + if c.supportedLocked(model) { + models = append(models, model) + } } sort.Strings(models) return models @@ -230,7 +333,7 @@ func (c *modelCatalog) Snapshot() modelCatalogSnapshot { } exposed := 0 for model := range seen { - if supportedModel(model) { + if c.supportedLocked(model) { exposed++ } } @@ -243,6 +346,40 @@ func (c *modelCatalog) Snapshot() modelCatalogSnapshot { } } +func (c *modelCatalog) Supported(model string) bool { + c.mu.RLock() + defer c.mu.RUnlock() + return c.supportedLocked(model) +} + +func (c *modelCatalog) supportedLocked(model string) bool { + if len(c.zen) == 0 && len(c.goModels) == 0 { + return true + } + if c.zen[model] && c.tierSupportedLocked(model, TierZen) { + return true + } + if c.goModels[model] && c.tierSupportedLocked(model, TierGo) { + return true + } + return false +} + +func (c *modelCatalog) tierSupportedLocked(model string, tier 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 { @@ -251,24 +388,191 @@ func toSet(items []string) map[string]bool { return out } -func inferProtocol(model string) Protocol { - m := strings.ToLower(model) - for _, prefix := range []string{"claude-", "qwen"} { - if strings.HasPrefix(m, prefix) { - return ProtocolAnthropic - } +func cloneProtocols(source map[string]Protocol) map[string]Protocol { + result := make(map[string]Protocol, len(source)) + for model, protocol := range source { + result[model] = protocol } - for _, prefix := range []string{"gpt-", "o1", "o3", "o4", "grok-", "muse-"} { - if strings.HasPrefix(m, prefix) { - return ProtocolResponses - } - } - return ProtocolChat + return result } -func supportedModel(model string) bool { - m := strings.ToLower(model) - return !strings.HasPrefix(m, "gemini-") +func cloneBools(source map[string]bool) map[string]bool { + result := make(map[string]bool, len(source)) + for model, value := range source { + result[model] = value + } + return result +} + +type protocolCapabilities struct { + Protocols map[Tier]map[string]Protocol + Unsupported map[Tier]map[string]bool +} + +type capabilityProvider struct { + ID string `json:"id"` + API string `json:"api"` + NPM string `json:"npm"` + Models map[string]capabilityModel `json:"models"` +} + +type capabilityModel struct { + ID string `json:"id"` + Provider *capabilityModelProvider `json:"provider"` +} + +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 fetchProtocolCapabilities(ctx context.Context, client *http.Client, endpoint string) (protocolCapabilities, error) { + if client == nil { + client = http.DefaultClient + } + req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil) + if err != nil { + return protocolCapabilities{}, err + } + req.Header.Set("Accept", "application/json") + req.Header.Set("User-Agent", opencodeUserAgent()) + resp, err := client.Do(req) + if err != nil { + return protocolCapabilities{}, err + } + defer resp.Body.Close() + if resp.StatusCode/100 != 2 { + return protocolCapabilities{}, fmt.Errorf("OpenCode capability endpoint returned HTTP %d", resp.StatusCode) + } + var providers map[string]capabilityProvider + dec := json.NewDecoder(io.LimitReader(resp.Body, 64<<20)) + if err := dec.Decode(&providers); err != nil { + return protocolCapabilities{}, err + } + result := protocolCapabilities{ + Protocols: map[Tier]map[string]Protocol{TierZen: {}, TierGo: {}}, + Unsupported: map[Tier]map[string]bool{TierZen: {}, TierGo: {}}, + } + for providerID, provider := range providers { + tier, ok := capabilityTier(providerID, provider.API) + if !ok { + continue + } + for modelID, model := range provider.Models { + if model.ID != "" { + modelID = model.ID + } + npm := provider.NPM + if model.Provider != nil && model.Provider.NPM != "" { + npm = model.Provider.NPM + } + if protocol, ok := protocolForSDK(npm); ok { + result.Protocols[tier][modelID] = protocol + } else { + result.Unsupported[tier][modelID] = true + } + } + } + // 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 Tier + url string + }{ + {TierZen, openCodeZenDocsURL}, + {TierGo, openCodeGoDocsURL}, + } { + protocols, err := fetchProtocolDocs(ctx, client, doc.url) + if err != nil { + continue + } + for modelID, protocol := range protocols { + result.Protocols[doc.tier][modelID] = protocol + delete(result.Unsupported[doc.tier], modelID) + } + } + if len(result.Protocols[TierZen]) == 0 && len(result.Protocols[TierGo]) == 0 && len(result.Unsupported[TierZen]) == 0 && len(result.Unsupported[TierGo]) == 0 { + return protocolCapabilities{}, errors.New("OpenCode capability endpoint returned no Zen or Go models") + } + return result, nil +} + +func fetchProtocolDocs(ctx context.Context, client *http.Client, endpoint string) (map[string]Protocol, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil) + if err != nil { + return nil, err + } + req.Header.Set("Accept", "text/plain, text/markdown, */*") + req.Header.Set("User-Agent", opencodeUserAgent()) + resp, err := client.Do(req) + if err != nil { + return nil, err + } + defer resp.Body.Close() + if resp.StatusCode/100 != 2 { + return nil, fmt.Errorf("OpenCode endpoint documentation returned HTTP %d", resp.StatusCode) + } + body, err := io.ReadAll(io.LimitReader(resp.Body, 8<<20)) + if err != nil { + return nil, err + } + result := make(map[string]Protocol) + for _, line := range strings.Split(string(body), "\n") { + match := protocolDocEndpointPattern.FindStringSubmatch(line) + if len(match) != 3 { + continue + } + modelID := strings.TrimSpace(match[1]) + if modelID == "" || strings.ContainsAny(modelID, " `|") { + continue + } + var protocol Protocol + switch match[2] { + case "chat/completions": + protocol = ProtocolChat + case "responses": + protocol = ProtocolResponses + case "messages": + protocol = ProtocolAnthropic + } + if protocol != "" { + result[modelID] = protocol + } + } + if len(result) == 0 { + return nil, errors.New("OpenCode endpoint documentation returned no protocol rows") + } + return result, nil +} + +func capabilityTier(providerID, api string) (Tier, bool) { + value := strings.ToLower(strings.TrimSpace(providerID + " " + api)) + if strings.Contains(value, "opencode-go") || strings.Contains(value, "/go/") { + return TierGo, true + } + if strings.Contains(value, "opencode") || strings.Contains(value, "/zen/") { + return TierZen, true + } + return "", false +} + +func protocolForSDK(npm string) (Protocol, bool) { + value := strings.ToLower(strings.TrimSpace(npm)) + switch { + case strings.Contains(value, "anthropic"): + return ProtocolAnthropic, true + case value == "@ai-sdk/openai" || strings.HasSuffix(value, "/openai"): + return ProtocolResponses, true + case strings.Contains(value, "openai-compatible"): + return ProtocolChat, true + default: + return "", false + } } type modelsResponse struct { diff --git a/observability.go b/observability.go index dab5dc1..3388861 100644 --- a/observability.go +++ b/observability.go @@ -89,11 +89,11 @@ func (h *LogHub) Publish(event LogEvent) { } 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) } - h.mu.RLock() - defer h.mu.RUnlock() oldest := uint64(0) if h.count > 0 { oldest = h.buffer[h.start].Sequence diff --git a/runtime.go b/runtime.go index 6d2b07e..09578d9 100644 --- a/runtime.go +++ b/runtime.go @@ -290,9 +290,6 @@ func (m *RuntimeManager) DebugModels() ([]ModelRouteDiagnostic, MetadataSnapshot models := gateway.catalog.List() result := make([]ModelRouteDiagnostic, 0, len(models)) for _, model := range models { - if !supportedModel(model) { - continue - } result = append(result, gateway.catalog.Diagnostic(model, "", len(gateway.cfg.ZenKeys) > 0, len(gateway.cfg.GoKeys) > 0, gateway.cfg.Anonymous)) } metadata := MetadataSnapshot{}