feat(plugin): 插件渠道可按渠道开关提供商插件的路由

同一个提供商插件绑到多个类型 61 渠道时,各渠道的路由完全相同,无法只在部分渠道上
开启某条转换路由。#8478 用 enabled_by 指向 channelConfig 里的 boolean 字段,已回退;
这里改为由渠道直接保存路由开关,插件不用为每条路由声明配置字段。

- meta.relay 的路由新增 default_enabled(默认 true),写 false 的路由新渠道默认不提供;
  管理路由(/v1/models、余额)始终开启,不能写 false。
- 渠道的 other_settings.plugin_routes 保存路由开关,键为 incoming_path,
  带 models 时追加 "|" 和逗号连接的模型名;保存时只保留与默认值不同的项,
  不认识的键丢弃。
- 选渠道、Responses WebSocket 判断、转发、提供商适配器绑定路由、渠道测试选端点、
  上游模型列表和定价端点都只看对该渠道开启的路由;同一路径的其他路由照常匹配。
- 插件选项接口返回 relayRoutes;渠道编辑「路由与映射」页签顶部列出插件路由,
  每条一个开关,补齐七种语言词条。
- pluginkit/v1.md、v1.d.ts、v1.schema.json 补充 default_enabled 与 plugin_routes。

Refs #8466
This commit is contained in:
CaIon committed 2026-11-27 23:22:23 +08:00
1 parent 50a9767024
commit 9a52aabc58
33 files changed
+759 -60

No files matched your search

