From 9b44a031ca534ea54b6e22bdf76b71ccb1035013 Mon Sep 17 00:00:00 2001 From: Jason Xu Date: Mon, 30 Nov 2026 04:15:14 +0800 Subject: [PATCH] feat(models): add collision-safe aliases and model echoes (#125) --- README.md | 6 ++ README.zh-CN.md | 6 ++ config.example.json | 2 + internal/admin/server.go | 18 +++- internal/config/config.go | 16 +++- internal/config/model_alias.go | 65 ++++++++++++++ internal/gateway/alias.go | 115 +++++++++++++++++++++++++ internal/gateway/gateway.go | 47 +++++++---- internal/gateway/health.go | 9 +- internal/gateway/runtime.go | 12 +++ internal/protocol/model.go | 150 +++++++++++++++++++++++++++++++++ webui/index.html | 10 +++ webui/js/i18n.js | 6 ++ webui/js/pages/config.js | 4 + 14 files changed, 443 insertions(+), 23 deletions(-) create mode 100644 internal/config/model_alias.go create mode 100644 internal/gateway/alias.go create mode 100644 internal/protocol/model.go diff --git a/README.md b/README.md index 2cf2690..f79c587 100644 --- a/README.md +++ b/README.md @@ -156,6 +156,8 @@ The gateway does not implement embeddings, file uploads, image generation, or Re | `upstream.anonymous` | `https://opencode.ai/inference` for anonymous traffic. | | `models.refresh_seconds` | `300`; model discovery interval. | | `models.protocols` | Per-model native-protocol overrides: `chat`, `responses`, `anthropic`, or `systemone`. | +| `models.aliases` | `{}`; public model names mapped to upstream IDs. Discovery and responses use the requested alias; routing and metadata retain the upstream ID. | +| `models.strip_free_suffix` | `false`; automatically publish routable `*-free` models without `-free` when the name is not reserved or already a known upstream ID. | | `models.free_only` | `false`; filters both model discovery and routing to free models. | | `models.active_probes` | `false`; optional synthetic free-model inference probes. | | `reasoning.effort` | Unset in built-in defaults; the example sets `high`. | @@ -167,6 +169,10 @@ Discovery combines upstream model lists with the OpenCode capability and price c With manual keys, eligible free models can first use the anonymous lane when explicitly enabled, then the available keyed tiers in `prefer` order. Without anonymous access they use configured keys. Free eligibility comes from a case-insensitive `free` in the model ID or non-deprecated metadata with zero input and output cost; eligibility does not guarantee acceptance upstream. Paid models require an appropriate authenticated route. `models.free_only` also filters members of rotation groups. +Model aliases only change client-facing names. For example, `"models": {"strip_free_suffix": true, "aliases": {"beam-pro": "beam-free"}}` publishes `beam-pro` for `beam-free` and strips `-free` from other available models when safe. Explicit aliases take priority; if several aliases point to one model, discovery publishes the lexicographically first and accepts all of them. Requests using original upstream IDs remain supported and echo that original name. Chat, Responses, Anthropic and System One replies preserve the requested alias, including model fields nested in streaming events. Pricing, reasoning overrides, quota tracking and rotation members continue to use upstream IDs. + +Alias names and targets must be nonempty and must not use a rotation group alias. Alias chains and names that shadow another configured or known upstream ID are rejected when the configuration is validated. Automatic names never shadow upstream IDs, explicit aliases or rotation group aliases. If a later catalog refresh introduces an upstream ID that conflicts with a saved alias, the upstream ID takes priority and that conflicting alias is no longer published; rename the alias before applying the configuration again. Automatic aliases are available only after their target is discovered and routable. + OAuth routes follow separate rules: the selected OAuth tier owns the request, uses only its confirmed routes, and does not fall back to anonymous traffic, manual keys, or another tier after failure. Selecting Go OAuth never triggers a PAYG request on authorization failure, quota exhaustion, or 429. When both tiers serve a model, explicitly choosing `prefer: "zen"` permits the connected Zen PAYG route. ### Timeouts, proxies, and affinity diff --git a/README.zh-CN.md b/README.zh-CN.md index 767964c..f228a85 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -156,6 +156,8 @@ Responses 历史中的 assistant reasoning、文本和函数调用会合并为 a | `upstream.anonymous` | 匿名通道默认使用 `https://opencode.ai/inference`。 | | `models.refresh_seconds` | `300`;模型发现间隔。 | | `models.protocols` | 按模型覆盖原生协议:`chat`、`responses`、`anthropic`、`systemone`。 | +| `models.aliases` | `{}`;公开模型名到上游 ID 的映射,发现与响应使用别名,路由和元数据仍使用上游 ID。 | +| `models.strip_free_suffix` | `false`;自动去掉可路由模型的 `-free` 后缀,但不占用保留名或已知上游 ID。 | | `models.free_only` | `false`;发现与路由均仅允许免费模型。 | | `models.active_probes` | `false`;可选的免费模型合成推理探测。 | | `reasoning.effort` | 内置默认未设置;示例设为 `high`。 | @@ -167,6 +169,10 @@ Responses 历史中的 assistant reasoning、文本和函数调用会合并为 a 使用手动 Key 时,明确开启匿名后,符合条件的免费模型可先尝试匿名通道,再按 `prefer` 尝试可用 Key 池;匿名关闭时使用已配置 Key。模型 ID 不区分大小写包含 `free`,或元数据表明未弃用且输入/输出价格均为零,即可判为免费,但不保证上游接受。付费模型需要适当的认证通道。`models.free_only` 同时限制轮转组成员。 +模型别名只改变面向客户端的名称。例如 `"models": {"strip_free_suffix": true, "aliases": {"beam-pro": "beam-free"}}` 会把 `beam-free` 发布为 `beam-pro`,并在无冲突时为其他可用模型自动去掉 `-free`。手动别名优先;多个别名指向同一模型时,发现列表使用字典序最小的别名,所有别名均可请求。原始上游 ID 仍可使用,响应也保持该原始名称。Chat、Responses、Anthropic 和 System One 均回显请求别名,包括流式事件的嵌套模型字段。计价、思考强度覆盖、配额与轮转成员仍按上游 ID 处理。 + +别名和目标不能为空,也不能使用轮转组别名。别名链以及遮蔽另一已配置或已知上游 ID 的名称会在配置校验时被拒绝。自动名称不会占用上游 ID、手动别名或轮转组别名。若后续目录刷新引入与已保存别名重名的上游 ID,原始上游 ID 优先,该冲突别名不再发布;再次应用配置前需修改别名。自动别名仅在目标已发现且可路由后可用。 + OAuth 另有规则:请求选择 OAuth 路由后,只使用该 Tier 已确认的路由,不因失败改走匿名、手动 Key 或其他 Tier。Go OAuth 授权失败、额度耗尽或返回 429,均不会触发 PAYG 请求。两类通道都能服务同一模型时,明确选择 `prefer: "zen"` 允许使用已连接的 Zen PAYG 通道。 ### 超时、代理与会话亲和 diff --git a/config.example.json b/config.example.json index 731221b..10f726e 100644 --- a/config.example.json +++ b/config.example.json @@ -27,6 +27,8 @@ "models": { "refresh_seconds": 300, "protocols": {}, + "aliases": {}, + "strip_free_suffix": false, "free_only": false, "active_probes": false }, diff --git a/internal/admin/server.go b/internal/admin/server.go index c11e38e..86513c9 100644 --- a/internal/admin/server.go +++ b/internal/admin/server.go @@ -201,6 +201,12 @@ type SecretInput struct { Value string `json:"value,omitempty"` } +type ModelsUpdate struct { + config.ModelsConfig + Aliases *map[string]string `json:"aliases,omitempty"` + StripFreeSuffix *bool `json:"strip_free_suffix,omitempty"` +} + // ConfigUpdate is the body of PUT /api/config. Secrets carry either a new // value or the ID of the existing one. The WebUI username and password are // not changed here; they go through /api/account. @@ -217,7 +223,7 @@ type ConfigUpdate struct { ProxyBindings map[string]string `json:"proxy_bindings,omitempty"` Upstream config.UpstreamConfig `json:"upstream"` Retry config.RetryConfig `json:"retry"` - Models config.ModelsConfig `json:"models"` + Models ModelsUpdate `json:"models"` Performance config.PerformanceConfig `json:"performance"` Logging config.LoggingConfig `json:"logging"` Prefer config.Tier `json:"prefer"` @@ -280,7 +286,7 @@ func (a *Server) handlePutConfig(w http.ResponseWriter, r *http.Request) { Listen: update.Listen, ServerKeys: serverKeys, ZenKeys: zenKeys, GoKeys: goKeys, Anonymous: update.Anonymous, Warp: update.Warp, Proxies: proxies, ProxyFile: update.ProxyFile, ProxyBindings: proxyBindings, KeysDirect: current.KeysDirect, - Upstream: update.Upstream, Retry: update.Retry, Models: update.Models, Performance: update.Performance, Logging: update.Logging, Prefer: update.Prefer, + Upstream: update.Upstream, Retry: update.Retry, Models: update.Models.ModelsConfig, Performance: update.Performance, Logging: update.Logging, Prefer: update.Prefer, Reasoning: reasoning, WebUI: config.WebUIConfig{Enabled: update.WebUI.Enabled, Listen: update.WebUI.Listen, Username: current.WebUI.Username, PasswordHash: current.WebUI.PasswordHash, SessionTTLMinutes: update.WebUI.SessionTTLMinutes}, } @@ -296,6 +302,14 @@ func (a *Server) handlePutConfig(w http.ResponseWriter, r *http.Request) { if update.KeysDirect != nil { candidate.KeysDirect = *update.KeysDirect } + candidate.Models.Aliases = latest.Models.Aliases + if update.Models.Aliases != nil { + candidate.Models.Aliases = *update.Models.Aliases + } + candidate.Models.StripFreeSuffix = latest.Models.StripFreeSuffix + if update.Models.StripFreeSuffix != nil { + candidate.Models.StripFreeSuffix = *update.Models.StripFreeSuffix + } candidate.WebUI.Username = latest.WebUI.Username candidate.WebUI.PasswordHash = latest.WebUI.PasswordHash if update.Reasoning == nil { diff --git a/internal/config/config.go b/internal/config/config.go index 95e10af..9b971b1 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -192,8 +192,10 @@ type RetryConfig struct { // catalog refresh interval, and Protocols maps a model ID to the wire protocol // used upstream, overriding the one the catalog reports. type ModelsConfig struct { - RefreshSeconds int `json:"refresh_seconds"` - Protocols map[string]string `json:"protocols"` + RefreshSeconds int `json:"refresh_seconds"` + Protocols map[string]string `json:"protocols"` + Aliases map[string]string `json:"aliases,omitempty"` + StripFreeSuffix bool `json:"strip_free_suffix,omitempty"` // FreeOnly limits discovery and routing to free models, even when Zen or // Go keys could serve paid ones. Free models may still fall back to keys. FreeOnly bool `json:"free_only"` @@ -511,6 +513,9 @@ func Normalize(path string, cfg Config) (Config, error) { if err := cfg.Models.AnonymousBackoff.Normalize(); err != nil { return Config{}, err } + if err := normalizeModelAliases(&cfg); err != nil { + return Config{}, err + } for model, protocol := range cfg.Models.Protocols { if model == "" || !wire.Valid(wire.Protocol(protocol)) { return Config{}, fmt.Errorf("models.protocols contains invalid mapping %q: %q", model, protocol) @@ -649,6 +654,13 @@ func Clone(cfg Config) Config { } cfg.Models.Protocols = protocols } + if cfg.Models.Aliases != nil { + aliases := make(map[string]string, len(cfg.Models.Aliases)) + for public, model := range cfg.Models.Aliases { + aliases[public] = model + } + cfg.Models.Aliases = aliases + } if cfg.Reasoning.EffortByModel != nil { efforts := make(map[string]string, len(cfg.Reasoning.EffortByModel)) for model, effort := range cfg.Reasoning.EffortByModel { diff --git a/internal/config/model_alias.go b/internal/config/model_alias.go new file mode 100644 index 0000000..63fa742 --- /dev/null +++ b/internal/config/model_alias.go @@ -0,0 +1,65 @@ +package config + +import ( + "errors" + "fmt" + "strings" + "unicode" + + "opencode2api/internal/oauth" +) + +const FreeSuffix = "-free" + +func StripFreeSuffix(model string) (string, bool) { + base, found := strings.CutSuffix(model, FreeSuffix) + if !found || base == "" { + return model, false + } + return base, true +} + +func normalizeModelAliases(cfg *Config) error { + if len(cfg.Models.Aliases) == 0 { + return nil + } + aliases := make(map[string]string, len(cfg.Models.Aliases)) + for public, model := range cfg.Models.Aliases { + if strings.ContainsFunc(public, unicode.IsControl) || strings.ContainsFunc(model, unicode.IsControl) { + return errors.New("models.aliases must contain nonempty model names without control characters") + } + public, model = strings.TrimSpace(public), strings.TrimSpace(model) + if public == "" || model == "" { + return errors.New("models.aliases must contain nonempty model names without control characters") + } + if existing, found := aliases[public]; found && existing != model { + return errors.New("models.aliases contains conflicting entries for the same public name") + } + if public == cfg.Rotation.SOTA.Alias || public == cfg.Rotation.Sweet.Alias || model == cfg.Rotation.SOTA.Alias || model == cfg.Rotation.Sweet.Alias { + return errors.New("models.aliases must not use a rotation group alias as a public name or upstream model") + } + aliases[public] = model + } + known := make(map[string]bool, len(aliases)+len(cfg.Models.Protocols)) + for _, model := range aliases { + known[model] = true + } + for model := range cfg.Models.Protocols { + known[model] = true + } + for _, connection := range []*oauth.Connection{cfg.GoOAuth, cfg.ZenOAuth} { + if connection == nil { + continue + } + for model := range connection.Routes { + known[model] = true + } + } + for public, model := range aliases { + if public != model && known[public] { + return fmt.Errorf("models.aliases public name %q shadows an upstream model ID", public) + } + } + cfg.Models.Aliases = aliases + return nil +} diff --git a/internal/gateway/alias.go b/internal/gateway/alias.go new file mode 100644 index 0000000..d6a5342 --- /dev/null +++ b/internal/gateway/alias.go @@ -0,0 +1,115 @@ +package gateway + +import ( + "encoding/json" + "fmt" + "slices" + + "opencode2api/internal/config" + "opencode2api/internal/models" + "opencode2api/internal/oauth" +) + +type modelNames struct { + public map[string]string + resolved map[string]string +} + +func (g *Gateway) knownModelName(model string) bool { + if g.catalog.Known(model) || g.cfg.Models.Protocols[model] != "" { + return true + } + for _, connection := range []*oauth.Connection{g.cfg.GoOAuth, g.cfg.ZenOAuth} { + if connection != nil { + if _, found := connection.Routes[model]; found { + return true + } + } + } + return false +} + +func (g *Gateway) validateModelAliases() error { + for public, model := range g.cfg.Models.Aliases { + if public != model && g.knownModelName(public) { + return fmt.Errorf("models.aliases public name %q shadows an upstream model ID", public) + } + } + return nil +} + +func (g *Gateway) modelNames(routes []models.Route) modelNames { + names := modelNames{ + public: make(map[string]string, len(routes)), + resolved: make(map[string]string, len(g.cfg.Models.Aliases)+len(routes)), + } + available := make(map[string]bool, len(routes)) + reserved := map[string]bool{g.cfg.Rotation.SOTA.Alias: true, g.cfg.Rotation.Sweet.Alias: true} + for _, route := range routes { + available[route.ID] = true + reserved[route.ID] = true + names.public[route.ID] = route.ID + } + aliases := make([]string, 0, len(g.cfg.Models.Aliases)) + for public := range g.cfg.Models.Aliases { + aliases = append(aliases, public) + reserved[public] = true + reserved[g.cfg.Models.Aliases[public]] = true + } + slices.Sort(aliases) + explicit := make(map[string]bool, len(aliases)) + for _, public := range aliases { + model := g.cfg.Models.Aliases[public] + if public != model && (available[public] || g.knownModelName(public)) { + continue + } + names.resolved[public] = model + if available[model] && !explicit[model] { + names.public[model] = public + explicit[model] = true + } + } + if g.cfg.Models.StripFreeSuffix { + for _, route := range routes { + if explicit[route.ID] { + continue + } + base, stripped := config.StripFreeSuffix(route.ID) + if !stripped || reserved[base] || g.knownModelName(base) { + continue + } + names.public[route.ID] = base + names.resolved[base] = route.ID + reserved[base] = true + } + } + return names +} + +func (g *Gateway) resolveModel(name string) (real, public string) { + if len(g.cfg.Models.Aliases) == 0 && !g.cfg.Models.StripFreeSuffix { + return name, name + } + routes, _ := g.availableModels() + names := g.modelNames(routes) + if model, found := names.resolved[name]; found { + return model, name + } + return name, name +} + +func rewriteModelBody(body []byte, model string, stripEnvironment bool) ([]byte, error) { + var payload map[string]json.RawMessage + if err := json.Unmarshal(body, &payload); err != nil { + return nil, err + } + encodedModel, err := json.Marshal(model) + if err != nil { + return nil, err + } + payload["model"] = encodedModel + if stripEnvironment { + delete(payload, "client_environment") + } + return json.Marshal(payload) +} diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 48a3794..3785384 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -319,6 +319,13 @@ func (g *Gateway) handleInference(external wire.Protocol) http.HandlerFunc { g.handleRotation(w, r, external, payload, id, model) return } + model, publicModel := g.resolveModel(model) + if model != publicModel { + payload["model"] = model + if meta != nil { + meta.Model, meta.ModelAlias = model, publicModel + } + } oauthModel := false for _, connection := range []*oauth.Connection{g.cfg.GoOAuth, g.cfg.ZenOAuth} { if connection != nil { @@ -371,15 +378,15 @@ func (g *Gateway) handleInference(external wire.Protocol) http.HandlerFunc { wire.WriteError(w, external, http.StatusBadRequest, "this model uses System One decisions, not chat; send state and typed questions to /v1/systemone", "invalid_request_error", "model") return } - if strippedEnvironment { + if strippedEnvironment || model != publicModel { // This path forwards raw bytes rather than converting payload. - body, err = jsonutil.Marshal(payload) + body, err = rewriteModelBody(body, model, strippedEnvironment) if err != nil { wire.WriteError(w, external, http.StatusBadRequest, "request body could not be encoded", "invalid_request_error", "") return } } - g.forwardSystemOne(w, r, body, payload, model, route) + g.forwardSystemOne(w, r, body, payload, model, publicModel, route) return } bodies, err := g.prepareRouteBodies(external, route, payload) @@ -491,6 +498,7 @@ func (g *Gateway) handleInference(external wire.Protocol) http.HandlerFunc { w.Header().Set("Cache-Control", "no-cache") w.Header().Set("X-Accel-Buffering", "no") streamBody := wire.RenameStreamReader(resp.Body, upstreamRoute.Protocol, toolRenames) + streamBody = wire.RenameStreamModel(streamBody, model, publicModel) var usage wire.Usage var usageReported bool if external == upstreamRoute.Protocol { @@ -498,10 +506,10 @@ func (g *Gateway) handleInference(external wire.Protocol) http.HandlerFunc { if flusher, ok := w.(http.Flusher); ok { streamWriter = &deferredStreamWriter{ResponseWriter: w, flusher: flusher, status: resp.StatusCode} } - usage, usageReported, err = wire.ForwardStream(r.Context(), streamWriter, streamBody, upstreamRoute.Protocol, model) + usage, usageReported, err = wire.ForwardStream(r.Context(), streamWriter, streamBody, upstreamRoute.Protocol, publicModel) } else { w.WriteHeader(resp.StatusCode) - usage, usageReported, err = wire.TranscodeStream(r.Context(), w, streamBody, upstreamRoute.Protocol, external, model) + usage, usageReported, err = wire.TranscodeStream(r.Context(), w, streamBody, upstreamRoute.Protocol, external, publicModel) } if meta != nil { meta.Usage, meta.UsageReported = usage, usageReported @@ -551,6 +559,7 @@ func (g *Gateway) handleInference(external wire.Protocol) http.HandlerFunc { return } } + responseBody = wire.RenameResponseModel(responseBody, model, publicModel) w.Header().Set("Content-Type", "application/json") w.WriteHeader(resp.StatusCode) _, _ = w.Write(responseBody) @@ -604,13 +613,6 @@ func (g *Gateway) handleSystemOne(w http.ResponseWriter, r *http.Request) { wire.WriteError(w, wire.SystemOne, http.StatusBadRequest, err.Error(), "invalid_request_error", "client_environment") return } - if strippedEnvironment { - body, err = jsonutil.Marshal(payload) - if err != nil { - wire.WriteError(w, wire.SystemOne, http.StatusBadRequest, "request body could not be encoded", "invalid_request_error", "") - return - } - } model := jsonutil.StringAt(payload, "model") if meta := telemetry.MetaFromRequest(r); meta != nil { meta.Model = model @@ -619,6 +621,17 @@ func (g *Gateway) handleSystemOne(w http.ResponseWriter, r *http.Request) { wire.WriteError(w, wire.SystemOne, http.StatusBadRequest, "model is required", "invalid_request_error", "model") return } + model, publicModel := g.resolveModel(model) + if model != publicModel { + payload["model"] = model + } + if strippedEnvironment || model != publicModel { + body, err = rewriteModelBody(body, model, strippedEnvironment) + if err != nil { + wire.WriteError(w, wire.SystemOne, http.StatusBadRequest, "request body could not be encoded", "invalid_request_error", "") + return + } + } if !g.catalog.Supported(model) { // Same split as the chat path: a model the catalog has never heard of // is a bad model NAME (404), a model it knows but cannot serve is a @@ -639,7 +652,7 @@ func (g *Gateway) handleSystemOne(w http.ResponseWriter, r *http.Request) { wire.WriteError(w, wire.SystemOne, http.StatusBadRequest, fmt.Sprintf("the model does not use the %s protocol", wire.SystemOne), "invalid_request_error", "model") return } - g.forwardSystemOne(w, r, body, payload, model, route) + g.forwardSystemOne(w, r, body, payload, model, publicModel, route) } // forwardSystemOne relays a System One decision payload verbatim to the @@ -647,10 +660,13 @@ func (g *Gateway) handleSystemOne(w http.ResponseWriter, r *http.Request) { // The payload pairs a free-form state with typed questions, which no // message-shaped upstream protocol accepts, so it is never translated. Answers // are non-streaming today; a streaming upstream reply is still relayed. -func (g *Gateway) forwardSystemOne(w http.ResponseWriter, r *http.Request, body []byte, payload map[string]any, model string, route models.Route) { +func (g *Gateway) forwardSystemOne(w http.ResponseWriter, r *http.Request, body []byte, payload map[string]any, model, publicModel string, route models.Route) { meta := telemetry.MetaFromRequest(r) if meta != nil { meta.Model = model + if model != publicModel { + meta.ModelAlias = publicModel + } meta.Tier = string(route.Tier) meta.Protocol = route.Protocol } @@ -720,7 +736,7 @@ func (g *Gateway) forwardSystemOne(w http.ResponseWriter, r *http.Request, body w.Header().Set("Content-Type", contentType) w.Header().Set("Cache-Control", "no-cache") w.WriteHeader(resp.StatusCode) - _, _ = io.Copy(w, resp.Body) + _, _ = io.Copy(w, wire.RenameStreamModel(resp.Body, model, publicModel)) return } responseBody, err := io.ReadAll(io.LimitReader(resp.Body, (64<<20)+1)) @@ -735,6 +751,7 @@ func (g *Gateway) forwardSystemOne(w http.ResponseWriter, r *http.Request, body if usage, reported := wire.ResponseUsage(upstreamRoute.Protocol, responseBody); meta != nil { meta.Usage, meta.UsageReported = usage, reported } + responseBody = wire.RenameResponseModel(responseBody, model, publicModel) w.Header().Set("Content-Type", "application/json") w.WriteHeader(resp.StatusCode) _, _ = w.Write(responseBody) diff --git a/internal/gateway/health.go b/internal/gateway/health.go index 57fca7c..06a9ef1 100644 --- a/internal/gateway/health.go +++ b/internal/gateway/health.go @@ -238,12 +238,13 @@ func (g *Gateway) reasoningEfforts(model string, route modelcatalog.Route) []str func (g *Gateway) handleModels(w http.ResponseWriter, _ *http.Request) { now := time.Now().Unix() routes, _ := g.availableModels() + names := g.modelNames(routes) data := make([]map[string]any, 0, len(routes)) for _, route := range routes { - model := route.ID + model := names.public[route.ID] // Tier-scoped metadata: the advertised context window must match // the tier that will serve the request (anonymous ⇒ Zen). - md := g.catalog.MetadataForTier(model, route.Tier) + md := g.catalog.MetadataForTier(route.ID, route.Tier) entry := map[string]any{ "id": model, "object": "model", "created": now, "owned_by": "opencode", "metadata": md, @@ -269,12 +270,12 @@ func (g *Gateway) handleModels(w http.ResponseWriter, _ *http.Request) { if md.Reasoning { entry["reasoning"] = true entry["supports_reasoning"] = true - efforts := g.reasoningEfforts(model, route) + efforts := g.reasoningEfforts(route.ID, route) entry["reasoning_efforts"] = efforts // OpenClaw and similar harnesses read effort levels from compat // rather than inferring them, and otherwise offer only off/max. entry["compat"] = map[string]any{"supportsReasoningEffort": true, "supportedReasoningEfforts": efforts} - if effort := g.resolvedEffort(model, route.Tier, route.Protocol); effort != "" && effort != "none" { + if effort := g.resolvedEffort(route.ID, route.Tier, route.Protocol); effort != "" && effort != "none" { entry["default_reasoning_effort"] = effort } } diff --git a/internal/gateway/runtime.go b/internal/gateway/runtime.go index 4dfa7f7..06ad67f 100644 --- a/internal/gateway/runtime.go +++ b/internal/gateway/runtime.go @@ -146,6 +146,12 @@ func RuntimeManager(root context.Context, configPath string, cfg config.Config, } } runtime.gateway.restoreOAuthCatalog() + if err := runtime.gateway.validateModelAliases(); err != nil { + if runtime.warpCreated && runtime.warpPool != nil { + runtime.warpPool.Close() + } + return nil, err + } if err := cfg.Rotation.Validate(runtime.gateway.catalog.List()); err != nil { if runtime.warpCreated && runtime.warpPool != nil { runtime.warpPool.Close() @@ -405,6 +411,12 @@ func (m *RuntimeController) applyLocked(candidate config.Config, persist bool) ( next.gateway.catalog.CopyState(current.gateway.catalog) } next.gateway.restoreOAuthCatalog() + if err := next.gateway.validateModelAliases(); err != nil { + if next.warpCreated && next.warpPool != nil { + next.warpPool.Close() + } + return ApplyResult{}, err + } if err := normalized.Rotation.Validate(next.gateway.catalog.List()); err != nil { if next.warpCreated && next.warpPool != nil { next.warpPool.Close() diff --git a/internal/protocol/model.go b/internal/protocol/model.go new file mode 100644 index 0000000..67e84a2 --- /dev/null +++ b/internal/protocol/model.go @@ -0,0 +1,150 @@ +package protocol + +import ( + "bufio" + "bytes" + "encoding/json" + "errors" + "io" + "strings" +) + +func RenameResponseModel(body []byte, fromModel, toModel string) []byte { + if fromModel == "" || toModel == "" || fromModel == toModel { + return body + } + var payload map[string]any + decoder := json.NewDecoder(bytes.NewReader(body)) + decoder.UseNumber() + if decoder.Decode(&payload) != nil || payload == nil { + return body + } + var extra any + if decoder.Decode(&extra) != io.EOF { + return body + } + rename := func(container map[string]any) bool { + model, found := container["model"].(string) + if !found || model == "" || model == toModel { + return false + } + container["model"] = toModel + return true + } + changed := rename(payload) + eventType, _ := payload["type"].(string) + if strings.HasPrefix(eventType, "response.") { + response, _ := payload["response"].(map[string]any) + changed = rename(response) || changed + } + if eventType == "message_start" { + message, _ := payload["message"].(map[string]any) + changed = rename(message) || changed + } + if !changed { + return body + } + encoded, err := json.Marshal(payload) + if err != nil { + return body + } + return encoded +} + +func RenameStreamModel(reader io.Reader, fromModel, toModel string) io.Reader { + if fromModel == "" || toModel == "" || fromModel == toModel { + return reader + } + return &modelStreamReader{ + reader: bufio.NewReaderSize(reader, 64<<10), + from: fromModel, + to: toModel, + } +} + +type modelStreamReader struct { + reader *bufio.Reader + from string + to string + pending []byte + err error +} + +func (reader *modelStreamReader) Read(data []byte) (int, error) { + if len(data) == 0 { + return 0, nil + } + for len(reader.pending) == 0 { + if reader.err != nil { + return 0, reader.err + } + var frame []byte + lineStart := 0 + for { + part, err := reader.reader.ReadSlice('\n') + if len(frame)+len(part) > maxSSEFrameBytes { + reader.err = errSSEFrameTooLarge + return 0, reader.err + } + frame = append(frame, part...) + if errors.Is(err, bufio.ErrBufferFull) { + continue + } + if err != nil { + reader.err = err + reader.pending = frame + break + } + line := bytes.TrimSuffix(bytes.TrimSuffix(frame[lineStart:], []byte("\n")), []byte("\r")) + if len(line) == 0 { + reader.pending = reader.rewrite(frame) + break + } + lineStart = len(frame) + } + } + count := copy(data, reader.pending) + reader.pending = reader.pending[count:] + return count, nil +} + +func (reader *modelStreamReader) rewrite(frame []byte) []byte { + lines := bytes.SplitAfter(frame, []byte("\n")) + var payload bytes.Buffer + for _, line := range lines { + if !bytes.HasPrefix(line, []byte("data:")) { + continue + } + if payload.Len() > 0 { + payload.WriteByte('\n') + } + payload.Write(bytes.TrimSpace(bytes.TrimPrefix(line, []byte("data:")))) + } + if payload.Len() == 0 { + return frame + } + rewritten := RenameResponseModel(payload.Bytes(), reader.from, reader.to) + if bytes.Equal(rewritten, payload.Bytes()) { + return frame + } + var output bytes.Buffer + written := false + for _, line := range lines { + if !bytes.HasPrefix(line, []byte("data:")) { + output.Write(line) + continue + } + if written { + continue + } + output.WriteString("data: ") + output.Write(rewritten) + if bytes.HasSuffix(line, []byte("\r\n")) { + output.WriteString("\r\n") + } else if bytes.HasSuffix(line, []byte("\n")) { + output.WriteByte('\n') + } + written = true + } + return output.Bytes() +} diff --git a/webui/index.html b/webui/index.html index 4dae7d8..904c193 100644 --- a/webui/index.html +++ b/webui/index.html @@ -1067,6 +1067,16 @@ +
+ + +
+
+ +