feat(models): add collision-safe aliases and model echoes (#125)

This commit is contained in:
Jason Xu committed 2026-11-30 04:40:43 +08:00
1 parent a0fbd6b6cb
commit 9b44a031ca
14 files changed
+443 -23

No files matched your search

+6
View File
@@ -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
+6
View File
@@ -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 通道。
### 超时、代理与会话亲和
+2
View File
@@ -27,6 +27,8 @@
"models": {
"refresh_seconds": 300,
"protocols": {},
"aliases": {},
"strip_free_suffix": false,
"free_only": false,
"active_probes": false
},
+16 -2
View File
@@ -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 {
+14 -2
View File
@@ -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 {
+65
View File
@@ -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
}
+115
View File
@@ -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)
}
+32 -15
View File
@@ -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)
+5 -4
View File
@@ -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
}
}
+12
View File
@@ -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()
+150
View File
@@ -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()
}
+10
View File
@@ -1067,6 +1067,16 @@
<label for="c-protocols" data-i18n="config.upstream.protocols">模型协议覆盖(JSON)</label>
<textarea id="c-protocols" spellcheck="false">{}</textarea>
</div>
<div class="field">
<label for="c-model-aliases" data-i18n="config.upstream.aliases">模型公开别名(JSON:公开名 → 上游 ID)</label>
<textarea id="c-model-aliases" spellcheck="false">{}</textarea>
</div>
<div class="field full">
<label class="check">
<input id="c-strip-free-suffix" type="checkbox" />
<span data-i18n="config.upstream.stripFreeSuffix">自动去掉公开模型名的 -free 后缀(保留原始 ID 兼容)</span>
</label>
</div>
<div class="field full">
<label class="check">
<input id="c-free-only" type="checkbox" />
+6
View File
@@ -347,6 +347,8 @@ const DICTIONARY = {
"config.upstream.timeout": "Request timeout (seconds)",
"config.upstream.refresh": "Model refresh interval (seconds)",
"config.upstream.protocols": "Model protocol overrides (JSON)",
"config.upstream.aliases": "Public model aliases (JSON: public name → upstream ID)",
"config.upstream.stripFreeSuffix": "Strip -free from public model names (upstream IDs remain accepted)",
"config.reasoning.title": "Thinking effort",
"config.reasoning.caption":
"Applied only when the client does not specify an effort; per-model overrides take priority. Choosing “Off” removes reasoning for requests that do not ask for it.",
@@ -973,6 +975,8 @@ const DICTIONARY = {
"config.upstream.timeout": "Timeout của request (giây)",
"config.upstream.refresh": "Làm mới mô hình (giây)",
"config.upstream.protocols": "Ghi đè giao thức mô hình (JSON)",
"config.upstream.aliases": "Bí danh mô hình (JSON: tên công khai → ID upstream)",
"config.upstream.stripFreeSuffix": "Bỏ hậu tố -free khỏi tên công khai (vẫn nhận ID upstream)",
"config.reasoning.title": "Cường độ Thinking",
"config.reasoning.caption":
"Chỉ áp dụng khi client không chỉ định rõ; có thể ghi đè theo từng mô hình. Chọn “Tắt” sẽ bỏ reasoning cho các request không yêu cầu rõ.",
@@ -1564,6 +1568,8 @@ const DICTIONARY = {
"config.upstream.timeout": "Timeout richiesta (secondi)",
"config.upstream.refresh": "Intervallo di refresh modelli (secondi)",
"config.upstream.protocols": "Override protocollo modello (JSON)",
"config.upstream.aliases": "Alias pubblici (JSON: nome pubblico → ID upstream)",
"config.upstream.stripFreeSuffix": "Rimuovi -free dai nomi pubblici (gli ID upstream restano validi)",
"config.reasoning.title": "Livello di ragionamento",
"config.reasoning.caption":
"Applicato solo quando il client non specifica un livello di ragionamento; gli override per modello hanno priorità. Scegliere “Disattivo” rimuove il ragionamento per le richieste che non lo richiedono.",
+4
View File
@@ -105,6 +105,8 @@ function fillConfig(value) {
$("#c-timeout").value = value.retry.timeout_seconds;
$("#c-refresh").value = value.models.refresh_seconds;
$("#c-protocols").value = JSON.stringify(value.models.protocols || {}, null, 2);
$("#c-model-aliases").value = JSON.stringify(value.models.aliases || {}, null, 2);
$("#c-strip-free-suffix").checked = !!value.models.strip_free_suffix;
$("#c-free-only").checked = !!value.models.free_only;
$("#c-active-probes").checked = !!value.models.active_probes;
const reasoning = value.reasoning || {};
@@ -172,6 +174,8 @@ async function save(event) {
...current.models,
refresh_seconds: numberValue("#c-refresh"),
protocols: JSON.parse($("#c-protocols").value || "{}"),
aliases: JSON.parse($("#c-model-aliases").value || "{}"),
strip_free_suffix: $("#c-strip-free-suffix").checked,
free_only: $("#c-free-only").checked,
active_probes: $("#c-active-probes").checked,
},