+7 -6
View File
@@ -67,15 +67,16 @@ var providerTestEndpoints = []constant.EndpointType{
}
// providerTestEndpoint returns the endpoint a task plugin channel test uses
// for model instead of requestPath, which meta's relay routes do not serve.
// ok is false when they serve requestPath or none of the test endpoints.
func providerTestEndpoint(meta jsplugin.Meta, requestPath, model string) (endpoint constant.EndpointType, ok bool) {
if _, served := meta.RelayRoute(requestPath, model); served {
// for model instead of requestPath, which meta's relay routes that are on for
// the channel (toggles are its plugin_routes) do not serve. ok is false when
// they serve requestPath or none of the test endpoints.
func providerTestEndpoint(meta jsplugin.Meta, toggles map[string]bool, requestPath, model string) (endpoint constant.EndpointType, ok bool) {
if _, served := meta.ChannelRelayRoute(toggles, requestPath, model); served {
return "", false
}
for _, endpoint := range providerTestEndpoints {
info, _ := common.GetDefaultEndpointInfo(endpoint)
if _, served := meta.RelayRoute(strings.ReplaceAll(info.Path, "{model}", model), model); served {
if _, served := meta.ChannelRelayRoute(toggles, strings.ReplaceAll(info.Path, "{model}", model), model); served {
return endpoint, true
}
}
@@ -181,7 +182,7 @@ func testChannel(ctx context.Context, channel *model.Channel, testUserID int, te
// A task plugin channel tests on an endpoint its relay routes serve for the
// model: the default one when they serve it, else the first they serve.
if providerChannel && endpointType == "" {
if endpoint, ok := providerTestEndpoint(plugin.Meta, requestPath, testModel); ok {
if endpoint, ok := providerTestEndpoint(plugin.Meta, channel.GetOtherSettings().PluginRoutes, requestPath, testModel); ok {
endpointType = string(endpoint)
endpointInfo, _ := common.GetDefaultEndpointInfo(endpoint)
requestPath = strings.ReplaceAll(endpointInfo.Path, "{model}", testModel)
+6 -2
View File
@@ -6,6 +6,7 @@ import (
"encoding/json"
"errors"
"fmt"
"maps"
"net/http"
"slices"
"strconv"
@@ -559,7 +560,8 @@ const maxTaskExtendPluginKeys = 32
// normalizePluginConfig validates the plugin config in the channel's settings
// and stores it as the schema reads it: declared properties only, defaults
// left to the read.
// left to the read. It keeps the plugin_routes entries that switch a relay
// route of the plugin away from its default.
func normalizePluginConfig(channel *model.Channel, plugin *jsplugin.LoadedPlugin) error {
otherSettings := channel.GetOtherSettings()
config, err := plugin.ValidateChannelConfig(otherSettings.PluginConfig)
@@ -569,8 +571,10 @@ func normalizePluginConfig(channel *model.Channel, plugin *jsplugin.LoadedPlugin
if plugin.Meta.ChannelConfig == nil || string(config) == "{}" {
config = nil
}
if !bytes.Equal(config, otherSettings.PluginConfig) {
routes := plugin.Meta.NormalizeRouteToggles(otherSettings.PluginRoutes)
if !bytes.Equal(config, otherSettings.PluginConfig) || !maps.Equal(routes, otherSettings.PluginRoutes) {
otherSettings.PluginConfig = config
otherSettings.PluginRoutes = routes
channel.SetOtherSettings(otherSettings)
}
return nil
+17 -2
View File
@@ -28,7 +28,10 @@ const (
// configPluginSource declares a channel config and checks typed-in keys.
configPluginSource = `
export const meta = {apiVersion: 1, key: "%KEY%", name: "Config", version: "1.0.0", author: {name: "Test"},
relay: [{incoming_path: "/v1/chat/completions", upstream_path: "/chat"}],
relay: [
{incoming_path: "/v1/chat/completions", upstream_path: "/chat"},
{incoming_path: "/v1/responses", upstream_path: "/chat", converter: "openai_responses_to_openai_chat_completions", default_enabled: false},
],
channelConfig: {type: "object", properties: {
region: {type: "string", title: {en: "Region"}, enum: ["us", "eu"], default: "us"},
timeout: {type: "integer", title: {en: "Timeout"}, minimum: 1, default: 30},
@@ -173,6 +176,18 @@ func TestGapsChannelConfigAndKeyCheckOnSave(t *testing.T) {
require.True(t, response.Success, raw)
assert.JSONEq(t, `{"region":"eu"}`, string(storedGapsChannel(t, channel.Id).GetOtherSettings().PluginConfig))
})
t.Run("update keeps only route switches that differ from the defaults", func(t *testing.T) {
channel := insertPluginChannel(t, "gaps-config", "https://vendor.example", "good-1", false)
settings := `{\"plugin_routes\":{\"/v1/responses\":true,\"/v1/chat/completions\":true,\"/v1/unknown\":false}}`
response, raw := callChannelAPI(t, UpdateChannel, http.MethodPut, "/api/channel", fmt.Sprintf(`{"id":%d,"settings":"%s"}`, channel.Id, settings))
require.True(t, response.Success, raw)
assert.Equal(t, map[string]bool{"/v1/responses": true}, storedGapsChannel(t, channel.Id).GetOtherSettings().PluginRoutes)
response, raw = callChannelAPI(t, UpdateChannel, http.MethodPut, "/api/channel", fmt.Sprintf(`{"id":%d,"settings":"{\"plugin_routes\":{\"/v1/responses\":false}}"}`, channel.Id))
require.True(t, response.Success, raw)
assert.Nil(t, storedGapsChannel(t, channel.Id).GetOtherSettings().PluginRoutes, "switching back to the default stores nothing")
})
}
// balanceServer answers the balance request of each key with the reply set
@@ -445,7 +460,7 @@ func TestGapsProviderTestEndpoint(t *testing.T) {
{"no test endpoint is served", routes(route("/v1/videos")), "/v1/chat/completions", "m", "", false},
} {
t.Run(tc.name, func(t *testing.T) {
endpoint, ok := providerTestEndpoint(tc.meta, tc.requestPath, tc.model)
endpoint, ok := providerTestEndpoint(tc.meta, nil, tc.requestPath, tc.model)
assert.Equal(t, tc.wantOK, ok)
assert.Equal(t, tc.wantEndpoint, endpoint)
})
+1 -1
View File
@@ -528,7 +528,7 @@ func fetchProviderPluginUpstreamModelIDs(channel *model.Channel, plugin *jsplugi
return nil, err
}
settings := channel.GetOtherSettings()
settings.AdvancedCustom = plugin.Meta.ChannelRelayConfig(plugin.ChannelConfigFor(settings.PluginConfig))
settings.AdvancedCustom = plugin.Meta.ChannelRelayConfig(plugin.ChannelConfigFor(settings.PluginConfig), settings.PluginRoutes)
info := &relaycommon.RelayInfo{
RelayFormat: types.RelayFormatOpenAI,
RelayMode: relayconstant.RelayModeUnknown,
+24
View File
@@ -23,6 +23,7 @@ import (
"github.com/QuantumNous/new-api/pkg/jsplugin"
"github.com/QuantumNous/new-api/plugins"
"github.com/QuantumNous/new-api/relay/requestplugin"
"github.com/QuantumNous/new-api/relaykit/dto"
"github.com/QuantumNous/new-api/service"
"github.com/QuantumNous/new-api/setting"
"github.com/gin-gonic/gin"
@@ -921,6 +922,28 @@ func relayPaths(meta jsplugin.Meta) []string {
return paths
}
// relayRouteOptions lists the relay routes a channel of the plugin can switch
// on or off, management routes left out. key is the plugin_routes key and
// default_enabled whether a channel that has not switched it serves it.
func relayRouteOptions(meta jsplugin.Meta) []gin.H {
routes := make([]gin.H, 0, len(meta.Relay))
for index, route := range meta.Relay {
path := strings.TrimSpace(route.IncomingPath)
if path == dto.AdvancedCustomModelListPath || path == dto.AdvancedCustomBalancePath {
continue
}
routes = append(routes, gin.H{
"key": jsplugin.RelayRouteKey(route),
"incoming_path": path,
"upstream_path": route.UpstreamPath,
"converter": strings.TrimSpace(route.Converter),
"models": route.Models,
"default_enabled": meta.RelayRouteDefault(index),
})
}
return routes
}
func GetTaskPluginOptions(c *gin.Context) {
snapshot := jsplugin.DefaultRegistry.Snapshot()
seen := make(map[string]bool)
@@ -989,6 +1012,7 @@ func GetTaskPluginOptions(c *gin.Context) {
"checkKey": loaded.HasProviderHook("checkKey"),
"balance": loaded.HasProviderHook("buildBalanceRequest") && loaded.HasProviderHook("parseBalance"),
"relayPaths": relayPaths(loaded.Meta),
"relayRoutes": relayRouteOptions(loaded.Meta),
"responsesWebsocket": loaded.Meta.ServesResponsesWebSocket(""),
}
if len(loaded.Meta.KeyHint) > 0 {
+1 -1
View File
@@ -684,7 +684,7 @@ func SetupContextForSelectedChannel(c *gin.Context, channel *model.Channel, mode
generation := jsplugin.DefaultRegistry.Generation()
if plugin, ok := generation.Get(channel.GetSetting().TaskPluginKey); ok && plugin.Meta.HasProviderPart() {
providerPlugin = jsplugin.PinnedPlugin{Generation: generation, Plugin: plugin}
otherSettings.AdvancedCustom = plugin.Meta.ChannelRelayConfig(plugin.ChannelConfigFor(otherSettings.PluginConfig))
otherSettings.AdvancedCustom = plugin.Meta.ChannelRelayConfig(plugin.ChannelConfigFor(otherSettings.PluginConfig), otherSettings.PluginRoutes)
}
}
common.SetContextKey(c, constant.ContextKeyChannelOtherSetting, otherSettings)
+2 -2
View File
@@ -139,7 +139,7 @@ func channelMatchesFilter(ch *Channel, modelName string, filter dto.ChannelFilte
case constant.ChannelTypeTaskPlugin:
// The same rule on the relay routes of the channel's plugin.
plugin, ok := jsplugin.DefaultRegistry.Get(ch.GetSetting().TaskPluginKey)
return ok && plugin.Meta.ServesResponsesWebSocket(modelName)
return ok && plugin.Meta.ChannelServesResponsesWebSocket(ch.GetOtherSettings().PluginRoutes, modelName)
default:
return false
}
@@ -159,6 +159,6 @@ func providerChannelServes(ch *Channel, requestPath, modelName string) bool {
if !ok || !plugin.Meta.HasProviderPart() {
return false
}
_, ok = plugin.Meta.RelayRoute(requestPath, modelName)
_, ok = plugin.Meta.ChannelRelayRoute(ch.GetOtherSettings().PluginRoutes, requestPath, modelName)
return ok
}
+8 -4
View File
@@ -216,9 +216,9 @@ func CacheUpdateChannelKey(id int, key string) {
}
// channelRelayConfig returns the relay routes of a task plugin channel's
// plugin, nil for any other channel. It reads the setting without GetSetting,
// which clears the stored setting when it is invalid, so a pricing read never
// writes the channel.
// plugin that are on for the channel, nil for any other channel. It reads the
// settings without GetSetting or GetOtherSettings, which clear a stored
// setting when it is invalid, so a pricing read never writes the channel.
func channelRelayConfig(ch *Channel) *dto.AdvancedCustomConfig {
var setting dto.ChannelSettings
if ch.Type != constant.ChannelTypeTaskPlugin || ch.Setting == nil || common.UnmarshalJsonStr(*ch.Setting, &setting) != nil {
@@ -228,7 +228,11 @@ func channelRelayConfig(ch *Channel) *dto.AdvancedCustomConfig {
if !ok {
return nil
}
return plugin.Meta.RelayConfig()
var otherSettings dto.ChannelOtherSettings
if ch.OtherSettings != "" {
_ = common.UnmarshalJsonStr(ch.OtherSettings, &otherSettings)
}
return plugin.Meta.ChannelRelayConfig(nil, otherSettings.PluginRoutes)
}
// UpdateScheduledChannelLocked persists a completed scheduled result. update
+48
View File
@@ -191,6 +191,54 @@ func TestProviderChannelSelectionFollowsRelayRoutes(t *testing.T) {
}
}
// Two channels bound to one plugin: the /v1/responses route declared
// default_enabled: false serves only the channel whose plugin_routes turn it on.
func TestProviderChannelSelectionFollowsChannelRouteToggles(t *testing.T) {
truncateTables(t)
registerModelTestPlugin(t, `
export const meta = {apiVersion: 1, key: "%KEY%", name: "Toggles", version: "1.0.0", author: {name: "Test"},
relay: [
{incoming_path: "/v1/chat/completions", upstream_path: "/chat"},
{incoming_path: "/v1/responses", upstream_path: "/chat", converter: "openai_responses_to_openai_chat_completions", default_enabled: false}
]};
`, "select-toggles")
originalMemoryCache := common.MemoryCacheEnabled
t.Cleanup(func() { common.MemoryCacheEnabled = originalMemoryCache; InitChannelCache() })
priority := int64(0)
weight := uint(1)
setting := `{"task_plugin_key":"select-toggles"}`
for _, channel := range []Channel{
{Id: 960011, Type: constant.ChannelTypeTaskPlugin, Status: common.ChannelStatusEnabled, Name: "off", Models: "m", Group: "default", Priority: &priority, Weight: &weight, Setting: &setting},
{Id: 960012, Type: constant.ChannelTypeTaskPlugin, Status: common.ChannelStatusEnabled, Name: "on", Models: "m", Group: "default", Priority: &priority, Weight: &weight, Setting: &setting,
OtherSettings: `{"plugin_routes":{"/v1/responses":true}}`},
} {
require.NoError(t, channel.Insert())
}
for _, tc := range []struct {
id int
path string
wantServes bool
}{
{id: 960011, path: "/v1/responses", wantServes: false},
{id: 960012, path: "/v1/responses", wantServes: true},
{id: 960011, path: "/v1/chat/completions", wantServes: true},
{id: 960012, path: "/v1/chat/completions", wantServes: true},
} {
channel, err := GetChannelById(tc.id, true)
require.NoError(t, err)
assert.Equal(t, tc.wantServes, providerChannelServes(channel, tc.path, "m"), "%s %s", channel.Name, tc.path)
}
for _, memoryCache := range []bool{false, true} {
common.MemoryCacheEnabled = memoryCache
InitChannelCache()
selected, err := GetChannel("default", "m", 0, []dto.ChannelFilter{{Kind: dto.FilterTaskPluginIdentity, RequestPath: "/v1/responses"}})
require.NoError(t, err)
require.NotNil(t, selected, "memory cache %v", memoryCache)
assert.Equal(t, "on", selected.Name, "memory cache %v", memoryCache)
}
}
func TestPricingProviderChannelUsesRelayRoutes(t *testing.T) {
resetPricingEndpointTestTables(t)
registerModelTestPlugin(t, dualPluginSource, "pricing-dual")
+1
View File
@@ -159,6 +159,7 @@ var (
ParseFileReference = pluginkit.ParseFileReference
PluginRouteBindings = pluginkit.PluginRouteBindings
RedactCredentialLines = pluginkit.RedactCredentialLines
RelayRouteKey = pluginkit.RelayRouteKey
ResolveRouteAction = pluginkit.ResolveRouteAction
SetParamOverrideFunc = pluginkit.SetParamOverrideFunc
SplitProviderConverter = pluginkit.SplitProviderConverter
+1 -1
View File
@@ -96,7 +96,7 @@ func TestConfigAddressRoutes(t *testing.T) {
require.NoError(t, err)
paths := func(config string) []string {
var upstream []string
for _, route := range plugin.Meta.ChannelRelayConfig(plugin.ChannelConfigFor(json.RawMessage(config))).Routes {
for _, route := range plugin.Meta.ChannelRelayConfig(plugin.ChannelConfigFor(json.RawMessage(config)), nil).Routes {
upstream = append(upstream, route.UpstreamPath)
}
return upstream
+142 -25
View File
@@ -106,6 +106,9 @@ type Meta struct {
// Relay is the provider part: the Advanced Custom routes a type-61
// channel bound to the plugin serves.
Relay []dto.AdvancedCustomRoute `json:"relay,omitempty"`
// RelayDefaultOff marks, aligned with Relay, a route a channel serves only
// after the channel turns it on (default_enabled: false in the manifest).
RelayDefaultOff []bool `json:"relayDefaultOff,omitempty"`
// ConfigSchema is the schema of a request processing instance's config.
ConfigSchema *ConfigSchema `json:"configSchema,omitempty"`
// ChannelConfig is the schema of the plugin config of a type-61 channel
@@ -173,10 +176,14 @@ func (m Meta) HasProviderPart() bool {
// a native route of its client protocol, and a chained one as a route of its
// registered converter; the provider adaptor converts around it.
func (m Meta) RelayConfig() *dto.AdvancedCustomConfig {
if len(m.Relay) == 0 {
return relayConfig(m.Relay)
}
func relayConfig(relay []dto.AdvancedCustomRoute) *dto.AdvancedCustomConfig {
if len(relay) == 0 {
return nil
}
routes := cloneRelayRoutes(m.Relay)
routes := cloneRelayRoutes(relay)
for index := range routes {
if converter, hooks := SplitProviderConverter(routes[index].Converter); hooks {
routes[index].Converter = converter
@@ -185,12 +192,80 @@ func (m Meta) RelayConfig() *dto.AdvancedCustomConfig {
return &dto.AdvancedCustomConfig{Routes: routes}
}
// ChannelRelayConfig is RelayConfig for a channel: an upstream_path that
// starts with {config.<name>} starts with that address of the channel's plugin
// config instead, or is relative to the channel base URL when the address is
// empty. config is the config as ChannelConfigFor returns it.
func (m Meta) ChannelRelayConfig(config []byte) *dto.AdvancedCustomConfig {
relay := m.RelayConfig()
// RelayRouteKey names a relay route in a channel's plugin_routes: its
// incoming_path, followed by "|" and its models joined with "," when it lists
// models.
func RelayRouteKey(route dto.AdvancedCustomRoute) string {
key := strings.TrimSpace(route.IncomingPath)
if len(route.Models) > 0 {
key += "|" + strings.Join(route.Models, ",")
}
return key
}
// RelayRouteDefault reports whether a channel that has not switched route
// index serves it: false only for a route declared default_enabled: false.
func (m Meta) RelayRouteDefault(index int) bool {
return index >= len(m.RelayDefaultOff) || !m.RelayDefaultOff[index]
}
// RelayRouteOn reports whether route index serves a channel whose
// plugin_routes are toggles. A management route is always on.
func (m Meta) RelayRouteOn(index int, toggles map[string]bool) bool {
if relayManagementRoute(m.Relay[index]) {
return true
}
if on, set := toggles[RelayRouteKey(m.Relay[index])]; set {
return on
}
return m.RelayRouteDefault(index)
}
// ChannelRelayRoutes returns the relay routes that serve a channel whose
// plugin_routes are toggles, with the converter as the manifest declares it.
func (m Meta) ChannelRelayRoutes(toggles map[string]bool) []dto.AdvancedCustomRoute {
routes := make([]dto.AdvancedCustomRoute, 0, len(m.Relay))
for index, route := range m.Relay {
if m.RelayRouteOn(index, toggles) {
routes = append(routes, route)
}
}
return routes
}
// NormalizeRouteToggles keeps the plugin_routes entries that name a relay
// route other than a management route and differ from its default; it
// returns nil when none is left.
func (m Meta) NormalizeRouteToggles(toggles map[string]bool) map[string]bool {
var normalized map[string]bool
for index, route := range m.Relay {
key := RelayRouteKey(route)
on, set := toggles[key]
if !set || relayManagementRoute(route) || on == m.RelayRouteDefault(index) {
continue
}
if normalized == nil {
normalized = make(map[string]bool)
}
normalized[key] = on
}
return normalized
}
// relayManagementRoute reports a /v1/models or balance route, which serves
// channel management rather than client requests.
func relayManagementRoute(route dto.AdvancedCustomRoute) bool {
path := strings.TrimSpace(route.IncomingPath)
return path == dto.AdvancedCustomModelListPath || path == dto.AdvancedCustomBalancePath
}
// ChannelRelayConfig is RelayConfig for a channel: only the routes its
// plugin_routes (toggles) leave on, and an upstream_path that starts with
// {config.<name>} starts with that address of the channel's plugin config
// instead, or is relative to the channel base URL when the address is empty.
// config is the config as ChannelConfigFor returns it.
func (m Meta) ChannelRelayConfig(config []byte, toggles map[string]bool) *dto.AdvancedCustomConfig {
relay := relayConfig(m.ChannelRelayRoutes(toggles))
if relay == nil {
return nil
}
@@ -227,13 +302,20 @@ func (m Meta) RelayRoute(requestPath, model string) (dto.AdvancedCustomRoute, bo
return config.MatchPathForModel(requestPath, model)
}
// ChannelRelayRoute is RelayRoute among the routes that serve a channel whose
// plugin_routes are toggles. Another route of the same path still matches
// when a switched-off one would have.
func (m Meta) ChannelRelayRoute(toggles map[string]bool, requestPath, model string) (dto.AdvancedCustomRoute, bool) {
config := dto.AdvancedCustomConfig{Routes: m.ChannelRelayRoutes(toggles)}
return config.MatchPathForModel(requestPath, model)
}
// RelaysModel reports whether a relay route accepts model for client
// requests: the plugin serves the model on chat paths, not only as a task. The
// model list and balance routes accept every model and serve none.
func (m Meta) RelaysModel(model string) bool {
return slices.ContainsFunc(m.Relay, func(route dto.AdvancedCustomRoute) bool {
path := strings.TrimSpace(route.IncomingPath)
return path != dto.AdvancedCustomModelListPath && path != dto.AdvancedCustomBalancePath && route.AcceptsModel(model)
return !relayManagementRoute(route) && route.AcceptsModel(model)
})
}
@@ -242,14 +324,25 @@ func (m Meta) RelaysModel(model string) bool {
// converter, so the session forwards native events as Advanced Custom does.
// An empty model asks whether any route of that path qualifies.
func (m Meta) ServesResponsesWebSocket(model string) bool {
return servesResponsesWebSocket(m.Relay, model)
}
// ChannelServesResponsesWebSocket is ServesResponsesWebSocket on the routes
// that serve a channel whose plugin_routes are toggles.
func (m Meta) ChannelServesResponsesWebSocket(toggles map[string]bool, model string) bool {
return servesResponsesWebSocket(m.ChannelRelayRoutes(toggles), model)
}
func servesResponsesWebSocket(routes []dto.AdvancedCustomRoute, model string) bool {
if model == "" {
return slices.ContainsFunc(m.Relay, func(route dto.AdvancedCustomRoute) bool {
return slices.ContainsFunc(routes, func(route dto.AdvancedCustomRoute) bool {
config := dto.AdvancedCustomConfig{Routes: []dto.AdvancedCustomRoute{route}}
_, ok := config.MatchPath(responsesPath)
return ok && route.IsNative()
})
}
route, ok := m.RelayRoute(responsesPath, model)
config := dto.AdvancedCustomConfig{Routes: routes}
route, ok := config.MatchPathForModel(responsesPath, model)
return ok && route.IsNative()
}
@@ -774,6 +867,7 @@ func cloneMeta(meta Meta) Meta {
profile.Examples = CloneUsageExamples(profile.Examples)
}
meta.Relay = cloneRelayRoutes(meta.Relay)
meta.RelayDefaultOff = slices.Clone(meta.RelayDefaultOff)
meta.transformHooks = slices.Clone(meta.transformHooks)
meta.Samples = slices.Clone(meta.Samples)
for index := range meta.Samples {
@@ -996,7 +1090,7 @@ func decodeMeta(value any) (Meta, error) {
}
}
if relay, exists := object["relay"]; exists {
meta.Relay, err = decodeRelayRoutes(relay)
meta.Relay, meta.RelayDefaultOff, err = decodeRelayRoutes(relay)
if err != nil {
return Meta{}, err
}
@@ -1324,53 +1418,76 @@ func normalizeV1Meta(meta *Meta) error {
return fmt.Errorf("plugin meta usageProfiles[%d]: %w", index, err)
}
}
for index, off := range meta.RelayDefaultOff {
if off && relayManagementRoute(meta.Relay[index]) {
return fmt.Errorf("plugin meta relay[%d].%s is not allowed on %s", index, relayDefaultEnabledField, strings.TrimSpace(meta.Relay[index].IncomingPath))
}
}
return validateRelayRoutes(meta.Relay, meta.ChannelConfig)
}
// relayErrorNames renames Advanced Custom validation errors for manifests.
var relayErrorNames = strings.NewReplacer("advanced_custom.advanced_routes", "plugin meta relay", "advanced_routes[", "relay[")
var relayRouteFields = []string{"incoming_path", "upstream_path", "converter", "models", "auth", "pass_through_body_enabled"}
var relayRouteFields = []string{"incoming_path", "upstream_path", "converter", "models", "auth", "pass_through_body_enabled", relayDefaultEnabledField}
// relayDefaultEnabledField says whether a new channel serves the route. Only a
// plugin route has it.
const relayDefaultEnabledField = "default_enabled"
// decodeRelayRoutes reads meta.relay. Each route has exactly the keys of an
// Advanced Custom route.
func decodeRelayRoutes(value any) ([]dto.AdvancedCustomRoute, error) {
// Advanced Custom route, plus default_enabled; defaultOff is aligned with the
// routes, or nil when every route is on by default.
func decodeRelayRoutes(value any) (routes []dto.AdvancedCustomRoute, defaultOff []bool, err error) {
items, ok := value.([]any)
if !ok {
return nil, fmt.Errorf("plugin meta relay must be an array")
return nil, nil, fmt.Errorf("plugin meta relay must be an array")
}
routes := make([]dto.AdvancedCustomRoute, len(items))
routes = make([]dto.AdvancedCustomRoute, len(items))
for index, item := range items {
object, ok := item.(map[string]any)
if !ok {
return nil, fmt.Errorf("plugin meta relay[%d] must be an object", index)
return nil, nil, fmt.Errorf("plugin meta relay[%d] must be an object", index)
}
for field, fieldValue := range object {
if !slices.Contains(relayRouteFields, field) {
return nil, fmt.Errorf("plugin meta relay[%d] has unknown field %q", index, field)
return nil, nil, fmt.Errorf("plugin meta relay[%d] has unknown field %q", index, field)
}
if field != "auth" || fieldValue == nil {
continue
}
auth, isObject := fieldValue.(map[string]any)
if !isObject {
return nil, fmt.Errorf("plugin meta relay[%d].auth must be an object", index)
return nil, nil, fmt.Errorf("plugin meta relay[%d].auth must be an object", index)
}
for authField := range auth {
if authField != "type" && authField != "name" && authField != "value" {
return nil, fmt.Errorf("plugin meta relay[%d].auth has unknown field %q", index, authField)
return nil, nil, fmt.Errorf("plugin meta relay[%d].auth has unknown field %q", index, authField)
}
}
}
if fieldValue, exists := object[relayDefaultEnabledField]; exists {
enabled, isBool := fieldValue.(bool)
if !isBool {
return nil, nil, fmt.Errorf("plugin meta relay[%d].%s must be a boolean", index, relayDefaultEnabledField)
}
if !enabled {
if defaultOff == nil {
defaultOff = make([]bool, len(items))
}
defaultOff[index] = true
}
delete(object, relayDefaultEnabledField)
}
encoded, err := marshalJSON(object)
if err != nil {
return nil, fmt.Errorf("plugin meta relay[%d]: %w", index, err)
return nil, nil, fmt.Errorf("plugin meta relay[%d]: %w", index, err)
}
if err = unmarshalJSON(encoded, &routes[index]); err != nil {
return nil, fmt.Errorf("plugin meta relay[%d] has a member of the wrong type: %w", index, err)
return nil, nil, fmt.Errorf("plugin meta relay[%d] has a member of the wrong type: %w", index, err)
}
}
return routes, nil
return routes, defaultOff, nil
}
// validateRelayRoutes applies the Advanced Custom route rules to meta.relay.
+93
View File
@@ -0,0 +1,93 @@
package pluginkit
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// toggleRelay serves chat always, Responses for model a off by default with a
// catch-all Responses route after it, and lists models.
const toggleRelay = `[
{incoming_path: "/v1/chat/completions", upstream_path: "/chat"},
{incoming_path: "/v1/responses", upstream_path: "/chat", models: ["a"], converter: "openai_responses_to_openai_chat_completions", default_enabled: false},
{incoming_path: "/v1/responses", upstream_path: "/responses"},
{incoming_path: "/v1/models", upstream_path: "/models"},
]`
func compileToggles(t *testing.T) *LoadedPlugin {
t.Helper()
plugin, err := CompilePlugin(`export const meta = {`+providerMeta+`, relay: `+toggleRelay+`};`, Options{})
require.NoError(t, err)
return plugin
}
func TestRelayRouteKeyNamesPathAndModels(t *testing.T) {
plugin := compileToggles(t)
keys := make([]string, 0, len(plugin.Meta.Relay))
for _, route := range plugin.Meta.Relay {
keys = append(keys, RelayRouteKey(route))
}
assert.Equal(t, []string{"/v1/chat/completions", "/v1/responses|a", "/v1/responses", "/v1/models"}, keys)
}
func TestDefaultEnabledFalseRouteIsOffUntilTheChannelTurnsItOn(t *testing.T) {
plugin := compileToggles(t)
assert.Equal(t, []bool{false, true, false, false}, plugin.Meta.RelayDefaultOff)
route, ok := plugin.Meta.ChannelRelayRoute(nil, "/v1/responses", "a")
require.True(t, ok, "the catch-all route still serves model a")
assert.Equal(t, "/responses", route.UpstreamPath)
route, ok = plugin.Meta.ChannelRelayRoute(map[string]bool{"/v1/responses|a": true}, "/v1/responses", "a")
require.True(t, ok)
assert.Equal(t, "/chat", route.UpstreamPath)
assert.Len(t, plugin.Meta.ChannelRelayConfig(nil, map[string]bool{"/v1/responses|a": true}).Routes, 4)
assert.Len(t, plugin.Meta.ChannelRelayConfig(nil, nil).Routes, 3)
}
func TestChannelCanSwitchOffADefaultOnRoute(t *testing.T) {
plugin := compileToggles(t)
toggles := map[string]bool{"/v1/responses": false}
_, ok := plugin.Meta.ChannelRelayRoute(toggles, "/v1/responses", "b")
assert.False(t, ok)
_, ok = plugin.Meta.ChannelRelayRoute(toggles, "/v1/chat/completions", "b")
assert.True(t, ok, "other paths are untouched")
assert.False(t, plugin.Meta.ChannelServesResponsesWebSocket(toggles, "b"))
assert.True(t, plugin.Meta.ChannelServesResponsesWebSocket(nil, "b"))
}
func TestManagementRoutesCannotBeSwitchedOff(t *testing.T) {
plugin := compileToggles(t)
_, ok := plugin.Meta.ChannelRelayConfig(nil, map[string]bool{"/v1/models": false}).ModelListRoute()
assert.True(t, ok)
_, err := CompilePlugin(`export const meta = {`+providerMeta+`, relay: [
{incoming_path: "/v1/models", upstream_path: "/models", default_enabled: false},
]};`, Options{})
require.Error(t, err)
assert.Contains(t, err.Error(), "default_enabled is not allowed on /v1/models")
}
func TestDefaultEnabledMustBeBoolean(t *testing.T) {
_, err := CompilePlugin(`export const meta = {`+providerMeta+`, relay: [
{incoming_path: "/v1/chat/completions", upstream_path: "/chat", default_enabled: "no"},
]};`, Options{})
require.Error(t, err)
assert.Contains(t, err.Error(), "relay[0].default_enabled must be a boolean")
}
func TestNormalizeRouteTogglesKeepsOnlyChangesFromDefaults(t *testing.T) {
plugin := compileToggles(t)
normalized := plugin.Meta.NormalizeRouteToggles(map[string]bool{
"/v1/chat/completions": true, // its default
"/v1/responses|a": true, // differs
"/v1/responses": false, // differs
"/v1/models": false, // management route
"/v1/unknown": false, // no such route
})
assert.Equal(t, map[string]bool{"/v1/responses|a": true, "/v1/responses": false}, normalized)
assert.Nil(t, plugin.Meta.NormalizeRouteToggles(map[string]bool{"/v1/chat/completions": true}))
}
+2 -2
View File
@@ -97,8 +97,8 @@ export type RelayFormat = "openai" | "openai_responses" | "openai_responses_comp
export type RelayConverterName = "openai_chat_completions_to_anthropic_messages" | "openai_chat_completions_to_openai_responses" | "openai_chat_completions_to_gemini_generate_content" | "openai_responses_to_openai_chat_completions" | "openai_responses_to_gemini_generate_content" | "openai_responses_to_claude_messages" | "anthropic_messages_to_openai_chat_completions" | "claude_messages_to_openai_responses" | "gemini_generate_content_to_openai_chat_completions" | "gemini_generate_content_to_openai_responses" | "jina_rerank_to_sglang";
/** none (default), a converter, "plugin" for the plugin's convert hooks, or "<converter>+plugin" for that converter's upstream protocol converted by the hooks. */
export type RelayConverter = "none" | RelayConverterName | "plugin" | `${RelayConverterName}+plugin`;
/** One meta.relay route. incoming_path: the client path, starting with /, without a query; {model} may stand for one path segment, once; a :generateContent path also serves :streamGenerateContent. upstream_path: a path starting with a single /, joined to the channel Base URL, or an absolute http(s) URL; {model} is replaced with the upstream model; it may start with {config.<name>}, a format url field of meta.channelConfig, and an empty address is the channel Base URL. models: names, or "re:" and an RE2 expression; an empty list is the route for every other model of its path, one per path, last. auth: without it the key is sent as Authorization: Bearer; {api_key} in value stands for the key. pass_through_body_enabled: only with converter none or jina_rerank_to_sglang. /v1/models and /v1/dashboard/billing/credit_grants take at most one route each, without models, {model} or pass-through; on /v1/models "plugin" runs convertResponse alone. These are the rules of a new-api Advanced Custom channel route. */
export interface RelayRoute {incoming_path: string; upstream_path: string; converter?: RelayConverter; models?: readonly string[]; auth?: {type: "none" | "header" | "query"; name?: string; value?: string}; pass_through_body_enabled?: boolean}
/** One meta.relay route. incoming_path: the client path, starting with /, without a query; {model} may stand for one path segment, once; a :generateContent path also serves :streamGenerateContent. upstream_path: a path starting with a single /, joined to the channel Base URL, or an absolute http(s) URL; {model} is replaced with the upstream model; it may start with {config.<name>}, a format url field of meta.channelConfig, and an empty address is the channel Base URL. models: names, or "re:" and an RE2 expression; an empty list is the route for every other model of its path, one per path, last. auth: without it the key is sent as Authorization: Bearer; {api_key} in value stands for the key. pass_through_body_enabled: only with converter none or jina_rerank_to_sglang. /v1/models and /v1/dashboard/billing/credit_grants take at most one route each, without models, {model} or pass-through; on /v1/models "plugin" runs convertResponse alone. default_enabled (true by default): whether a channel serves the route before an administrator switches it on the channel; the management routes are always on. These are the rules of a new-api Advanced Custom channel route, plus default_enabled. */
export interface RelayRoute {incoming_path: string; upstream_path: string; converter?: RelayConverter; models?: readonly string[]; auth?: {type: "none" | "header" | "query"; name?: string; value?: string}; pass_through_body_enabled?: boolean; default_enabled?: boolean}
/** One field of an instance config: a JSON Schema subset. title is required; nesting is at most 4 levels; unit, visibleWhen and every format but url are form hints that never change the check, the defaults or the config. A non-empty url value must be an absolute http(s) URL without credentials or fragment, and its host is one utils.fetch may address in ingress, egress, reply and report; password marks a secret the form hides. The form shows a slider for an integer field whose minimum and maximum are both set and at most 100 apart. */
export interface ConfigField {type: "string" | "number" | "integer" | "boolean" | "array" | "object"; title: LocalizedText; description?: LocalizedText; default?: JSONValue; examples?: readonly JSONValue[]; enum?: readonly (string | number)[]; enumTitles?: readonly LocalizedText[]; minimum?: number; maximum?: number; /** number and integer fields: byte values get a KB/MB choice (1000-based, stored in bytes), the others a suffix. */ unit?: "byte" | "pixel" | "character" | "second"; minLength?: number; maxLength?: number; /** RE2 regular expression. */ pattern?: string; /** string: textarea, regex, url, password, keywords (a property of the schema itself only); object: json. */ format?: "textarea" | "regex" | "url" | "password" | "keywords" | "json"; items?: ConfigField; minItems?: number; maxItems?: number; uniqueItems?: boolean; properties?: Readonly<Record<string, ConfigField>>; required?: readonly string[]; /** meta.channelConfig only, on an object field without properties: a value per model, keyed by model name. A string, number, integer or boolean field without default or visibleWhen. */ additionalProperties?: ConfigField; /** A property only, not an items field: shown while every named sibling property (string, number, integer or boolean) holds one of the listed values. Values must be valid for that sibling; lists are non-empty without repeats. API responses always write lists. */ visibleWhen?: Readonly<Record<string, string | number | boolean | readonly (string | number | boolean)[]>>}
/** The schema of a request processing instance's config. Without it the config is {}. */
+14
View File
@@ -1205,6 +1205,20 @@ route.
it standing for the key.
- `pass_through_body_enabled`: sends the client body as it came. Only with
converter `none` or `jina_rerank_to_sglang`.
- `default_enabled`: whether a channel serves the route before an
administrator switches it, `true` by default. Every route but the management
routes has a switch on the channel form, stored per channel in
`plugin_routes` only when it differs from this default. A channel does not
take requests for a route that is off for it: selection skips the channel
for that path and model, and the relay, the channel test and the Responses
WebSocket check do not see the route. Another route of the same path still
serves the models it accepts. The management routes are always on and cannot
have `default_enabled: false`. Only a plugin route has this key.
A channel's `plugin_routes` names each route by its `incoming_path`, followed by
`|` and its `models` joined with `,` when it lists models. A switch whose name
matches no route, after an update of the plugin, is dropped the next time the
channel is saved.
`/v1/models` and `/v1/dashboard/billing/credit_grants` are management routes:
at most one each, with no `models`, converter `none` (`/v1/models` also takes
+3 -2
View File
@@ -180,9 +180,10 @@
"required": ["type"],
"properties": {"type": {"enum": ["none", "header", "query"]}, "name": {"type": "string"}, "value": {"type": "string"}}
},
"pass_through_body_enabled": {"type": "boolean"}
"pass_through_body_enabled": {"type": "boolean"},
"default_enabled": {"type": "boolean", "default": true, "description": "Whether a channel serves the route before an administrator switches it on the channel. Not false on /v1/models or /v1/dashboard/billing/credit_grants."}
},
"description": "The keys of an Advanced Custom channel route; the host applies the same validation rules."
"description": "The keys of an Advanced Custom channel route, plus default_enabled; the host applies the same validation rules."
},
"upstreamKind": {"enum": ["vendor", "new_api"]},
"upstreamContext": {
+1 -1
View File
@@ -526,7 +526,7 @@ func (a *Adaptor) bind(c *gin.Context, info *relaycommon.RelayInfo) error {
if c.Request != nil && c.Request.URL != nil {
path = c.Request.URL.Path
}
route, ok := a.plugin.Meta.RelayRoute(strings.Split(path, "?")[0], info.OriginModelName)
route, ok := a.plugin.Meta.ChannelRelayRoute(info.ChannelOtherSettings.PluginRoutes, strings.Split(path, "?")[0], info.OriginModelName)
if !ok {
return fmt.Errorf("plugin %s has no relay route for %s and model %s", a.plugin.Meta.Key, path, info.OriginModelName)
}
@@ -76,7 +76,7 @@ func TestFetchModelListPagesAndExchangesAgainOn401(t *testing.T) {
ChannelId: 910_001,
ChannelBaseUrl: upstream.URL,
ApiKey: "sk-paged",
ChannelOtherSettings: dto.ChannelOtherSettings{AdvancedCustom: plugin.Meta.ChannelRelayConfig(nil)},
ChannelOtherSettings: dto.ChannelOtherSettings{AdvancedCustom: plugin.Meta.ChannelRelayConfig(nil, nil)},
},
}
@@ -118,7 +118,7 @@ export function convertResponse() { return {next: {path: "/models"}}; }
ChannelId: 910_002,
ChannelBaseUrl: upstream.URL,
ApiKey: "sk-endless",
ChannelOtherSettings: dto.ChannelOtherSettings{AdvancedCustom: plugin.Meta.ChannelRelayConfig(nil)},
ChannelOtherSettings: dto.ChannelOtherSettings{AdvancedCustom: plugin.Meta.ChannelRelayConfig(nil, nil)},
},
}
@@ -161,7 +161,7 @@ export function parseBalance(ctx, res) { return {amount: JSON.parse(res.body).us
ChannelId: 910_003,
ChannelBaseUrl: base.URL,
ApiKey: "sk-balance",
ChannelOtherSettings: dto.ChannelOtherSettings{AdvancedCustom: plugin.Meta.ChannelRelayConfig(nil)},
ChannelOtherSettings: dto.ChannelOtherSettings{AdvancedCustom: plugin.Meta.ChannelRelayConfig(nil, nil)},
},
}
return QueryBalance(context.Background(), plugin, info, ManagementClient{
+1 -1
View File
@@ -726,7 +726,7 @@ func connectionOtherSettings(c *gin.Context, channel *appmodel.Channel) dto.Chan
otherSettings := channel.GetOtherSettings()
pinned, _ := common.GetContextKey(c, appconstant.ContextKeyProviderPlugin)
if plugin, ok := pinned.(jsplugin.PinnedPlugin); ok && channel.Type == appconstant.ChannelTypeTaskPlugin {
otherSettings.AdvancedCustom = plugin.Plugin.Meta.ChannelRelayConfig(plugin.Plugin.ChannelConfigFor(otherSettings.PluginConfig))
otherSettings.AdvancedCustom = plugin.Plugin.Meta.ChannelRelayConfig(plugin.Plugin.ChannelConfigFor(otherSettings.PluginConfig), otherSettings.PluginRoutes)
}
return otherSettings
}
+4
View File
@@ -147,6 +147,10 @@ type ChannelOtherSettings struct {
// PluginConfig is the config a type-61 channel gives its plugin, checked
// against the plugin's meta.channelConfig when the channel is saved.
PluginConfig json.RawMessage `json:"plugin_config,omitempty"`
// PluginRoutes switches relay routes of a type-61 channel's plugin on or
// off, keyed by route (see pluginkit.RelayRouteKey). Only entries that
// differ from the route's default are kept.
PluginRoutes map[string]bool `json:"plugin_routes,omitempty"`
}
func (s *ChannelOtherSettings) IsOpenRouterEnterprise() bool {
+14
View File
@@ -133,10 +133,24 @@ export type TaskPluginOption = {
balance?: boolean
/** The client paths of the plugin's relay routes. */
relayPaths?: string[] | null
/** The relay routes a channel of the plugin can switch on or off. */
relayRoutes?: PluginRelayRoute[] | null
/** A channel of the plugin can serve the Responses WebSocket. */
responsesWebsocket?: boolean
}
/** A relay route of a plugin, as a channel switches it. */
export type PluginRelayRoute = {
/** Its name in the channel's plugin_routes. */
key: string
incoming_path: string
upstream_path: string
converter?: string
models?: string[] | null
/** Whether a channel that has not switched it serves it. */
default_enabled: boolean
}
/** The plugins a channel can be bound to: request processing alone is not one. */
export async function getTaskPluginOptions(): Promise<TaskPluginOption[]> {
const response = await api.get<{
@@ -0,0 +1,127 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { cleanup, render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { FormProvider, useForm } from 'react-hook-form'
import { afterEach, expect, test } from 'vitest'
import type { PluginRelayRoute } from '../../api'
import {
CHANNEL_FORM_DEFAULT_VALUES,
transformFormDataToCreatePayload,
type ChannelFormValues,
} from '../../lib/channel-form'
import { PluginChannelRoutes } from '../plugin-channel-routes'
const routes: PluginRelayRoute[] = [
{
key: '/v1/chat/completions',
incoming_path: '/v1/chat/completions',
upstream_path: '/chat',
default_enabled: true,
},
{
key: '/v1/responses',
incoming_path: '/v1/responses',
upstream_path: '/chat',
converter: 'openai_responses_to_openai_chat_completions',
default_enabled: false,
},
]
let form: ReturnType<typeof useForm<ChannelFormValues>>
function Harness(props: {
toggles?: Record<string, boolean>
disabled?: boolean
}) {
form = useForm<ChannelFormValues>({
defaultValues: {
...CHANNEL_FORM_DEFAULT_VALUES,
type: 61,
task_plugin_key: 'vendor-x',
plugin_routes: props.toggles ?? {},
},
})
return (
<FormProvider {...form}>
<PluginChannelRoutes routes={routes} disabled={props.disabled} />
</FormProvider>
)
}
/** The plugin_routes the channel would save. */
function savedRoutes(): unknown {
const payload = transformFormDataToCreatePayload(form.getValues())
return JSON.parse(payload.channel.settings ?? '{}').plugin_routes
}
afterEach(() => {
cleanup()
})
test('a new channel shows each route at its plugin default and saves no switches', () => {
render(<Harness />)
expect(
screen.getByRole('switch', { name: '/v1/chat/completions' })
).toBeChecked()
expect(
screen.getByRole('switch', { name: '/v1/responses' })
).not.toBeChecked()
expect(screen.getByText('1 of 2 on')).toBeInTheDocument()
expect(savedRoutes()).toBeUndefined()
})
test('turning on a route that is off by default saves that switch', async () => {
const user = userEvent.setup()
render(<Harness />)
await user.click(screen.getByRole('switch', { name: '/v1/responses' }))
expect(screen.getByRole('switch', { name: '/v1/responses' })).toBeChecked()
expect(screen.getByText('2 of 2 on')).toBeInTheDocument()
expect(savedRoutes()).toEqual({ '/v1/responses': true })
})
test('switching a route back to its default removes the saved switch', async () => {
const user = userEvent.setup()
render(<Harness toggles={{ '/v1/responses': true }} />)
await user.click(screen.getByRole('switch', { name: '/v1/responses' }))
expect(savedRoutes()).toBeUndefined()
})
test('turning off a route that is on by default saves it as off', async () => {
const user = userEvent.setup()
render(<Harness />)
await user.click(screen.getByRole('switch', { name: '/v1/chat/completions' }))
expect(savedRoutes()).toEqual({ '/v1/chat/completions': false })
})
test('a locked form keeps the switches disabled', () => {
render(<Harness disabled />)
for (const toggle of screen.getAllByRole('switch')) {
expect(toggle).toHaveAttribute('aria-disabled', 'true')
}
})
@@ -237,6 +237,7 @@ import {
type ModelMappingDraftRequest,
} from '../model-mapping-editor'
import { ModelRedirectPanel } from '../model-redirect-panel'
import { PluginChannelRoutes } from '../plugin-channel-routes'
import { ResponsesWebSocketSetting } from '../responses-websocket-setting'
import { UpstreamModelSelection } from '../upstream-model-selection'
import {
@@ -357,6 +358,7 @@ const SENSITIVE_FORM_FIELDS = [
'upstream_model_update_auto_sync_enabled',
'upstream_model_update_ignored_models',
'plugin_config',
'plugin_routes',
'plugin_config_draft',
] satisfies (keyof ChannelFormValues)[]
@@ -909,6 +911,7 @@ export function ChannelMutateDrawer({
// Settings belong to the plugin that declared them.
if (previousKey !== plugin.key) {
form.setValue('plugin_config', {}, { shouldDirty: true })
form.setValue('plugin_routes', {}, { shouldDirty: true })
form.setValue('plugin_config_draft', null, { shouldDirty: true })
}
if (!plugin.responsesWebsocket) {
@@ -5006,6 +5009,12 @@ export function ChannelMutateDrawer({
}
routing={
<>
{boundTaskPlugin?.relayRoutes?.length ? (
<PluginChannelRoutes
routes={boundTaskPlugin.relayRoutes}
disabled={sensitiveLocked || isSubmitting}
/>
) : null}
{redirectPanelActive ? redirectPanelNotice : modelMappingFields}
{routingFields}
</>
@@ -0,0 +1,134 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { ArrowRight, Route, Shuffle } from 'lucide-react'
import { useFormContext, useWatch } from 'react-hook-form'
import { useTranslation } from 'react-i18next'
import { Badge } from '@/components/ui/badge'
import { Switch } from '@/components/ui/switch'
import { cn } from '@/lib/utils'
import type { PluginRelayRoute } from '../api'
import type { ChannelFormValues } from '../lib/channel-form'
import {
nextPluginRouteToggles,
pluginRouteConverterLabel,
} from '../lib/plugin-routes'
type PluginChannelRoutesProps = {
routes: PluginRelayRoute[]
disabled?: boolean
}
/**
* The relay routes of the bound plugin, each with a switch that turns it on
* or off for this channel. The switches are kept in plugin_routes.
*/
export function PluginChannelRoutes(props: PluginChannelRoutesProps) {
const { t } = useTranslation()
const form = useFormContext<ChannelFormValues>()
const toggles = useWatch({ control: form.control, name: 'plugin_routes' })
const isOn = (route: PluginRelayRoute) =>
toggles?.[route.key] ?? route.default_enabled
const onCount = props.routes.filter(isOn).length
return (
<div role='group' aria-label={t('Plugin routes')} className='space-y-3'>
<div className='flex items-center justify-between gap-2'>
<div className='flex items-center gap-2'>
<Route
className='text-muted-foreground size-3.5'
aria-hidden='true'
/>
<h4 className='text-muted-foreground text-xs font-medium tracking-wide uppercase'>
{t('Plugin routes')}
</h4>
</div>
<Badge variant='secondary'>
{t('{{on}} of {{total}} on', {
on: onCount,
total: props.routes.length,
})}
</Badge>
</div>
<ul className='divide-y rounded-xl border'>
{props.routes.map((route) => {
const converter = route.converter?.trim() ?? ''
const native = converter === '' || converter === 'none'
const on = isOn(route)
return (
<li
key={route.key}
className='flex items-center justify-between gap-3 px-4 py-3'
>
<div className={cn('min-w-0 space-y-1.5', !on && 'opacity-50')}>
<div className='flex min-w-0 flex-wrap items-center gap-2 font-mono text-sm'>
<span className='break-all'>{route.incoming_path}</span>
<ArrowRight
className='text-muted-foreground size-3.5 shrink-0'
aria-hidden='true'
/>
<span className='text-muted-foreground break-all'>
{route.upstream_path}
</span>
</div>
<div className='flex flex-wrap items-center gap-1.5'>
<Badge variant={native ? 'secondary' : 'outline'}>
{native ? (
<ArrowRight aria-hidden='true' />
) : (
<Shuffle aria-hidden='true' />
)}
{t(pluginRouteConverterLabel(converter))}
</Badge>
<Badge variant='outline' className='font-normal'>
{route.models?.length
? route.models.join(', ')
: t('All models')}
</Badge>
</div>
</div>
<Switch
checked={on}
disabled={props.disabled}
aria-label={
route.models?.length
? `${route.incoming_path} (${route.models.join(', ')})`
: route.incoming_path
}
onCheckedChange={(checked) =>
form.setValue(
'plugin_routes',
nextPluginRouteToggles(
props.routes,
toggles ?? {},
route.key,
checked
),
{ shouldDirty: true }
)
}
/>
</li>
)
})}
</ul>
</div>
)
}
@@ -299,6 +299,9 @@ export const channelFormSchema = z
upstream_model_update_ignored_models: z.string().optional(),
// The bound plugin's channel settings (type 61, stored in settings JSON)
plugin_config: z.record(z.string(), z.unknown()).optional(),
// Switches of the bound plugin's relay routes that differ from their
// defaults (type 61, stored in settings JSON)
plugin_routes: z.record(z.string(), z.boolean()).optional(),
// Their values as typed, null until edited (not sent to backend)
plugin_config_draft: z
.record(z.string(), z.unknown())
@@ -501,6 +504,7 @@ export const CHANNEL_FORM_DEFAULT_VALUES: ChannelFormValues = {
upstream_model_update_ignored_models: '',
advanced_custom: '',
plugin_config: {},
plugin_routes: {},
plugin_config_draft: null,
}
@@ -586,6 +590,7 @@ export function transformChannelToFormDefaults(
let upstreamModelUpdateIgnoredModels = ''
let advancedCustom = ''
let pluginConfig: Record<string, unknown> = {}
let pluginRoutes: Record<string, boolean> = {}
if (channel.settings) {
try {
@@ -622,6 +627,13 @@ export function transformChannelToFormDefaults(
if (isJsonObjectValue(parsed.plugin_config)) {
pluginConfig = parsed.plugin_config
}
if (isJsonObjectValue(parsed.plugin_routes)) {
pluginRoutes = Object.fromEntries(
Object.entries(parsed.plugin_routes).filter(
(entry): entry is [string, boolean] => typeof entry[1] === 'boolean'
)
)
}
} catch (error) {
// eslint-disable-next-line no-console
console.error('Failed to parse channel settings:', error)
@@ -678,6 +690,7 @@ export function transformChannelToFormDefaults(
upstream_model_update_ignored_models: upstreamModelUpdateIgnoredModels,
advanced_custom: advancedCustom,
plugin_config: pluginConfig,
plugin_routes: pluginRoutes,
plugin_config_draft: null,
}
}
@@ -896,6 +909,14 @@ function buildSettingsJSON(formData: ChannelFormValues): string {
} else {
delete settingsObj.plugin_config
}
if (
formData.type === CHANNEL_TYPE_TASK_PLUGIN &&
Object.keys(formData.plugin_routes ?? {}).length > 0
) {
settingsObj.plugin_routes = formData.plugin_routes
} else {
delete settingsObj.plugin_routes
}
return JSON.stringify(settingsObj)
}
@@ -0,0 +1,54 @@
/*
Copyright (C) 2023-2026 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import type { PluginRelayRoute } from '../api'
import { ADVANCED_CUSTOM_CONVERTER_OPTIONS } from './advanced-custom'
/** The label key of a route converter; a hooks chain names its converter. */
export function pluginRouteConverterLabel(converter?: string): string {
const value = converter?.trim() ?? ''
if (value === '' || value === 'none') return 'Native forwarding'
if (value === 'plugin') return 'Converted by the plugin'
const base = value.endsWith('+plugin')
? value.slice(0, -'+plugin'.length)
: value
return (
ADVANCED_CUSTOM_CONVERTER_OPTIONS.find((option) => option.value === base)
?.label ?? base
)
}
/**
* The switches a channel keeps for its plugin's routes after one changes:
* only those that differ from the route's default.
*/
export function nextPluginRouteToggles(
routes: PluginRelayRoute[],
toggles: Record<string, boolean>,
key: string,
on: boolean
): Record<string, boolean> {
const next: Record<string, boolean> = {}
for (const route of routes) {
const value = route.key === key ? on : toggles[route.key]
if (value !== undefined && value !== route.default_enabled) {
next[route.key] = value
}
}
return next
}
+3 -1
View File
@@ -7816,6 +7816,8 @@
"Zhipu": "Zhipu",
"Zhipu GLM": "Zhipu GLM",
"Zhipu V4": "Zhipu V4",
"Zoom": "Zoom"
"Zoom": "Zoom",
"Plugin routes": "Plugin routes",
"{{on}} of {{total}} on": "{{on}} of {{total}} on"
}
}
+3 -1
View File
@@ -7816,6 +7816,8 @@
"Zhipu": "Zhipu",
"Zhipu GLM": "Zhipu GLM",
"Zhipu V4": "Zhipu V4",
"Zoom": "Zoom"
"Zoom": "Zoom",
"Plugin routes": "Routes du plugin",
"{{on}} of {{total}} on": "{{on}} sur {{total}} activées"
}
}
+3 -1
View File
@@ -7816,6 +7816,8 @@
"Zhipu": "Zhipu",
"Zhipu GLM": "Zhipu GLM",
"Zhipu V4": "Zhipu V 4",
"Zoom": "ズーム"
"Zoom": "ズーム",
"Plugin routes": "プラグインルート",
"{{on}} of {{total}} on": "{{total}} 件中 {{on}} 件オン"
}
}
+3 -1
View File
@@ -7816,6 +7816,8 @@
"Zhipu": "Zhipu",
"Zhipu GLM": "Zhipu GLM",
"Zhipu V4": "Zhipu V4",
"Zoom": "Zoom"
"Zoom": "Zoom",
"Plugin routes": "Маршруты плагина",
"{{on}} of {{total}} on": "Включено {{on}} из {{total}}"
}
}
+3 -1
View File
@@ -7816,6 +7816,8 @@
"Zhipu": "Zhipu",
"Zhipu GLM": "Zhipu GLM",
"Zhipu V4": "Zhipu V4",
"Zoom": "Zoom"
"Zoom": "Zoom",
"Plugin routes": "Tuyến của plugin",
"{{on}} of {{total}} on": "Đã bật {{on}}/{{total}}"
}
}
+3 -1
View File
@@ -7816,6 +7816,8 @@
"Zhipu": "智譜",
"Zhipu GLM": "智譜GLM",
"Zhipu V4": "智譜 V4",
"Zoom": "縮放"
"Zoom": "縮放",
"Plugin routes": "外掛路由",
"{{on}} of {{total}} on": "已開啟 {{on}}/{{total}}"
}
}
+3 -1
View File
@@ -7816,6 +7816,8 @@
"Zhipu": "智谱",
"Zhipu GLM": "智谱GLM",
"Zhipu V4": "智谱 V4",
"Zoom": "缩放"
"Zoom": "缩放",
"Plugin routes": "插件路由",
"{{on}} of {{total}} on": "已开启 {{on}}/{{total}}"
}
}