From c063a4016eeebdc21d3ebd07e792194576119433 Mon Sep 17 00:00:00 2001 From: SavitarC <71271200+SavitarC@users.noreply.github.com> Date: Sun, 27 Sep 2026 11:08:41 +0800 Subject: [PATCH 01/19] =?UTF-8?q?refactor(provider):=20=E4=BB=A5=20provide?= =?UTF-8?q?r=20profile=20=E6=94=B6=E6=95=9B=E5=A4=9A=E5=8D=8F=E8=AE=AE?= =?UTF-8?q?=E4=BE=9B=E5=BA=94=E5=95=86=E9=BB=98=E8=AE=A4=E7=AB=AF=E7=82=B9?= =?UTF-8?q?=E8=A1=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 多协议 API Key 供应商(kimi/zhipu/deepseek/minimax/opencode_go)的默认端点 此前在 account.go 的 GetOpenAIBaseURL / defaultCNProtocolBaseURL / GetAnthropicProtocolBaseURL / GetOpenAIFormatBaseURL 中按平台 switch 重复了 四遍,Responses 能力与 OpenCode 内置分流表也各自散落。 新增 provider_profile.go 作为单一数据来源:每个供应商登记各接入模式的 Chat/Anthropic 默认基址、内置 protocol_rules 与原生 Responses 能力; 上述函数、SupportsNativeCNResponses、IsMultiProtocolAPIKeyProvider 与 defaultOpenCodeProtocolRules 改为查表。纯重构,行为不变:新增测试以旧 switch 逻辑为基准,逐一核对平台 × account_mode × 协议的全部组合。 Co-Authored-By: Claude Opus 5.5 --- backend/internal/service/account.go | 118 ++------------ backend/internal/service/domain_constants.go | 3 +- backend/internal/service/opencode_go.go | 20 +-- backend/internal/service/provider_profile.go | 152 ++++++++++++++++++ .../internal/service/provider_profile_test.go | 144 +++++++++++++++++ 5 files changed, 311 insertions(+), 126 deletions(-) create mode 100644 backend/internal/service/provider_profile.go create mode 100644 backend/internal/service/provider_profile_test.go diff --git a/backend/internal/service/account.go b/backend/internal/service/account.go index 5262134a2b..fd60f098ef 100644 --- a/backend/internal/service/account.go +++ b/backend/internal/service/account.go @@ -1399,27 +1399,11 @@ func (a *Account) GetOpenAIBaseURL() string { return baseURL } } - // 平台默认 base_url:CN 供应商按 account_mode 选择 payg / coding 默认值。 - switch a.Platform { - case PlatformKimi: - if a.GetAccountMode() == AccountModeCoding { - return DefaultKimiCodingBaseURL - } - return DefaultKimiPayGBaseURL - case PlatformZhipu: - if a.GetAccountMode() == AccountModeCoding { - return DefaultZhipuCodingBaseURL - } - return DefaultZhipuPayGBaseURL - case PlatformDeepseek: - return DefaultDeepseekBaseURL - case PlatformMiniMax: - return DefaultMiniMaxBaseURL - case PlatformOpenCodeGo: - return a.openCodeDefaultChatBaseURL() - default: - return "https://api.openai.com" + // 平台默认 base_url:多协议供应商按 account_mode 查 provider profile。 + if baseURL := a.defaultProviderBaseURL(APIProtocolChatCompletions); baseURL != "" { + return baseURL } + return "https://api.openai.com" } // GetAccountMode 返回国产供应商账号的接入模式(payg / coding);非国产供应商或未设置时 @@ -1470,15 +1454,8 @@ func (a *Account) GetAPIProtocol() string { // DeepSeek 官方为 /responses(无 /v1);Kimi 按量付费与 Coding Plan 均为 // /v1/responses(moonshot.cn / kimi.com/coding);MiniMax 为 /v1/responses。 func (a *Account) SupportsNativeCNResponses() bool { - if a == nil { - return false - } - switch a.Platform { - case PlatformDeepseek, PlatformKimi, PlatformMiniMax, PlatformOpenCodeGo: - return true - default: - return false - } + profile := a.providerProfile() + return profile != nil && profile.NativeResponses } // UsesNativeCNResponses 报告当前账号是否应按原生 Responses 协议转发 @@ -1519,48 +1496,7 @@ func (a *Account) GetCNProtocolBaseURL(protocol string) string { } } } - return a.defaultCNProtocolBaseURL(protocol) -} - -func (a *Account) defaultCNProtocolBaseURL(protocol string) string { - switch protocol { - case APIProtocolAnthropic: - switch a.Platform { - case PlatformKimi: - if a.GetAccountMode() == AccountModeCoding { - return DefaultKimiCodingAnthropicBaseURL - } - return DefaultKimiPayGAnthropicBaseURL - case PlatformZhipu: - return DefaultZhipuAnthropicBaseURL - case PlatformDeepseek: - return DefaultDeepseekAnthropicBaseURL - case PlatformMiniMax: - return DefaultMiniMaxAnthropicBaseURL - case PlatformOpenCodeGo: - return a.openCodeDefaultAnthropicBaseURL() - } - case APIProtocolChatCompletions, APIProtocolResponses: - switch a.Platform { - case PlatformKimi: - if a.GetAccountMode() == AccountModeCoding { - return DefaultKimiCodingBaseURL - } - return DefaultKimiPayGBaseURL - case PlatformZhipu: - if a.GetAccountMode() == AccountModeCoding { - return DefaultZhipuCodingBaseURL - } - return DefaultZhipuPayGBaseURL - case PlatformDeepseek: - return DefaultDeepseekBaseURL - case PlatformMiniMax: - return DefaultMiniMaxBaseURL - case PlatformOpenCodeGo: - return a.openCodeDefaultChatBaseURL() - } - } - return "" + return a.defaultProviderBaseURL(protocol) } // IsAnthropicProtocol 报告账号是否以原生 Anthropic 协议接入上游 @@ -1584,23 +1520,7 @@ func (a *Account) GetAnthropicProtocolBaseURL() string { return baseURL } } - switch a.Platform { - case PlatformKimi: - if a.GetAccountMode() == AccountModeCoding { - return DefaultKimiCodingAnthropicBaseURL - } - return DefaultKimiPayGAnthropicBaseURL - case PlatformZhipu: - return DefaultZhipuAnthropicBaseURL - case PlatformDeepseek: - return DefaultDeepseekAnthropicBaseURL - case PlatformMiniMax: - return DefaultMiniMaxAnthropicBaseURL - case PlatformOpenCodeGo: - return a.openCodeDefaultAnthropicBaseURL() - default: - return "" - } + return a.defaultProviderBaseURL(APIProtocolAnthropic) } // GetOpenAIFormatBaseURL 返回供 OpenAI 格式端点(/v1/models、/v1/chat/completions @@ -1612,26 +1532,10 @@ func (a *Account) GetOpenAIFormatBaseURL() string { if a == nil || !a.IsAnthropicProtocol() { return a.GetOpenAIBaseURL() } - switch a.Platform { - case PlatformKimi: - if a.GetAccountMode() == AccountModeCoding { - return DefaultKimiCodingBaseURL - } - return DefaultKimiPayGBaseURL - case PlatformZhipu: - if a.GetAccountMode() == AccountModeCoding { - return DefaultZhipuCodingBaseURL - } - return DefaultZhipuPayGBaseURL - case PlatformDeepseek: - return DefaultDeepseekBaseURL - case PlatformMiniMax: - return DefaultMiniMaxBaseURL - case PlatformOpenCodeGo: - return a.openCodeDefaultChatBaseURL() - default: - return a.GetOpenAIBaseURL() + if baseURL := a.defaultProviderBaseURL(APIProtocolChatCompletions); baseURL != "" { + return baseURL } + return a.GetOpenAIBaseURL() } // GetCNAPIKey 返回国产 OpenAI 兼容供应商账号的 api_key 凭据(kimi/zhipu/deepseek)。 diff --git a/backend/internal/service/domain_constants.go b/backend/internal/service/domain_constants.go index e29b4639c0..014e6f6bb9 100644 --- a/backend/internal/service/domain_constants.go +++ b/backend/internal/service/domain_constants.go @@ -118,8 +118,9 @@ func IsOpenCodeGo(platform string) bool { // IsMultiProtocolAPIKeyProvider 报告 platform 是否为多协议 API Key 网关 // (国产供应商 + OpenCode):走 OpenAI 网关、支持 adaptive 协议分流。 +// 归属以 provider profile 登记为准(见 provider_profile.go)。 func IsMultiProtocolAPIKeyProvider(platform string) bool { - return IsCNProvider(platform) || platform == PlatformOpenCodeGo + return LookupProviderProfile(platform) != nil } // AllowedQuotaPlatforms 是允许设置 user × platform quota 的平台列表(单一权威来源)。 diff --git a/backend/internal/service/opencode_go.go b/backend/internal/service/opencode_go.go index 68a5437664..073a7bd116 100644 --- a/backend/internal/service/opencode_go.go +++ b/backend/internal/service/opencode_go.go @@ -133,11 +133,9 @@ func DefaultOpenCodeZenProtocolRules() []OpenCodeGoProtocolRule { } } +// defaultOpenCodeProtocolRules 从 provider profile 取该接入模式的内置分流表。 func defaultOpenCodeProtocolRules(mode string) []OpenCodeGoProtocolRule { - if mode == AccountModeZen { - return DefaultOpenCodeZenProtocolRules() - } - return DefaultOpenCodeGoProtocolRules() + return LookupProviderProfile(PlatformOpenCodeGo).Endpoints(mode).ProtocolRules } func isNativeOpenCodeGoProtocol(protocol string) bool { @@ -308,20 +306,6 @@ func (a *Account) IsOpenCodeGoPlan() bool { return a.GetOpenCodeAccountMode() == AccountModeGo } -func (a *Account) openCodeDefaultChatBaseURL() string { - if a.IsOpenCodeZen() { - return DefaultOpenCodeZenBaseURL - } - return DefaultOpenCodeGoBaseURL -} - -func (a *Account) openCodeDefaultAnthropicBaseURL() string { - if a.IsOpenCodeZen() { - return DefaultOpenCodeZenAnthropicBaseURL - } - return DefaultOpenCodeGoAnthropicBaseURL -} - func (a *Account) IsMultiProtocolAPIKey() bool { return a != nil && IsMultiProtocolAPIKeyProvider(a.Platform) } diff --git a/backend/internal/service/provider_profile.go b/backend/internal/service/provider_profile.go new file mode 100644 index 0000000000..bc7e0b7c35 --- /dev/null +++ b/backend/internal/service/provider_profile.go @@ -0,0 +1,152 @@ +package service + +import "strings" + +// ProviderEndpoints 是多协议 API Key 供应商在某个接入模式下的官方默认端点与 +// 内置分流规则。账号凭证里的 base_url / api_base_urls / protocol_rules 仍优先于这里。 +type ProviderEndpoints struct { + // ChatBaseURL 供 Chat Completions / Responses / models 共用。 + ChatBaseURL string + // AnthropicBaseURL 是 Anthropic 协议基址,上游路径为 {base}/v1/messages。 + AnthropicBaseURL string + // ProtocolRules 是按模型分流的内置默认表(首条命中生效);为空表示该模式 + // 不按模型分流,由账号 api_protocol 决定上游协议。 + ProtocolRules []OpenCodeGoProtocolRule +} + +// ProviderProfile 描述一个多协议 API Key 供应商(国产厂商或多模型聚合平台)的 +// 静态数据:各接入模式的默认端点、能力开关与内置分流规则。 +// 额度解析、会话头等行为差异不在这里,仍由各自的代码路径处理。 +type ProviderProfile struct { + Platform string + // DefaultMode 在 credentials.account_mode 缺失或不在 Modes 中时使用。 + DefaultMode string + Modes map[string]ProviderEndpoints + // NativeResponses 表示上游提供原生 Responses 端点。 + NativeResponses bool +} + +// Endpoints 返回指定接入模式的端点;未知模式回落 DefaultMode。 +func (p *ProviderProfile) Endpoints(mode string) ProviderEndpoints { + if p == nil { + return ProviderEndpoints{} + } + if endpoints, ok := p.Modes[strings.TrimSpace(mode)]; ok { + return endpoints + } + return p.Modes[p.DefaultMode] +} + +// DefaultBaseURL 返回指定接入模式与上游协议的官方默认基址;协议未知时为空串。 +func (p *ProviderProfile) DefaultBaseURL(mode, protocol string) string { + endpoints := p.Endpoints(mode) + switch protocol { + case APIProtocolAnthropic: + return endpoints.AnthropicBaseURL + case APIProtocolChatCompletions, APIProtocolResponses: + return endpoints.ChatBaseURL + default: + return "" + } +} + +// providerProfiles 是多协议 API Key 供应商的单一数据来源。新增同类供应商时在此 +// 登记一条即可获得默认端点、Responses 能力判定与 IsMultiProtocolAPIKeyProvider 归属。 +// 默认端点需与前端 credentialsBuilder.ts 的预设保持一致。 +var providerProfiles = map[string]*ProviderProfile{ + PlatformKimi: { + Platform: PlatformKimi, + DefaultMode: AccountModePayG, + NativeResponses: true, + Modes: map[string]ProviderEndpoints{ + AccountModePayG: { + ChatBaseURL: DefaultKimiPayGBaseURL, + AnthropicBaseURL: DefaultKimiPayGAnthropicBaseURL, + }, + AccountModeCoding: { + ChatBaseURL: DefaultKimiCodingBaseURL, + AnthropicBaseURL: DefaultKimiCodingAnthropicBaseURL, + }, + }, + }, + PlatformZhipu: { + Platform: PlatformZhipu, + DefaultMode: AccountModePayG, + Modes: map[string]ProviderEndpoints{ + AccountModePayG: { + ChatBaseURL: DefaultZhipuPayGBaseURL, + AnthropicBaseURL: DefaultZhipuAnthropicBaseURL, + }, + AccountModeCoding: { + ChatBaseURL: DefaultZhipuCodingBaseURL, + AnthropicBaseURL: DefaultZhipuAnthropicBaseURL, + }, + }, + }, + PlatformDeepseek: { + Platform: PlatformDeepseek, + DefaultMode: AccountModePayG, + NativeResponses: true, + Modes: map[string]ProviderEndpoints{ + AccountModePayG: { + ChatBaseURL: DefaultDeepseekBaseURL, + AnthropicBaseURL: DefaultDeepseekAnthropicBaseURL, + }, + }, + }, + PlatformMiniMax: { + Platform: PlatformMiniMax, + DefaultMode: AccountModePayG, + NativeResponses: true, + Modes: map[string]ProviderEndpoints{ + // 按量付费与 Coding/Token Plan 共用推理域名,靠 API Key 区分套餐。 + AccountModePayG: { + ChatBaseURL: DefaultMiniMaxBaseURL, + AnthropicBaseURL: DefaultMiniMaxAnthropicBaseURL, + }, + AccountModeCoding: { + ChatBaseURL: DefaultMiniMaxBaseURL, + AnthropicBaseURL: DefaultMiniMaxAnthropicBaseURL, + }, + }, + }, + PlatformOpenCodeGo: { + Platform: PlatformOpenCodeGo, + DefaultMode: AccountModeGo, + NativeResponses: true, + Modes: map[string]ProviderEndpoints{ + AccountModeGo: { + ChatBaseURL: DefaultOpenCodeGoBaseURL, + AnthropicBaseURL: DefaultOpenCodeGoAnthropicBaseURL, + ProtocolRules: DefaultOpenCodeGoProtocolRules(), + }, + AccountModeZen: { + ChatBaseURL: DefaultOpenCodeZenBaseURL, + AnthropicBaseURL: DefaultOpenCodeZenAnthropicBaseURL, + ProtocolRules: DefaultOpenCodeZenProtocolRules(), + }, + }, + }, +} + +// LookupProviderProfile 返回 platform 对应的多协议供应商 profile;非此类平台返回 nil。 +func LookupProviderProfile(platform string) *ProviderProfile { + return providerProfiles[platform] +} + +func (a *Account) providerProfile() *ProviderProfile { + if a == nil { + return nil + } + return LookupProviderProfile(a.Platform) +} + +// defaultProviderBaseURL 按账号 account_mode 返回多协议供应商指定协议的官方默认基址; +// 非多协议供应商或协议未知时为空串。 +func (a *Account) defaultProviderBaseURL(protocol string) string { + profile := a.providerProfile() + if profile == nil { + return "" + } + return profile.DefaultBaseURL(a.GetCredential("account_mode"), protocol) +} diff --git a/backend/internal/service/provider_profile_test.go b/backend/internal/service/provider_profile_test.go new file mode 100644 index 0000000000..514ede372e --- /dev/null +++ b/backend/internal/service/provider_profile_test.go @@ -0,0 +1,144 @@ +//go:build unit + +package service + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +// legacyProviderDefaultBaseURL 复述 provider profile 引入前 account.go 中逐平台 +// switch 的默认端点逻辑,作为等价性基准。 +func legacyProviderDefaultBaseURL(platform, mode, protocol string) string { + coding := mode == AccountModeCoding + zen := mode == AccountModeZen + switch protocol { + case APIProtocolAnthropic: + switch platform { + case PlatformKimi: + if coding { + return DefaultKimiCodingAnthropicBaseURL + } + return DefaultKimiPayGAnthropicBaseURL + case PlatformZhipu: + return DefaultZhipuAnthropicBaseURL + case PlatformDeepseek: + return DefaultDeepseekAnthropicBaseURL + case PlatformMiniMax: + return DefaultMiniMaxAnthropicBaseURL + case PlatformOpenCodeGo: + if zen { + return DefaultOpenCodeZenAnthropicBaseURL + } + return DefaultOpenCodeGoAnthropicBaseURL + } + case APIProtocolChatCompletions, APIProtocolResponses: + switch platform { + case PlatformKimi: + if coding { + return DefaultKimiCodingBaseURL + } + return DefaultKimiPayGBaseURL + case PlatformZhipu: + if coding { + return DefaultZhipuCodingBaseURL + } + return DefaultZhipuPayGBaseURL + case PlatformDeepseek: + return DefaultDeepseekBaseURL + case PlatformMiniMax: + return DefaultMiniMaxBaseURL + case PlatformOpenCodeGo: + if zen { + return DefaultOpenCodeZenBaseURL + } + return DefaultOpenCodeGoBaseURL + } + } + return "" +} + +func TestProviderProfile_DefaultBaseURLsMatchLegacySwitches(t *testing.T) { + t.Parallel() + + platforms := []string{PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo} + modes := []string{"", AccountModePayG, AccountModeCoding, AccountModeZen, AccountModeGo, " coding ", "unknown"} + + for _, platform := range platforms { + for _, mode := range modes { + legacyMode := mode + if legacyMode == " coding " { + legacyMode = AccountModeCoding + } + newAccount := func(protocol string) *Account { + return &Account{ + Platform: platform, + Type: AccountTypeAPIKey, + Credentials: map[string]any{ + "api_key": "sk-test", + "account_mode": mode, + "api_protocol": protocol, + }, + } + } + name := platform + "/" + mode + + chat := newAccount(APIProtocolChatCompletions) + require.Equal(t, legacyProviderDefaultBaseURL(platform, legacyMode, APIProtocolChatCompletions), chat.GetOpenAIBaseURL(), name) + + anthropic := newAccount(APIProtocolAnthropic) + require.Equal(t, legacyProviderDefaultBaseURL(platform, legacyMode, APIProtocolAnthropic), anthropic.GetAnthropicProtocolBaseURL(), name) + require.Equal(t, legacyProviderDefaultBaseURL(platform, legacyMode, APIProtocolChatCompletions), anthropic.GetOpenAIFormatBaseURL(), name) + + adaptive := newAccount(APIProtocolAdaptive) + for _, protocol := range []string{APIProtocolChatCompletions, APIProtocolResponses, APIProtocolAnthropic, "unknown"} { + require.Equal(t, legacyProviderDefaultBaseURL(platform, legacyMode, protocol), adaptive.GetCNProtocolBaseURL(protocol), name+"/"+protocol) + } + } + } +} + +func TestProviderProfile_ProfilesMatchMultiProtocolPlatforms(t *testing.T) { + t.Parallel() + + for _, platform := range []string{ + PlatformAnthropic, PlatformOpenAI, PlatformGemini, PlatformAntigravity, PlatformGrok, + PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformComposite, "", + } { + want := IsCNProvider(platform) || platform == PlatformOpenCodeGo + require.Equal(t, want, IsMultiProtocolAPIKeyProvider(platform), platform) + require.Equal(t, want, LookupProviderProfile(platform) != nil, platform) + } + + for platform, profile := range providerProfiles { + require.Equal(t, platform, profile.Platform) + _, ok := profile.Modes[profile.DefaultMode] + require.True(t, ok, "%s default mode %q must be registered", platform, profile.DefaultMode) + } +} + +func TestProviderProfile_NativeResponsesMatchesLegacy(t *testing.T) { + t.Parallel() + + legacy := map[string]bool{ + PlatformDeepseek: true, + PlatformKimi: true, + PlatformMiniMax: true, + PlatformOpenCodeGo: true, + } + for _, platform := range []string{PlatformOpenAI, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo} { + account := &Account{Platform: platform, Type: AccountTypeAPIKey} + require.Equal(t, legacy[platform], account.SupportsNativeCNResponses(), platform) + } + require.False(t, (*Account)(nil).SupportsNativeCNResponses()) +} + +func TestProviderProfile_OpenCodeProtocolRulesByMode(t *testing.T) { + t.Parallel() + + require.Equal(t, DefaultOpenCodeGoProtocolRules(), defaultOpenCodeProtocolRules(AccountModeGo)) + require.Equal(t, DefaultOpenCodeGoProtocolRules(), defaultOpenCodeProtocolRules("")) + require.Equal(t, DefaultOpenCodeZenProtocolRules(), defaultOpenCodeProtocolRules(AccountModeZen)) + require.Empty(t, LookupProviderProfile(PlatformKimi).Endpoints(AccountModeCoding).ProtocolRules) +} From 3f8eea08079a244c9def66d0998fd4f79e9e1d25 Mon Sep 17 00:00:00 2001 From: SavitarC <71271200+SavitarC@users.noreply.github.com> Date: Sun, 27 Sep 2026 11:08:41 +0800 Subject: [PATCH 02/19] =?UTF-8?q?refactor(provider):=20profile=20=E7=AB=AF?= =?UTF-8?q?=E7=82=B9=E6=94=B9=E4=B8=BA=E6=8C=89=E5=8D=8F=E8=AE=AE=E7=99=BB?= =?UTF-8?q?=E8=AE=B0=EF=BC=8CResponses=20=E8=B7=AF=E5=BE=84=E7=BA=A6?= =?UTF-8?q?=E5=AE=9A=E5=B9=B6=E5=85=A5=20profile?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ProviderEndpoints 由 ChatBaseURL + AnthropicBaseURL 改为以协议为键的 BaseURLs(chat_completions / responses / anthropic),与账号凭证 api_base_urls、前端 defaultCNAdaptiveBaseUrls 的结构一致: - 某协议没有条目即表示不提供该原生端点,SupportsNativeCNResponses 改为 由 responses 条目推导,去掉单独的 NativeResponses 布尔值; - DeepSeek 的 Responses 路径例外(/responses,无 /v1)从 buildOpenAIResponsesURLForPlatform 的平台硬编码移入 profile.ResponsesPath。 运行时行为不变。唯一的函数级差异:智谱 adaptive 账号的 GetCNProtocolBaseURL(responses) 默认值由 CC 基址变为空串;所有运行时调用方 均先经 UsesNativeCNResponses / SupportsNativeCNResponses 守卫,智谱不会走到, TestAdaptiveProtocolBaseURLs 的对应期望随之更新。 Co-Authored-By: Claude Opus 5.5 --- backend/internal/service/account.go | 3 +- backend/internal/service/cn_providers_test.go | 5 +- .../service/openai_gateway_request_body.go | 8 +- backend/internal/service/provider_profile.go | 129 +++++++++++------- .../internal/service/provider_profile_test.go | 47 ++++++- 5 files changed, 132 insertions(+), 60 deletions(-) diff --git a/backend/internal/service/account.go b/backend/internal/service/account.go index fd60f098ef..783fffc349 100644 --- a/backend/internal/service/account.go +++ b/backend/internal/service/account.go @@ -1454,8 +1454,7 @@ func (a *Account) GetAPIProtocol() string { // DeepSeek 官方为 /responses(无 /v1);Kimi 按量付费与 Coding Plan 均为 // /v1/responses(moonshot.cn / kimi.com/coding);MiniMax 为 /v1/responses。 func (a *Account) SupportsNativeCNResponses() bool { - profile := a.providerProfile() - return profile != nil && profile.NativeResponses + return a.providerSupportsProtocol(APIProtocolResponses) } // UsesNativeCNResponses 报告当前账号是否应按原生 Responses 协议转发 diff --git a/backend/internal/service/cn_providers_test.go b/backend/internal/service/cn_providers_test.go index 44becd4e5b..b78dfbebeb 100644 --- a/backend/internal/service/cn_providers_test.go +++ b/backend/internal/service/cn_providers_test.go @@ -668,8 +668,9 @@ func TestAdaptiveProtocolBaseURLs(t *testing.T) { }{ {"kimi payg", PlatformKimi, AccountModePayG, DefaultKimiPayGBaseURL, DefaultKimiPayGAnthropicBaseURL, DefaultKimiPayGBaseURL}, {"kimi coding", PlatformKimi, AccountModeCoding, DefaultKimiCodingBaseURL, DefaultKimiCodingAnthropicBaseURL, DefaultKimiCodingBaseURL}, - {"zhipu payg", PlatformZhipu, AccountModePayG, DefaultZhipuPayGBaseURL, DefaultZhipuAnthropicBaseURL, DefaultZhipuPayGBaseURL}, - {"zhipu coding", PlatformZhipu, AccountModeCoding, DefaultZhipuCodingBaseURL, DefaultZhipuAnthropicBaseURL, DefaultZhipuCodingBaseURL}, + // 智谱没有原生 Responses 端点:profile 不登记 responses 条目,默认基址为空。 + {"zhipu payg", PlatformZhipu, AccountModePayG, DefaultZhipuPayGBaseURL, DefaultZhipuAnthropicBaseURL, ""}, + {"zhipu coding", PlatformZhipu, AccountModeCoding, DefaultZhipuCodingBaseURL, DefaultZhipuAnthropicBaseURL, ""}, {"deepseek", PlatformDeepseek, AccountModePayG, DefaultDeepseekBaseURL, DefaultDeepseekAnthropicBaseURL, DefaultDeepseekBaseURL}, {"minimax payg", PlatformMiniMax, AccountModePayG, DefaultMiniMaxBaseURL, DefaultMiniMaxAnthropicBaseURL, DefaultMiniMaxBaseURL}, {"minimax coding", PlatformMiniMax, AccountModeCoding, DefaultMiniMaxBaseURL, DefaultMiniMaxAnthropicBaseURL, DefaultMiniMaxBaseURL}, diff --git a/backend/internal/service/openai_gateway_request_body.go b/backend/internal/service/openai_gateway_request_body.go index b0e2dbf408..663944e479 100644 --- a/backend/internal/service/openai_gateway_request_body.go +++ b/backend/internal/service/openai_gateway_request_body.go @@ -53,11 +53,11 @@ func buildOpenAIResponsesURL(base string) string { } // buildOpenAIResponsesURLForPlatform 组装 Responses 端点(平台感知)。 -// DeepSeek 官方 Responses 端点为 /responses(无 /v1 前缀,适配 Codex); -// 其余平台维持 /v1/responses。 +// 供应商 profile 声明了 ResponsesPath 时按其拼接(如 DeepSeek 为无 /v1 前缀的 +// /responses);其余平台维持 /v1/responses。 func buildOpenAIResponsesURLForPlatform(platform string, base string) string { - if platform == PlatformDeepseek { - return buildOpenAIEndpointURL(base, "/responses") + if profile := LookupProviderProfile(platform); profile != nil && profile.ResponsesPath != "" { + return buildOpenAIEndpointURL(base, profile.ResponsesPath) } return buildOpenAIResponsesURL(base) } diff --git a/backend/internal/service/provider_profile.go b/backend/internal/service/provider_profile.go index bc7e0b7c35..7fee5d96df 100644 --- a/backend/internal/service/provider_profile.go +++ b/backend/internal/service/provider_profile.go @@ -5,25 +5,26 @@ import "strings" // ProviderEndpoints 是多协议 API Key 供应商在某个接入模式下的官方默认端点与 // 内置分流规则。账号凭证里的 base_url / api_base_urls / protocol_rules 仍优先于这里。 type ProviderEndpoints struct { - // ChatBaseURL 供 Chat Completions / Responses / models 共用。 - ChatBaseURL string - // AnthropicBaseURL 是 Anthropic 协议基址,上游路径为 {base}/v1/messages。 - AnthropicBaseURL string + // BaseURLs 以上游协议(chat_completions / responses / anthropic)为键, + // 值为该协议的官方默认基址。缺少某协议的条目即表示该模式不提供该原生端点。 + // Anthropic 基址的上游路径为 {base}/v1/messages。 + BaseURLs map[string]string // ProtocolRules 是按模型分流的内置默认表(首条命中生效);为空表示该模式 // 不按模型分流,由账号 api_protocol 决定上游协议。 ProtocolRules []OpenCodeGoProtocolRule } // ProviderProfile 描述一个多协议 API Key 供应商(国产厂商或多模型聚合平台)的 -// 静态数据:各接入模式的默认端点、能力开关与内置分流规则。 +// 静态数据:各接入模式的默认端点、内置分流规则与端点路径约定。 // 额度解析、会话头等行为差异不在这里,仍由各自的代码路径处理。 type ProviderProfile struct { Platform string // DefaultMode 在 credentials.account_mode 缺失或不在 Modes 中时使用。 DefaultMode string Modes map[string]ProviderEndpoints - // NativeResponses 表示上游提供原生 Responses 端点。 - NativeResponses bool + // ResponsesPath 覆盖 Responses 端点路径(按 buildOpenAIEndpointURL 的版本感知 + // 规则拼接),空值为 /v1/responses。对自定义 base_url 的账号同样生效。 + ResponsesPath string } // Endpoints 返回指定接入模式的端点;未知模式回落 DefaultMode。 @@ -37,93 +38,115 @@ func (p *ProviderProfile) Endpoints(mode string) ProviderEndpoints { return p.Modes[p.DefaultMode] } -// DefaultBaseURL 返回指定接入模式与上游协议的官方默认基址;协议未知时为空串。 +// DefaultBaseURL 返回指定接入模式与上游协议的官方默认基址;该模式不提供此协议时为空串。 func (p *ProviderProfile) DefaultBaseURL(mode, protocol string) string { - endpoints := p.Endpoints(mode) - switch protocol { - case APIProtocolAnthropic: - return endpoints.AnthropicBaseURL - case APIProtocolChatCompletions, APIProtocolResponses: - return endpoints.ChatBaseURL - default: - return "" - } + return p.Endpoints(mode).BaseURLs[protocol] +} + +// SupportsProtocol 报告指定接入模式是否提供该协议的原生端点。 +func (p *ProviderProfile) SupportsProtocol(mode, protocol string) bool { + return p.DefaultBaseURL(mode, protocol) != "" } // providerProfiles 是多协议 API Key 供应商的单一数据来源。新增同类供应商时在此 -// 登记一条即可获得默认端点、Responses 能力判定与 IsMultiProtocolAPIKeyProvider 归属。 +// 登记一条即可获得默认端点、原生 Responses 能力判定(有 responses 条目即支持)、 +// Responses 路径约定与 IsMultiProtocolAPIKeyProvider 归属。 // 默认端点需与前端 credentialsBuilder.ts 的预设保持一致。 var providerProfiles = map[string]*ProviderProfile{ PlatformKimi: { - Platform: PlatformKimi, - DefaultMode: AccountModePayG, - NativeResponses: true, + Platform: PlatformKimi, + DefaultMode: AccountModePayG, Modes: map[string]ProviderEndpoints{ AccountModePayG: { - ChatBaseURL: DefaultKimiPayGBaseURL, - AnthropicBaseURL: DefaultKimiPayGAnthropicBaseURL, + BaseURLs: map[string]string{ + APIProtocolChatCompletions: DefaultKimiPayGBaseURL, + APIProtocolResponses: DefaultKimiPayGBaseURL, + APIProtocolAnthropic: DefaultKimiPayGAnthropicBaseURL, + }, }, AccountModeCoding: { - ChatBaseURL: DefaultKimiCodingBaseURL, - AnthropicBaseURL: DefaultKimiCodingAnthropicBaseURL, + BaseURLs: map[string]string{ + APIProtocolChatCompletions: DefaultKimiCodingBaseURL, + APIProtocolResponses: DefaultKimiCodingBaseURL, + APIProtocolAnthropic: DefaultKimiCodingAnthropicBaseURL, + }, }, }, }, PlatformZhipu: { Platform: PlatformZhipu, DefaultMode: AccountModePayG, + // 智谱没有原生 Responses 端点,故不登记 responses 条目。 Modes: map[string]ProviderEndpoints{ AccountModePayG: { - ChatBaseURL: DefaultZhipuPayGBaseURL, - AnthropicBaseURL: DefaultZhipuAnthropicBaseURL, + BaseURLs: map[string]string{ + APIProtocolChatCompletions: DefaultZhipuPayGBaseURL, + APIProtocolAnthropic: DefaultZhipuAnthropicBaseURL, + }, }, AccountModeCoding: { - ChatBaseURL: DefaultZhipuCodingBaseURL, - AnthropicBaseURL: DefaultZhipuAnthropicBaseURL, + BaseURLs: map[string]string{ + APIProtocolChatCompletions: DefaultZhipuCodingBaseURL, + APIProtocolAnthropic: DefaultZhipuAnthropicBaseURL, + }, }, }, }, PlatformDeepseek: { - Platform: PlatformDeepseek, - DefaultMode: AccountModePayG, - NativeResponses: true, + Platform: PlatformDeepseek, + DefaultMode: AccountModePayG, + // DeepSeek 官方 Responses 端点为 /responses(无 /v1 前缀,适配 Codex)。 + ResponsesPath: "/responses", Modes: map[string]ProviderEndpoints{ AccountModePayG: { - ChatBaseURL: DefaultDeepseekBaseURL, - AnthropicBaseURL: DefaultDeepseekAnthropicBaseURL, + BaseURLs: map[string]string{ + APIProtocolChatCompletions: DefaultDeepseekBaseURL, + APIProtocolResponses: DefaultDeepseekBaseURL, + APIProtocolAnthropic: DefaultDeepseekAnthropicBaseURL, + }, }, }, }, PlatformMiniMax: { - Platform: PlatformMiniMax, - DefaultMode: AccountModePayG, - NativeResponses: true, + Platform: PlatformMiniMax, + DefaultMode: AccountModePayG, Modes: map[string]ProviderEndpoints{ // 按量付费与 Coding/Token Plan 共用推理域名,靠 API Key 区分套餐。 AccountModePayG: { - ChatBaseURL: DefaultMiniMaxBaseURL, - AnthropicBaseURL: DefaultMiniMaxAnthropicBaseURL, + BaseURLs: map[string]string{ + APIProtocolChatCompletions: DefaultMiniMaxBaseURL, + APIProtocolResponses: DefaultMiniMaxBaseURL, + APIProtocolAnthropic: DefaultMiniMaxAnthropicBaseURL, + }, }, AccountModeCoding: { - ChatBaseURL: DefaultMiniMaxBaseURL, - AnthropicBaseURL: DefaultMiniMaxAnthropicBaseURL, + BaseURLs: map[string]string{ + APIProtocolChatCompletions: DefaultMiniMaxBaseURL, + APIProtocolResponses: DefaultMiniMaxBaseURL, + APIProtocolAnthropic: DefaultMiniMaxAnthropicBaseURL, + }, }, }, }, PlatformOpenCodeGo: { - Platform: PlatformOpenCodeGo, - DefaultMode: AccountModeGo, - NativeResponses: true, + Platform: PlatformOpenCodeGo, + DefaultMode: AccountModeGo, Modes: map[string]ProviderEndpoints{ AccountModeGo: { - ChatBaseURL: DefaultOpenCodeGoBaseURL, - AnthropicBaseURL: DefaultOpenCodeGoAnthropicBaseURL, - ProtocolRules: DefaultOpenCodeGoProtocolRules(), + BaseURLs: map[string]string{ + APIProtocolChatCompletions: DefaultOpenCodeGoBaseURL, + APIProtocolResponses: DefaultOpenCodeGoBaseURL, + APIProtocolAnthropic: DefaultOpenCodeGoAnthropicBaseURL, + }, + ProtocolRules: DefaultOpenCodeGoProtocolRules(), }, AccountModeZen: { - ChatBaseURL: DefaultOpenCodeZenBaseURL, - AnthropicBaseURL: DefaultOpenCodeZenAnthropicBaseURL, - ProtocolRules: DefaultOpenCodeZenProtocolRules(), + BaseURLs: map[string]string{ + APIProtocolChatCompletions: DefaultOpenCodeZenBaseURL, + APIProtocolResponses: DefaultOpenCodeZenBaseURL, + APIProtocolAnthropic: DefaultOpenCodeZenAnthropicBaseURL, + }, + ProtocolRules: DefaultOpenCodeZenProtocolRules(), }, }, }, @@ -150,3 +173,9 @@ func (a *Account) defaultProviderBaseURL(protocol string) string { } return profile.DefaultBaseURL(a.GetCredential("account_mode"), protocol) } + +// providerSupportsProtocol 报告账号所在供应商在其 account_mode 下是否提供该协议的原生端点。 +func (a *Account) providerSupportsProtocol(protocol string) bool { + profile := a.providerProfile() + return profile != nil && profile.SupportsProtocol(a.GetCredential("account_mode"), protocol) +} diff --git a/backend/internal/service/provider_profile_test.go b/backend/internal/service/provider_profile_test.go index 514ede372e..1dc9f94175 100644 --- a/backend/internal/service/provider_profile_test.go +++ b/backend/internal/service/provider_profile_test.go @@ -34,6 +34,12 @@ func legacyProviderDefaultBaseURL(platform, mode, protocol string) string { return DefaultOpenCodeGoAnthropicBaseURL } case APIProtocolChatCompletions, APIProtocolResponses: + if platform == PlatformZhipu && protocol == APIProtocolResponses { + // 唯一的函数级差异:旧 switch 对智谱 Responses 也返回 CC 基址,profile + // 以"缺条目即不支持"建模后返回空串。所有运行时调用方都先经 + // UsesNativeCNResponses / SupportsNativeCNResponses 守卫,智谱不会走到这里。 + return "" + } switch platform { case PlatformKimi: if coding { @@ -127,13 +133,50 @@ func TestProviderProfile_NativeResponsesMatchesLegacy(t *testing.T) { PlatformMiniMax: true, PlatformOpenCodeGo: true, } + modes := []string{"", AccountModePayG, AccountModeCoding, AccountModeZen, AccountModeGo, "unknown"} for _, platform := range []string{PlatformOpenAI, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo} { - account := &Account{Platform: platform, Type: AccountTypeAPIKey} - require.Equal(t, legacy[platform], account.SupportsNativeCNResponses(), platform) + for _, mode := range modes { + account := &Account{Platform: platform, Type: AccountTypeAPIKey, Credentials: map[string]any{"account_mode": mode}} + require.Equal(t, legacy[platform], account.SupportsNativeCNResponses(), platform+"/"+mode) + } } require.False(t, (*Account)(nil).SupportsNativeCNResponses()) } +func TestProviderProfile_BaseURLKeysAreNativeProtocols(t *testing.T) { + t.Parallel() + + for platform, profile := range providerProfiles { + for mode, endpoints := range profile.Modes { + require.NotEmpty(t, endpoints.BaseURLs[APIProtocolChatCompletions], "%s/%s must have a chat_completions base", platform, mode) + for protocol, baseURL := range endpoints.BaseURLs { + require.True(t, isNativeOpenCodeGoProtocol(protocol), "%s/%s has unknown protocol key %q", platform, mode, protocol) + require.NotEmpty(t, baseURL, "%s/%s/%s", platform, mode, protocol) + } + } + } +} + +func TestProviderProfile_ResponsesPathMatchesLegacy(t *testing.T) { + t.Parallel() + + legacy := func(platform, base string) string { + if platform == PlatformDeepseek { + return buildOpenAIEndpointURL(base, "/responses") + } + return buildOpenAIResponsesURL(base) + } + bases := []string{ + "https://api.deepseek.com", "https://relay.example.com", "https://relay.example.com/v1", + "https://opencode.ai/zen/go/v1", "https://open.bigmodel.cn/api/paas/v4", "https://api.moonshot.cn/v1", + } + for _, platform := range []string{PlatformOpenAI, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo} { + for _, base := range bases { + require.Equal(t, legacy(platform, base), buildOpenAIResponsesURLForPlatform(platform, base), platform+" "+base) + } + } +} + func TestProviderProfile_OpenCodeProtocolRulesByMode(t *testing.T) { t.Parallel() From 8ac2936a3d8cc9c61b02e3f92f10de343afbed78 Mon Sep 17 00:00:00 2001 From: SavitarC <71271200+SavitarC@users.noreply.github.com> Date: Sun, 27 Sep 2026 11:08:41 +0800 Subject: [PATCH 03/19] =?UTF-8?q?refactor(gateway):=20=E4=B8=89=E4=B8=AA?= =?UTF-8?q?=E5=85=A5=E7=AB=99=E5=85=A5=E5=8F=A3=E7=9A=84=E4=B8=8A=E6=B8=B8?= =?UTF-8?q?=E5=8D=8F=E8=AE=AE=E5=88=86=E6=B5=81=E6=94=B6=E6=95=9B=E4=B8=BA?= =?UTF-8?q?=20resolveUpstreamProtocol?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 此前 /v1/responses、/v1/chat/completions、/v1/messages 各自用一串 if 决定 上游协议:OpenCode 按模型规则、国产 adaptive 按入站、显式 api_protocol、 Responses 探针四个来源的优先级靠语句先后隐式决定,且每个入口都有 IsOpenCodeGo 特判。 - provider profile 新增 Routing(by_inbound / by_model),OpenCode 登记为 by_model;routesByModel 取代转发路径与 GetAPIProtocol 默认值中的 IsOpenCodeGo 判断。 - 新增 upstream_protocol_routing.go:resolveUpstreamProtocol 以单一函数给出 上游协议(按模型分流 → adaptive 按入站 → 显式 anthropic → CC 直转条件 → Responses),resolveModelRoutedProtocol 以 profile 规则泛化 OpenCode 的规则解析;三个入口改为 switch 该结果选择既有转换路径,Responses 形状 请求体的转换合并为 convertResponsesShapedChatBody。 转换函数本身不变。新增分流矩阵测试经真实入口遍历 平台 × api_protocol × 探针 × 账号类型 × 接入模式 × protocol_rules × 入站 × 模型(2045 组), 与改动前逐条 diff 仅 6 条不同:智谱 adaptive 的非 API Key 账号(UI 无法 创建)在 /v1/responses 入站时由 Responses 改为回落 CC,与 /v1/chat/completions 入口一致;这 6 组前后都在发出上游请求前报错。 协议规则与映射模型相关的类型、函数已被所有按模型分流的供应商共用,同时去掉 OpenCode 前缀(OpenCodeGoProtocolRule → ProtocolRule、matchOpenCodeGoProtocolRules → matchProtocolRules、NormalizeOpenCodeGoProtocolRulesCredentials → NormalizeProtocolRulesCredentials、resolveOpenCodeGoMappedModel → resolveMappedUpstreamModel 等),并删除收敛后已无调用方的 defaultOpenCodeProtocolRules。 Co-Authored-By: Claude Opus 5.5 --- backend/internal/service/account.go | 3 +- backend/internal/service/admin_account.go | 8 +- .../openai_gateway_chat_completions.go | 99 ++--- .../service/openai_gateway_forward.go | 41 +-- .../service/openai_gateway_messages.go | 39 +- ...penai_gateway_messages_anthropic_native.go | 2 +- backend/internal/service/opencode_go.go | 84 ++--- backend/internal/service/opencode_go_test.go | 30 +- backend/internal/service/provider_profile.go | 29 +- .../internal/service/provider_profile_test.go | 9 +- .../service/upstream_protocol_routing.go | 92 +++++ .../upstream_protocol_routing_matrix_test.go | 344 ++++++++++++++++++ .../service/upstream_protocol_routing_test.go | 119 ++++++ 13 files changed, 704 insertions(+), 195 deletions(-) create mode 100644 backend/internal/service/upstream_protocol_routing.go create mode 100644 backend/internal/service/upstream_protocol_routing_matrix_test.go create mode 100644 backend/internal/service/upstream_protocol_routing_test.go diff --git a/backend/internal/service/account.go b/backend/internal/service/account.go index 783fffc349..97a797580c 100644 --- a/backend/internal/service/account.go +++ b/backend/internal/service/account.go @@ -1444,7 +1444,8 @@ func (a *Account) GetAPIProtocol() string { case APIProtocolChatCompletions: return APIProtocolChatCompletions } - if a.IsOpenCodeGo() { + // 按模型分流的供应商(多模型聚合平台)未显式配置时默认 adaptive。 + if a.routesByModel() { return APIProtocolAdaptive } return APIProtocolChatCompletions diff --git a/backend/internal/service/admin_account.go b/backend/internal/service/admin_account.go index ef4a47fa1f..256e488d09 100644 --- a/backend/internal/service/admin_account.go +++ b/backend/internal/service/admin_account.go @@ -323,7 +323,7 @@ func (s *adminServiceImpl) DuplicateAccount(ctx context.Context, id int64, actor if err := NormalizeHeaderOverrideCredentials(input.Credentials); err != nil { return nil, err } - if err := NormalizeOpenCodeGoProtocolRulesCredentials(input.Credentials); err != nil { + if err := NormalizeProtocolRulesCredentials(input.Credentials); err != nil { return nil, err } duplicate, err := buildAccountForCreate(input, accountExtra) @@ -522,7 +522,7 @@ func (s *adminServiceImpl) CreateAccount(ctx context.Context, input *CreateAccou if err := NormalizeHeaderOverrideCredentials(input.Credentials); err != nil { return nil, err } - if err := NormalizeOpenCodeGoProtocolRulesCredentials(input.Credentials); err != nil { + if err := NormalizeProtocolRulesCredentials(input.Credentials); err != nil { return nil, err } // Never persist ephemeral SSO/password secrets after OAuth conversion. @@ -655,7 +655,7 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U if err := NormalizeHeaderOverrideCredentials(account.Credentials); err != nil { return nil, err } - if err := NormalizeOpenCodeGoProtocolRulesCredentials(account.Credentials); err != nil { + if err := NormalizeProtocolRulesCredentials(account.Credentials); err != nil { return nil, err } // Strip SSO/password residue that must never sit next to OAuth tokens. @@ -1102,7 +1102,7 @@ func (s *adminServiceImpl) BulkUpdateAccounts(ctx context.Context, input *BulkUp if err := NormalizeHeaderOverrideCredentials(input.Credentials); err != nil { return nil, err } - if err := NormalizeOpenCodeGoProtocolRulesCredentials(input.Credentials); err != nil { + if err := NormalizeProtocolRulesCredentials(input.Credentials); err != nil { return nil, err } // Bulk may mix platforms; always drop ephemeral SSO/password keys (cookie diff --git a/backend/internal/service/openai_gateway_chat_completions.go b/backend/internal/service/openai_gateway_chat_completions.go index 7ffd20916f..66c2471ae7 100644 --- a/backend/internal/service/openai_gateway_chat_completions.go +++ b/backend/internal/service/openai_gateway_chat_completions.go @@ -110,88 +110,43 @@ func (s *OpenAIGatewayService) forwardAsChatCompletions( } // Cursor compatibility: some clients send a Responses-shaped body to the - // /v1/chat/completions URL. Detect it before adaptive routing so adaptive + // /v1/chat/completions URL. Detect it before protocol routing so adaptive // accounts never forward the body unchanged to a Chat Completions endpoint. isResponsesShape := !gjson.GetBytes(body, "messages").Exists() && gjson.GetBytes(body, "input").Exists() - - // OpenCode Go:按模型原生协议分流(与 inbound 协议正交)。 - // 规则未命中一律兜底 Chat Completions,只有显式 Responses 才走下方转换链。 - if account.IsOpenCodeGo() { - mapped := resolveOpenCodeGoMappedModel(account, body, defaultMappedModel) - if IsOpenCodeUnsupportedModel(mapped) { - return nil, writeOpenCodeUnsupportedModelError(c, false, mapped) - } - proto := openCodeGoNativeProtocol(account, mapped) - if proto != APIProtocolResponses { - if isResponsesShape { - if proto == APIProtocolAnthropic { - return s.forwardResponsesViaNativeAnthropic(ctx, c, account, body, "") - } - var responsesReq apicompat.ResponsesRequest - if err := json.Unmarshal(body, &responsesReq); err != nil { - return nil, fmt.Errorf("parse responses-shaped chat completions request: %w", err) - } - chatReq, err := apicompat.ResponsesToChatCompletionsRequestWithOptions( - &responsesReq, - &apicompat.ResponsesToChatOptions{ReasoningContentByID: s.reasoningContentByID}, - ) - if err != nil { - return nil, fmt.Errorf("convert responses-shaped chat completions request: %w", err) - } - chatBody, err := json.Marshal(chatReq) - if err != nil { - return nil, fmt.Errorf("marshal converted chat completions request: %w", err) - } - return s.forwardAsRawChatCompletions(ctx, c, account, chatBody, defaultMappedModel) - } - if proto == APIProtocolAnthropic { - return s.forwardChatCompletionsViaNativeAnthropic(ctx, c, account, body, defaultMappedModel) - } - return s.forwardAsRawChatCompletions(ctx, c, account, body, defaultMappedModel) - } + inbound := APIProtocolChatCompletions + if isResponsesShape { + inbound = APIProtocolResponses } + // 按模型分流与 adaptive 账号按请求体形状处理 Responses 形状入站;其余账号 + // 维持原样把请求体交给所选路径。 + convertResponsesShape := isResponsesShape && (account.routesByModel() || account.IsAdaptiveAPIProtocol()) - // 自适应账号的标准 Chat Completions 入站使用供应商原生 CC 端点。 - // Responses 形状下,DeepSeek / Kimi 继续走下方原生 Responses 链;GLM - // 没有 Responses 端点,先转换成 Chat Completions 再直转。 - if account.IsAdaptiveAPIProtocol() && !account.IsOpenCodeGo() { - if !isResponsesShape { - return s.forwardAsRawChatCompletions(ctx, c, account, body, defaultMappedModel) + // 上游协议统一由 resolveUpstreamProtocol 判定。Anthropic 分流必须先于 + // ShouldUseResponsesAPI:Anthropic 协议账号经 probe 落标 + // openai_responses_supported=false,否则会命中 CC 直转。 + routingModel := upstreamRoutingModel(account, body, defaultMappedModel) + if account.IsOpenCodeGo() && IsOpenCodeUnsupportedModel(routingModel) { + return nil, writeOpenCodeUnsupportedModelError(c, false, routingModel) + } + switch resolveUpstreamProtocol(account, inbound, routingModel) { + case APIProtocolAnthropic: + if convertResponsesShape { + return s.forwardResponsesViaNativeAnthropic(ctx, c, account, body, "") } - if !account.SupportsNativeCNResponses() { - var responsesReq apicompat.ResponsesRequest - if err := json.Unmarshal(body, &responsesReq); err != nil { - return nil, fmt.Errorf("parse responses-shaped chat completions request: %w", err) - } - chatReq, err := apicompat.ResponsesToChatCompletionsRequestWithOptions( - &responsesReq, - &apicompat.ResponsesToChatOptions{ReasoningContentByID: s.reasoningContentByID}, - ) + // CC 入站经 CC→Responses→Anthropic 转换链直通供应商原生 Anthropic 端点。 + return s.forwardChatCompletionsViaNativeAnthropic(ctx, c, account, body, defaultMappedModel) + case APIProtocolChatCompletions: + if convertResponsesShape { + chatBody, err := s.convertResponsesShapedChatBody(body) if err != nil { - return nil, fmt.Errorf("convert responses-shaped chat completions request: %w", err) - } - chatBody, err := json.Marshal(chatReq) - if err != nil { - return nil, fmt.Errorf("marshal converted chat completions request: %w", err) + return nil, err } return s.forwardAsRawChatCompletions(ctx, c, account, chatBody, defaultMappedModel) } - // DeepSeek / Kimi 原生 Responses 请求继续走下方 Responses→Chat 回程转换。 - } - - // 入口分流(国产供应商 Anthropic 协议):上游为供应商原生 Anthropic 端点, - // CC 入站请求经 CC→Responses→Anthropic 转换链直通该端点。必须先于 - // ShouldUseResponsesAPI 分流:该类账号经 probe 落标 - // openai_responses_supported=false,会先命中下方的 CC 直转分支。 - if account.IsAnthropicProtocol() { - return s.forwardChatCompletionsViaNativeAnthropic(ctx, c, account, body, defaultMappedModel) - } - - // 固定 chat_completions 的 CN 账号,以及强制或已探测确认不支持 Responses - // 的其他 APIKey 账号,均走 CC 直转。 - if shouldForwardOpenAIResponsesViaRawChatCompletions(account) { return s.forwardAsRawChatCompletions(ctx, c, account, body, defaultMappedModel) } + // 上游为 Responses(含 adaptive 下 Responses 形状入站且供应商有原生 + // Responses 端点):走下方 Chat Completions ↔ Responses 转换链。 SetActualOpenAIUpstreamEndpoint(c, openAIResponsesUpstreamEndpoint) startTime := time.Now() @@ -424,7 +379,7 @@ func (s *OpenAIGatewayService) forwardAsChatCompletions( return s.forwardAsChatCompletions(markAgentIdentityTaskRecoveryTried(ctx), c, account, body, promptCacheKey, defaultMappedModel, compatPromptCacheTenantIsolated) } if account.Type == AccountTypeAPIKey && - !account.IsOpenCodeGo() && + !account.routesByModel() && openai_compat.ResolveResponsesSupport(account.Extra) == openai_compat.ResponsesSupportUnknown && !isResponsesEndpointSupportedByStatus(resp.StatusCode) { logger.L().Info("openai chat_completions: /responses unsupported, falling back to raw chat completions", diff --git a/backend/internal/service/openai_gateway_forward.go b/backend/internal/service/openai_gateway_forward.go index 78dd47afe6..03d239774b 100644 --- a/backend/internal/service/openai_gateway_forward.go +++ b/backend/internal/service/openai_gateway_forward.go @@ -159,27 +159,6 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco return s.forwardGrokResponses(ctx, c, account, body, originalModel, reqStream, startTime) } - if account.IsOpenCodeGo() { - mapped := resolveOpenCodeGoMappedModel(account, body, "") - if IsOpenCodeUnsupportedModel(mapped) { - return nil, writeOpenCodeUnsupportedModelError(c, false, mapped) - } - switch openCodeGoNativeProtocol(account, mapped) { - case APIProtocolAnthropic: - return s.forwardResponsesViaNativeAnthropic(ctx, c, account, body, "") - case APIProtocolResponses: - break - default: - return s.forwardResponsesViaRawChatCompletions(ctx, c, account, body) - } - } - - // CN 供应商 anthropic 协议账号:/v1/responses 入站是交叉协议组合 - // (Responses 客户端 × Anthropic 上游),转成 Anthropic 请求走原生端点。 - // 不能落到下面的 raw-CC 分支——其 URL 构造会把 anthropic base 当 CC base 用。 - if account.IsAnthropicProtocol() { - return s.forwardResponsesViaNativeAnthropic(ctx, c, account, body, reqModel) - } if account.IsOpenAIApiKey() { if normalized, changed, normalizeErr := normalizeOpenAIParallelToolCallsWithoutTools(body, responsesLite); normalizeErr != nil { return nil, normalizeErr @@ -198,7 +177,23 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco originalModel = reqModel } - if shouldForwardOpenAIResponsesViaRawChatCompletions(account) { + // 上游协议统一由 resolveUpstreamProtocol 判定。OpenAI API Key 账号只会落到 + // Responses / Chat Completions,上面的归一化对两条路径都生效。 + routingModel := upstreamRoutingModel(account, body, "") + if account.IsOpenCodeGo() && IsOpenCodeUnsupportedModel(routingModel) { + return nil, writeOpenCodeUnsupportedModelError(c, false, routingModel) + } + switch resolveUpstreamProtocol(account, APIProtocolResponses, routingModel) { + case APIProtocolAnthropic: + // Responses 客户端 × Anthropic 上游:转成 Anthropic 请求走原生端点。不能落到 + // raw-CC 分支——其 URL 构造会把 anthropic base 当 CC base 用。 + // 按模型分流的账号不以请求模型兜底模型映射。 + defaultMappedModel := reqModel + if account.routesByModel() { + defaultMappedModel = "" + } + return s.forwardResponsesViaNativeAnthropic(ctx, c, account, body, defaultMappedModel) + case APIProtocolChatCompletions: return s.forwardResponsesViaRawChatCompletions(ctx, c, account, body) } SetActualOpenAIUpstreamEndpoint(c, openAIResponsesUpstreamEndpoint) @@ -1355,7 +1350,7 @@ func shouldForwardOpenAIResponsesViaRawChatCompletions(account *Account) bool { if account == nil || account.Type != AccountTypeAPIKey { return false } - if account.IsOpenCodeGo() { + if account.routesByModel() { // Model protocol_rules are the authority. Probe Extra must not collapse // Grok/GPT/Muse into Chat Completions. return false diff --git a/backend/internal/service/openai_gateway_messages.go b/backend/internal/service/openai_gateway_messages.go index a45dd5e565..9594a79a73 100644 --- a/backend/internal/service/openai_gateway_messages.go +++ b/backend/internal/service/openai_gateway_messages.go @@ -53,32 +53,21 @@ func (s *OpenAIGatewayService) ForwardAsAnthropic( return nil, err } - // OpenCode Go:按模型原生协议分流。规则未命中兜底 Chat Completions。 - if account.IsOpenCodeGo() { - mapped := resolveOpenCodeGoMappedModel(account, body, defaultMappedModel) - if IsOpenCodeUnsupportedModel(mapped) { - return nil, writeOpenCodeUnsupportedModelError(c, true, mapped) - } - switch openCodeGoNativeProtocol(account, mapped) { - case APIProtocolAnthropic: - return s.forwardAnthropicViaNativeAnthropicEndpoint(ctx, c, account, body, defaultMappedModel) - case APIProtocolResponses: - break - default: - return s.forwardAnthropicViaRawChatCompletions(ctx, c, account, body, defaultMappedModel) - } - } else if account.IsAnthropicProtocol() || account.IsAdaptiveAPIProtocol() { - // 入口分流(国产供应商 Anthropic 协议):上游为供应商原生 Anthropic 端点时, - // /v1/messages 请求零转换直通(仅模型名映射 + 少量 body 清洗),完整保留 - // thinking / tool_use / cache 语义,适配 Claude Code 等原生客户端。 - // 必须先于 ShouldUseResponsesAPI 分流:Anthropic 协议账号经 probe 落标 - // openai_responses_supported=false,会先命中下方的 CC 直转分支。 - return s.forwardAnthropicViaNativeAnthropicEndpoint(ctx, c, account, body, defaultMappedModel) + // 上游协议统一由 resolveUpstreamProtocol 判定。Anthropic 分流必须先于 + // ShouldUseResponsesAPI:Anthropic 协议账号经 probe 落标 + // openai_responses_supported=false,否则会命中 CC 直转。 + routingModel := upstreamRoutingModel(account, body, defaultMappedModel) + if account.IsOpenCodeGo() && IsOpenCodeUnsupportedModel(routingModel) { + return nil, writeOpenCodeUnsupportedModelError(c, true, routingModel) } - - // 固定 chat_completions 的 CN 账号,以及不支持 Responses 的其他 APIKey - // 账号,均将 Messages 转为 CC;固定 responses 的 CN 账号不受探针旧值覆盖。 - if shouldForwardOpenAIResponsesViaRawChatCompletions(account) { + switch resolveUpstreamProtocol(account, APIProtocolAnthropic, routingModel) { + case APIProtocolAnthropic: + // 上游为供应商原生 Anthropic 端点:/v1/messages 零转换直通(仅模型名映射 + + // 少量 body 清洗),完整保留 thinking / tool_use / cache 语义。 + return s.forwardAnthropicViaNativeAnthropicEndpoint(ctx, c, account, body, defaultMappedModel) + case APIProtocolChatCompletions: + // 固定 chat_completions 的多协议账号、规则命中 CC 的按模型分流账号,以及 + // 不支持 Responses 的其他 APIKey 账号,均将 Messages 转为 CC。 return s.forwardAnthropicViaRawChatCompletions(ctx, c, account, body, defaultMappedModel) } SetActualOpenAIUpstreamEndpoint(c, openAIResponsesUpstreamEndpoint) diff --git a/backend/internal/service/openai_gateway_messages_anthropic_native.go b/backend/internal/service/openai_gateway_messages_anthropic_native.go index 0026046a58..eb061c9750 100644 --- a/backend/internal/service/openai_gateway_messages_anthropic_native.go +++ b/backend/internal/service/openai_gateway_messages_anthropic_native.go @@ -140,7 +140,7 @@ func (s *OpenAIGatewayService) nativeAnthropicTargetURL(account *Account) (strin return strings.TrimRight(validatedURL, "/") + "/v1/messages", nil } -func resolveOpenCodeGoMappedModel(account *Account, body []byte, defaultMappedModel string) string { +func resolveMappedUpstreamModel(account *Account, body []byte, defaultMappedModel string) string { original := strings.TrimSpace(gjson.GetBytes(body, "model").String()) billing := resolveOpenAIForwardModel(account, original, defaultMappedModel) return normalizeOpenAIModelForUpstream(account, billing) diff --git a/backend/internal/service/opencode_go.go b/backend/internal/service/opencode_go.go index 073a7bd116..d052451a56 100644 --- a/backend/internal/service/opencode_go.go +++ b/backend/internal/service/opencode_go.go @@ -19,9 +19,9 @@ const ( // the UI does not pick a model. glm-5.3 is a Chat Completions catalog ID. DefaultOpenCodeGoTestModel = "glm-5.3" - openCodeGoProtocolRulesKey = "protocol_rules" - maxOpenCodeGoProtocolRules = 64 - maxOpenCodeGoProtocolPatternLength = 128 + protocolRulesCredentialKey = "protocol_rules" + maxProtocolRules = 64 + maxProtocolRulePatternLength = 128 ) // DefaultOpenCodeGoModelIDs 是官方文档当前公开的模型 ID 目录, @@ -101,16 +101,16 @@ func writeOpenCodeUnsupportedModelError(c *gin.Context, isAnthropic bool, model return fmt.Errorf("opencode unsupported model: %s", model) } -// OpenCodeGoProtocolRule is one model-pattern → native protocol mapping. +// ProtocolRule is one model-pattern → native protocol mapping. // Pattern is an exact ID or a suffix glob (foo* / *). First match wins. -type OpenCodeGoProtocolRule struct { +type ProtocolRule struct { Pattern string `json:"pattern"` Protocol string `json:"protocol"` } // DefaultOpenCodeGoProtocolRules is the built-in adaptive routing table for Go. -func DefaultOpenCodeGoProtocolRules() []OpenCodeGoProtocolRule { - return []OpenCodeGoProtocolRule{ +func DefaultOpenCodeGoProtocolRules() []ProtocolRule { + return []ProtocolRule{ {Pattern: "grok-*", Protocol: APIProtocolResponses}, {Pattern: "gpt-*", Protocol: APIProtocolResponses}, {Pattern: "muse-spark-*", Protocol: APIProtocolResponses}, @@ -122,8 +122,8 @@ func DefaultOpenCodeGoProtocolRules() []OpenCodeGoProtocolRule { // DefaultOpenCodeZenProtocolRules 对齐 https://opencode.ai/docs/zen/ 端点表: // GPT/Grok/Muse Spark → Responses,Claude/Qwen(除 qwen3.8-max) → Anthropic, // qwen3.8-max 及其余模型 → Chat Completions。 -func DefaultOpenCodeZenProtocolRules() []OpenCodeGoProtocolRule { - return []OpenCodeGoProtocolRule{ +func DefaultOpenCodeZenProtocolRules() []ProtocolRule { + return []ProtocolRule{ {Pattern: "grok-*", Protocol: APIProtocolResponses}, {Pattern: "gpt-*", Protocol: APIProtocolResponses}, {Pattern: "muse-spark-*", Protocol: APIProtocolResponses}, @@ -133,12 +133,7 @@ func DefaultOpenCodeZenProtocolRules() []OpenCodeGoProtocolRule { } } -// defaultOpenCodeProtocolRules 从 provider profile 取该接入模式的内置分流表。 -func defaultOpenCodeProtocolRules(mode string) []OpenCodeGoProtocolRule { - return LookupProviderProfile(PlatformOpenCodeGo).Endpoints(mode).ProtocolRules -} - -func isNativeOpenCodeGoProtocol(protocol string) bool { +func isNativeUpstreamProtocol(protocol string) bool { switch protocol { case APIProtocolChatCompletions, APIProtocolAnthropic, APIProtocolResponses: return true @@ -147,7 +142,7 @@ func isNativeOpenCodeGoProtocol(protocol string) bool { } } -func openCodeGoPatternMatches(pattern, model string) bool { +func protocolRulePatternMatches(pattern, model string) bool { pattern = strings.ToLower(strings.TrimSpace(pattern)) model = normalizeOpenCodeGoModelID(model) if pattern == "" || model == "" { @@ -162,12 +157,12 @@ func openCodeGoPatternMatches(pattern, model string) bool { return model == pattern } -func matchOpenCodeGoProtocolRules(model string, rules []OpenCodeGoProtocolRule) string { +func matchProtocolRules(model string, rules []ProtocolRule) string { for _, rule := range rules { - if !isNativeOpenCodeGoProtocol(rule.Protocol) { + if !isNativeUpstreamProtocol(rule.Protocol) { continue } - if openCodeGoPatternMatches(rule.Pattern, model) { + if protocolRulePatternMatches(rule.Pattern, model) { return rule.Protocol } } @@ -178,33 +173,33 @@ func matchOpenCodeGoProtocolRules(model string, rules []OpenCodeGoProtocolRule) // 未命中时为 Chat Completions。账号自定义 protocol_rules 见 // ResolveOpenCodeGoUpstreamProtocol。 func OpenCodeGoModelProtocol(model string) string { - return matchOpenCodeGoProtocolRules(model, DefaultOpenCodeGoProtocolRules()) + return matchProtocolRules(model, DefaultOpenCodeGoProtocolRules()) } -func (a *Account) openCodeGoProtocolRules() ([]OpenCodeGoProtocolRule, bool) { +func (a *Account) configuredProtocolRules() ([]ProtocolRule, bool) { if a == nil || a.Credentials == nil { return nil, false } - raw, ok := a.Credentials[openCodeGoProtocolRulesKey] + raw, ok := a.Credentials[protocolRulesCredentialKey] if !ok || raw == nil { return nil, false } - rules, err := parseOpenCodeGoProtocolRules(raw) + rules, err := parseProtocolRules(raw) if err != nil { return nil, false } return rules, true } -func parseOpenCodeGoProtocolRules(raw any) ([]OpenCodeGoProtocolRule, error) { - items, err := openCodeGoProtocolRuleItems(raw) +func parseProtocolRules(raw any) ([]ProtocolRule, error) { + items, err := protocolRuleItems(raw) if err != nil { return nil, err } - if len(items) > maxOpenCodeGoProtocolRules { - return nil, fmt.Errorf("protocol_rules supports at most %d entries", maxOpenCodeGoProtocolRules) + if len(items) > maxProtocolRules { + return nil, fmt.Errorf("protocol_rules supports at most %d entries", maxProtocolRules) } - rules := make([]OpenCodeGoProtocolRule, 0, len(items)) + rules := make([]ProtocolRule, 0, len(items)) for i, item := range items { entry, ok := item.(map[string]any) if !ok { @@ -212,20 +207,20 @@ func parseOpenCodeGoProtocolRules(raw any) ([]OpenCodeGoProtocolRule, error) { } pattern, _ := entry["pattern"].(string) protocol, _ := entry["protocol"].(string) - pattern, err := normalizeOpenCodeGoProtocolPattern(pattern) + pattern, err := normalizeProtocolRulePattern(pattern) if err != nil { return nil, fmt.Errorf("protocol_rules[%d]: %w", i, err) } protocol = strings.TrimSpace(protocol) - if !isNativeOpenCodeGoProtocol(protocol) { + if !isNativeUpstreamProtocol(protocol) { return nil, fmt.Errorf("protocol_rules[%d]: protocol must be chat_completions, anthropic, or responses", i) } - rules = append(rules, OpenCodeGoProtocolRule{Pattern: pattern, Protocol: protocol}) + rules = append(rules, ProtocolRule{Pattern: pattern, Protocol: protocol}) } return rules, nil } -func openCodeGoProtocolRuleItems(raw any) ([]any, error) { +func protocolRuleItems(raw any) ([]any, error) { switch items := raw.(type) { case []any: return items, nil @@ -240,12 +235,12 @@ func openCodeGoProtocolRuleItems(raw any) ([]any, error) { } } -func normalizeOpenCodeGoProtocolPattern(pattern string) (string, error) { +func normalizeProtocolRulePattern(pattern string) (string, error) { pattern = strings.ToLower(strings.TrimSpace(pattern)) if pattern == "" { return "", fmt.Errorf("pattern is required") } - if len(pattern) > maxOpenCodeGoProtocolPatternLength { + if len(pattern) > maxProtocolRulePatternLength { return "", fmt.Errorf("pattern is too long") } if strings.ContainsAny(pattern, " \t") { @@ -258,17 +253,17 @@ func normalizeOpenCodeGoProtocolPattern(pattern string) (string, error) { return pattern, nil } -// NormalizeOpenCodeGoProtocolRulesCredentials 校验并原地规范化 credentials.protocol_rules。 +// NormalizeProtocolRulesCredentials 校验并原地规范化 credentials.protocol_rules。 // 未携带该字段时为 no-op,使旧账号继续使用内置默认表。 -func NormalizeOpenCodeGoProtocolRulesCredentials(credentials map[string]any) error { +func NormalizeProtocolRulesCredentials(credentials map[string]any) error { if credentials == nil { return nil } - raw, ok := credentials[openCodeGoProtocolRulesKey] + raw, ok := credentials[protocolRulesCredentialKey] if !ok || raw == nil { return nil } - rules, err := parseOpenCodeGoProtocolRules(raw) + rules, err := parseProtocolRules(raw) if err != nil { return infraerrors.New(http.StatusBadRequest, "INVALID_OPENCODE_GO_PROTOCOL_RULES", err.Error()) } @@ -279,7 +274,7 @@ func NormalizeOpenCodeGoProtocolRulesCredentials(credentials map[string]any) err "protocol": rule.Protocol, }) } - credentials[openCodeGoProtocolRulesKey] = encoded + credentials[protocolRulesCredentialKey] = encoded return nil } @@ -327,19 +322,12 @@ func openCodeGoNativeProtocol(account *Account, model string) string { // ResolveOpenCodeGoUpstreamProtocol 按账号协议配置与模型规则决定上游协议。 // 显式 pinned 协议优先;adaptive(默认)先走 credentials.protocol_rules, // 未配置时回落内置默认表;已配置但未命中则走 Chat Completions。 +// 规则见 resolveModelRoutedProtocol。 func (a *Account) ResolveOpenCodeGoUpstreamProtocol(model string) string { if a == nil || !a.IsOpenCodeGo() { return "" } - switch a.GetAPIProtocol() { - case APIProtocolChatCompletions, APIProtocolAnthropic, APIProtocolResponses: - return a.GetAPIProtocol() - default: - if rules, present := a.openCodeGoProtocolRules(); present { - return matchOpenCodeGoProtocolRules(model, rules) - } - return matchOpenCodeGoProtocolRules(model, defaultOpenCodeProtocolRules(a.GetOpenCodeAccountMode())) - } + return a.resolveModelRoutedProtocol(model) } // openCodeGoQuotaURL 根据 base_url 解析 OpenCode Go 额度端点。 diff --git a/backend/internal/service/opencode_go_test.go b/backend/internal/service/opencode_go_test.go index 2583d30ac1..a8dbce1003 100644 --- a/backend/internal/service/opencode_go_test.go +++ b/backend/internal/service/opencode_go_test.go @@ -67,7 +67,7 @@ func TestResolveOpenCodeGoUpstreamProtocolUsesAccountRules(t *testing.T) { Platform: PlatformOpenCodeGo, Credentials: map[string]any{ "api_protocol": APIProtocolAdaptive, - openCodeGoProtocolRulesKey: []any{ + protocolRulesCredentialKey: []any{ map[string]any{"pattern": "grok-*", "protocol": APIProtocolChatCompletions}, map[string]any{"pattern": "deepseek-v4-flash", "protocol": APIProtocolResponses}, map[string]any{"pattern": "qwen*", "protocol": APIProtocolAnthropic}, @@ -86,7 +86,7 @@ func TestResolveOpenCodeGoUpstreamProtocolEmptyRulesAreAllChatCompletions(t *tes account := &Account{ Platform: PlatformOpenCodeGo, Credentials: map[string]any{ - openCodeGoProtocolRulesKey: []any{}, + protocolRulesCredentialKey: []any{}, }, } require.Equal(t, APIProtocolChatCompletions, account.ResolveOpenCodeGoUpstreamProtocol("grok-4.6")) @@ -98,7 +98,7 @@ func TestResolveOpenCodeGoUpstreamProtocolFirstMatchWins(t *testing.T) { account := &Account{ Platform: PlatformOpenCodeGo, Credentials: map[string]any{ - openCodeGoProtocolRulesKey: []any{ + protocolRulesCredentialKey: []any{ map[string]any{"pattern": "gpt-5.6-luna", "protocol": APIProtocolChatCompletions}, map[string]any{"pattern": "gpt-*", "protocol": APIProtocolResponses}, }, @@ -114,7 +114,7 @@ func TestOpenCodeGoNativeProtocolUnmatchedFallsBackToChatCompletions(t *testing. Platform: PlatformOpenCodeGo, Credentials: map[string]any{ "api_protocol": APIProtocolAdaptive, - openCodeGoProtocolRulesKey: []any{ + protocolRulesCredentialKey: []any{ map[string]any{"pattern": "grok-*", "protocol": APIProtocolResponses}, map[string]any{"pattern": "gpt-*", "protocol": APIProtocolResponses}, map[string]any{"pattern": "qwen*", "protocol": APIProtocolAnthropic}, @@ -136,12 +136,12 @@ func TestOpenCodeGoNativeProtocolUnmatchedFallsBackToChatCompletions(t *testing. func TestParseOpenCodeGoProtocolRulesAcceptsTypedMaps(t *testing.T) { t.Parallel() - rules, err := parseOpenCodeGoProtocolRules([]map[string]any{ + rules, err := parseProtocolRules([]map[string]any{ {"pattern": "grok-*", "protocol": APIProtocolResponses}, {"pattern": "qwen*", "protocol": APIProtocolAnthropic}, }) require.NoError(t, err) - require.Equal(t, []OpenCodeGoProtocolRule{ + require.Equal(t, []ProtocolRule{ {Pattern: "grok-*", Protocol: APIProtocolResponses}, {Pattern: "qwen*", Protocol: APIProtocolAnthropic}, }, rules) @@ -178,31 +178,31 @@ func TestStampOpenAIResponsesUpstreamEndpoint(t *testing.T) { func TestNormalizeOpenCodeGoProtocolRulesCredentials(t *testing.T) { t.Parallel() - require.NoError(t, NormalizeOpenCodeGoProtocolRulesCredentials(nil)) - require.NoError(t, NormalizeOpenCodeGoProtocolRulesCredentials(map[string]any{})) + require.NoError(t, NormalizeProtocolRulesCredentials(nil)) + require.NoError(t, NormalizeProtocolRulesCredentials(map[string]any{})) creds := map[string]any{ - openCodeGoProtocolRulesKey: []any{ + protocolRulesCredentialKey: []any{ map[string]any{"pattern": " Grok-* ", "protocol": APIProtocolResponses}, }, } - require.NoError(t, NormalizeOpenCodeGoProtocolRulesCredentials(creds)) - rules, ok := creds[openCodeGoProtocolRulesKey].([]any) + require.NoError(t, NormalizeProtocolRulesCredentials(creds)) + rules, ok := creds[protocolRulesCredentialKey].([]any) require.True(t, ok) require.NotEmpty(t, rules) entry, ok := rules[0].(map[string]any) require.True(t, ok) require.Equal(t, "grok-*", entry["pattern"]) - err := NormalizeOpenCodeGoProtocolRulesCredentials(map[string]any{ - openCodeGoProtocolRulesKey: []any{ + err := NormalizeProtocolRulesCredentials(map[string]any{ + protocolRulesCredentialKey: []any{ map[string]any{"pattern": "*grok", "protocol": APIProtocolResponses}, }, }) require.Error(t, err) - err = NormalizeOpenCodeGoProtocolRulesCredentials(map[string]any{ - openCodeGoProtocolRulesKey: []any{ + err = NormalizeProtocolRulesCredentials(map[string]any{ + protocolRulesCredentialKey: []any{ map[string]any{"pattern": "grok-*", "protocol": "adaptive"}, }, }) diff --git a/backend/internal/service/provider_profile.go b/backend/internal/service/provider_profile.go index 7fee5d96df..111cf968fb 100644 --- a/backend/internal/service/provider_profile.go +++ b/backend/internal/service/provider_profile.go @@ -11,9 +11,21 @@ type ProviderEndpoints struct { BaseURLs map[string]string // ProtocolRules 是按模型分流的内置默认表(首条命中生效);为空表示该模式 // 不按模型分流,由账号 api_protocol 决定上游协议。 - ProtocolRules []OpenCodeGoProtocolRule + ProtocolRules []ProtocolRule } +// ProviderRouting 决定多协议供应商账号如何选择上游协议。 +type ProviderRouting string + +const ( + // ProviderRoutingByInbound 适用于单一厂商:模型在各原生端点都可用,adaptive 账号 + // 按入站协议选同协议端点,供应商不提供该协议时回落 Chat Completions。 + ProviderRoutingByInbound ProviderRouting = "by_inbound" + // ProviderRoutingByModel 适用于多模型聚合平台:每个模型只在某一协议端点提供, + // 按 protocol_rules 以模型名选协议,与入站协议无关。 + ProviderRoutingByModel ProviderRouting = "by_model" +) + // ProviderProfile 描述一个多协议 API Key 供应商(国产厂商或多模型聚合平台)的 // 静态数据:各接入模式的默认端点、内置分流规则与端点路径约定。 // 额度解析、会话头等行为差异不在这里,仍由各自的代码路径处理。 @@ -22,6 +34,8 @@ type ProviderProfile struct { // DefaultMode 在 credentials.account_mode 缺失或不在 Modes 中时使用。 DefaultMode string Modes map[string]ProviderEndpoints + // Routing 为空时按 ProviderRoutingByInbound 处理。 + Routing ProviderRouting // ResponsesPath 覆盖 Responses 端点路径(按 buildOpenAIEndpointURL 的版本感知 // 规则拼接),空值为 /v1/responses。对自定义 base_url 的账号同样生效。 ResponsesPath string @@ -50,12 +64,13 @@ func (p *ProviderProfile) SupportsProtocol(mode, protocol string) bool { // providerProfiles 是多协议 API Key 供应商的单一数据来源。新增同类供应商时在此 // 登记一条即可获得默认端点、原生 Responses 能力判定(有 responses 条目即支持)、 -// Responses 路径约定与 IsMultiProtocolAPIKeyProvider 归属。 +// 上游协议分流方式、Responses 路径约定与 IsMultiProtocolAPIKeyProvider 归属。 // 默认端点需与前端 credentialsBuilder.ts 的预设保持一致。 var providerProfiles = map[string]*ProviderProfile{ PlatformKimi: { Platform: PlatformKimi, DefaultMode: AccountModePayG, + Routing: ProviderRoutingByInbound, Modes: map[string]ProviderEndpoints{ AccountModePayG: { BaseURLs: map[string]string{ @@ -76,6 +91,7 @@ var providerProfiles = map[string]*ProviderProfile{ PlatformZhipu: { Platform: PlatformZhipu, DefaultMode: AccountModePayG, + Routing: ProviderRoutingByInbound, // 智谱没有原生 Responses 端点,故不登记 responses 条目。 Modes: map[string]ProviderEndpoints{ AccountModePayG: { @@ -95,6 +111,7 @@ var providerProfiles = map[string]*ProviderProfile{ PlatformDeepseek: { Platform: PlatformDeepseek, DefaultMode: AccountModePayG, + Routing: ProviderRoutingByInbound, // DeepSeek 官方 Responses 端点为 /responses(无 /v1 前缀,适配 Codex)。 ResponsesPath: "/responses", Modes: map[string]ProviderEndpoints{ @@ -110,6 +127,7 @@ var providerProfiles = map[string]*ProviderProfile{ PlatformMiniMax: { Platform: PlatformMiniMax, DefaultMode: AccountModePayG, + Routing: ProviderRoutingByInbound, Modes: map[string]ProviderEndpoints{ // 按量付费与 Coding/Token Plan 共用推理域名,靠 API Key 区分套餐。 AccountModePayG: { @@ -131,6 +149,7 @@ var providerProfiles = map[string]*ProviderProfile{ PlatformOpenCodeGo: { Platform: PlatformOpenCodeGo, DefaultMode: AccountModeGo, + Routing: ProviderRoutingByModel, Modes: map[string]ProviderEndpoints{ AccountModeGo: { BaseURLs: map[string]string{ @@ -179,3 +198,9 @@ func (a *Account) providerSupportsProtocol(protocol string) bool { profile := a.providerProfile() return profile != nil && profile.SupportsProtocol(a.GetCredential("account_mode"), protocol) } + +// routesByModel 报告账号所在供应商是否按模型名分流上游协议(多模型聚合平台)。 +func (a *Account) routesByModel() bool { + profile := a.providerProfile() + return profile != nil && profile.Routing == ProviderRoutingByModel +} diff --git a/backend/internal/service/provider_profile_test.go b/backend/internal/service/provider_profile_test.go index 1dc9f94175..e9fc2994bd 100644 --- a/backend/internal/service/provider_profile_test.go +++ b/backend/internal/service/provider_profile_test.go @@ -150,7 +150,7 @@ func TestProviderProfile_BaseURLKeysAreNativeProtocols(t *testing.T) { for mode, endpoints := range profile.Modes { require.NotEmpty(t, endpoints.BaseURLs[APIProtocolChatCompletions], "%s/%s must have a chat_completions base", platform, mode) for protocol, baseURL := range endpoints.BaseURLs { - require.True(t, isNativeOpenCodeGoProtocol(protocol), "%s/%s has unknown protocol key %q", platform, mode, protocol) + require.True(t, isNativeUpstreamProtocol(protocol), "%s/%s has unknown protocol key %q", platform, mode, protocol) require.NotEmpty(t, baseURL, "%s/%s/%s", platform, mode, protocol) } } @@ -180,8 +180,9 @@ func TestProviderProfile_ResponsesPathMatchesLegacy(t *testing.T) { func TestProviderProfile_OpenCodeProtocolRulesByMode(t *testing.T) { t.Parallel() - require.Equal(t, DefaultOpenCodeGoProtocolRules(), defaultOpenCodeProtocolRules(AccountModeGo)) - require.Equal(t, DefaultOpenCodeGoProtocolRules(), defaultOpenCodeProtocolRules("")) - require.Equal(t, DefaultOpenCodeZenProtocolRules(), defaultOpenCodeProtocolRules(AccountModeZen)) + openCode := LookupProviderProfile(PlatformOpenCodeGo) + require.Equal(t, DefaultOpenCodeGoProtocolRules(), openCode.Endpoints(AccountModeGo).ProtocolRules) + require.Equal(t, DefaultOpenCodeGoProtocolRules(), openCode.Endpoints("").ProtocolRules) + require.Equal(t, DefaultOpenCodeZenProtocolRules(), openCode.Endpoints(AccountModeZen).ProtocolRules) require.Empty(t, LookupProviderProfile(PlatformKimi).Endpoints(AccountModeCoding).ProtocolRules) } diff --git a/backend/internal/service/upstream_protocol_routing.go b/backend/internal/service/upstream_protocol_routing.go new file mode 100644 index 0000000000..c0c6df333c --- /dev/null +++ b/backend/internal/service/upstream_protocol_routing.go @@ -0,0 +1,92 @@ +package service + +import ( + "encoding/json" + "fmt" + + "github.com/Wei-Shaw/sub2api/internal/pkg/apicompat" +) + +// resolveUpstreamProtocol 决定 OpenAI 网关本次请求发往上游的协议 +// (chat_completions / responses / anthropic),是 /v1/responses、 +// /v1/chat/completions、/v1/messages 三个入站入口共用的唯一判定。 +// 只做判断,不改写请求体、不发请求;各入口再按「入站 × 上游」选择转换路径。 +// +// inbound 为入站协议;/v1/chat/completions 收到 Responses 形状请求体时按 +// responses 计。model 仅按模型分流的账号使用,取 upstreamRoutingModel 的结果。 +// +// 优先级: +// 1. 按模型分流的供应商(多模型聚合平台,如 OpenCode):显式 api_protocol → +// 账号 protocol_rules → profile 内置规则 → Chat Completions,与入站协议无关。 +// 2. adaptive(按入站协议分流):供应商提供入站协议的原生端点则走同协议, +// 否则回落 Chat Completions。 +// 3. 显式 anthropic 协议 → Anthropic。 +// 4. shouldForwardOpenAIResponsesViaRawChatCompletions(显式 chat_completions、 +// 探针确认不支持 Responses 等)→ Chat Completions。 +// 5. 其余 → Responses。 +// +// Grok 在 Responses / Chat Completions 入口有专属链路,须在调用本函数前分流。 +func resolveUpstreamProtocol(account *Account, inbound, model string) string { + if account.routesByModel() { + return account.resolveModelRoutedProtocol(model) + } + if account.IsAdaptiveAPIProtocol() { + if account.providerSupportsProtocol(inbound) { + return inbound + } + return APIProtocolChatCompletions + } + if account.IsAnthropicProtocol() { + return APIProtocolAnthropic + } + if shouldForwardOpenAIResponsesViaRawChatCompletions(account) { + return APIProtocolChatCompletions + } + return APIProtocolResponses +} + +// resolveModelRoutedProtocol 按模型名解析按模型分流账号的上游协议。 +// 显式 pinned 协议优先;adaptive 先走 credentials.protocol_rules,未配置时回落 +// profile 对应接入模式的内置规则;规则未命中或结果未知一律 Chat Completions, +// 避免落入 Responses 转换链。 +func (a *Account) resolveModelRoutedProtocol(model string) string { + switch proto := a.GetAPIProtocol(); proto { + case APIProtocolChatCompletions, APIProtocolAnthropic, APIProtocolResponses: + return proto + } + rules, present := a.configuredProtocolRules() + if !present { + rules = a.providerProfile().Endpoints(a.GetCredential("account_mode")).ProtocolRules + } + return matchProtocolRules(model, rules) +} + +// upstreamRoutingModel 返回参与协议分流的模型名:仅按模型分流的账号需要,按账号 +// 模型映射与上游归一后的名字匹配规则;其余账号的分流与模型无关,返回空串。 +func upstreamRoutingModel(account *Account, body []byte, defaultMappedModel string) string { + if !account.routesByModel() { + return "" + } + return resolveMappedUpstreamModel(account, body, defaultMappedModel) +} + +// convertResponsesShapedChatBody 把发到 /v1/chat/completions 的 Responses 形状 +// 请求体(Cursor 兼容)转换为 Chat Completions 请求体。 +func (s *OpenAIGatewayService) convertResponsesShapedChatBody(body []byte) ([]byte, error) { + var responsesReq apicompat.ResponsesRequest + if err := json.Unmarshal(body, &responsesReq); err != nil { + return nil, fmt.Errorf("parse responses-shaped chat completions request: %w", err) + } + chatReq, err := apicompat.ResponsesToChatCompletionsRequestWithOptions( + &responsesReq, + &apicompat.ResponsesToChatOptions{ReasoningContentByID: s.reasoningContentByID}, + ) + if err != nil { + return nil, fmt.Errorf("convert responses-shaped chat completions request: %w", err) + } + chatBody, err := json.Marshal(chatReq) + if err != nil { + return nil, fmt.Errorf("marshal converted chat completions request: %w", err) + } + return chatBody, nil +} diff --git a/backend/internal/service/upstream_protocol_routing_matrix_test.go b/backend/internal/service/upstream_protocol_routing_matrix_test.go new file mode 100644 index 0000000000..fc3a5165a1 --- /dev/null +++ b/backend/internal/service/upstream_protocol_routing_matrix_test.go @@ -0,0 +1,344 @@ +//go:build unit + +package service + +import ( + "context" + "errors" + "fmt" + "os" + "sort" + "strings" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/pkg/openai_compat" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +// 上游协议分流矩阵:经真实入口(Forward / ForwardAsChatCompletions / +// ForwardAsAnthropic)遍历 平台 × api_protocol × 探针 × 账号类型 × 接入模式 × +// protocol_rules × 入站 × 模型,从录制到的上游 URL 与请求体推断实际走的协议 +// 与是否做了 Responses 形状转换,并与 legacyUpstreamRouting(统一判定前三个 +// 入口各自的分流顺序)逐条比对。 +// +// 设置 ROUTING_MATRIX_DUMP= 时把全部观测(含 URL、上游模型、错误)按行 +// 写入文件,便于在两个版本间直接 diff。 + +type routingMatrixIngress struct { + name string + path string + responsesBody bool + forward func(*OpenAIGatewayService, *gin.Context, *Account, []byte) error +} + +func routingMatrixIngresses() []routingMatrixIngress { + return []routingMatrixIngress{ + { + name: "responses", path: "/v1/responses", responsesBody: true, + forward: func(svc *OpenAIGatewayService, c *gin.Context, account *Account, body []byte) error { + _, err := svc.Forward(context.Background(), c, account, body) + return err + }, + }, + { + name: "chat", path: "/v1/chat/completions", + forward: func(svc *OpenAIGatewayService, c *gin.Context, account *Account, body []byte) error { + _, err := svc.ForwardAsChatCompletions(context.Background(), c, account, body, "", "") + return err + }, + }, + { + name: "chat_responses_shape", path: "/v1/chat/completions", responsesBody: true, + forward: func(svc *OpenAIGatewayService, c *gin.Context, account *Account, body []byte) error { + _, err := svc.ForwardAsChatCompletions(context.Background(), c, account, body, "", "") + return err + }, + }, + { + name: "messages", path: "/v1/messages", + forward: func(svc *OpenAIGatewayService, c *gin.Context, account *Account, body []byte) error { + _, err := svc.ForwardAsAnthropic(context.Background(), c, account, body, "", "") + return err + }, + }, + } +} + +type routingMatrixCase struct { + platform string + apiProtocol string + mode string + accountType string + probe string + rules bool + ingress routingMatrixIngress + model string +} + +func (tc routingMatrixCase) key() string { + return fmt.Sprintf("%s|proto=%s|mode=%s|type=%s|probe=%s|rules=%t|%s|%s", + tc.platform, tc.apiProtocol, tc.mode, tc.accountType, tc.probe, tc.rules, tc.ingress.name, tc.model) +} + +func (tc routingMatrixCase) account() *Account { + credentials := map[string]any{ + "api_key": "sk-test", + "base_url": "http://base.example", + "api_base_urls": map[string]any{ + APIProtocolChatCompletions: "http://cc.example", + APIProtocolResponses: "http://responses.example", + APIProtocolAnthropic: "http://anthropic.example", + }, + } + if tc.apiProtocol != "" { + credentials["api_protocol"] = tc.apiProtocol + } + if tc.mode != "" { + credentials["account_mode"] = tc.mode + } + if tc.rules { + credentials["protocol_rules"] = []any{ + map[string]any{"pattern": "glm-*", "protocol": APIProtocolAnthropic}, + map[string]any{"pattern": "gpt-*", "protocol": APIProtocolResponses}, + } + } + extra := map[string]any{} + switch tc.probe { + case "yes": + extra[openai_compat.ExtraKeyResponsesSupported] = true + case "no": + extra[openai_compat.ExtraKeyResponsesSupported] = false + } + return &Account{ + ID: 801, + Name: "routing-matrix", + Platform: tc.platform, + Type: tc.accountType, + Concurrency: 1, + Credentials: credentials, + Extra: extra, + } +} + +func (tc routingMatrixCase) body() []byte { + switch { + case tc.ingress.responsesBody: + return []byte(fmt.Sprintf(`{"model":%q,"input":"hello","max_output_tokens":32,"stream":false}`, tc.model)) + case tc.ingress.name == "messages": + return []byte(fmt.Sprintf(`{"model":%q,"max_tokens":32,"messages":[{"role":"user","content":"hello"}],"stream":false}`, tc.model)) + default: + return []byte(fmt.Sprintf(`{"model":%q,"messages":[{"role":"user","content":"hello"}],"stream":false}`, tc.model)) + } +} + +func routingMatrixCases() []routingMatrixCase { + var cases []routingMatrixCase + protocols := []string{"", APIProtocolAdaptive, APIProtocolChatCompletions, APIProtocolAnthropic, APIProtocolResponses} + types := []string{AccountTypeAPIKey, AccountTypeUpstream, AccountTypeOAuth} + probes := []string{"", "yes", "no"} + add := func(platform string, modes, models []string, rulesOptions []bool, probeOptions, typeOptions []string, ingresses []routingMatrixIngress) { + for _, proto := range protocols { + for _, mode := range modes { + for _, accountType := range typeOptions { + for _, probe := range probeOptions { + for _, rules := range rulesOptions { + for _, ingress := range ingresses { + for _, model := range models { + cases = append(cases, routingMatrixCase{ + platform: platform, apiProtocol: proto, mode: mode, accountType: accountType, + probe: probe, rules: rules, ingress: ingress, model: model, + }) + } + } + } + } + } + } + } + } + all := routingMatrixIngresses() + add(PlatformKimi, []string{AccountModePayG}, []string{"kimi-k2"}, []bool{false}, probes, types, all) + add(PlatformZhipu, []string{AccountModePayG}, []string{"glm-4.7"}, []bool{false}, probes, types, all) + add(PlatformDeepseek, []string{AccountModePayG}, []string{"deepseek-chat"}, []bool{false}, probes, types, all) + add(PlatformOpenAI, []string{""}, []string{"gpt-5"}, []bool{false}, probes, types, all) + add(PlatformOpenCodeGo, []string{AccountModeGo, AccountModeZen}, + []string{"gpt-5.6-luna", "minimax-m3", "glm-5.3", "claude-sonnet-4"}, + []bool{false, true}, []string{"", "no"}, []string{AccountTypeAPIKey, AccountTypeUpstream}, all) + // Grok 仅 /v1/messages 经统一判定;另两个入口在判定前走 Grok 专属链路。 + add(PlatformGrok, []string{""}, []string{"grok-4"}, []bool{false}, probes, types, all[3:]) + return cases +} + +type routingObservation struct { + urls []string + lastBody []byte + errText string + panicText string +} + +func (o routingObservation) protocol() string { + if len(o.urls) == 0 { + return "" + } + last := o.urls[len(o.urls)-1] + switch { + case strings.HasSuffix(last, "/chat/completions"): + return APIProtocolChatCompletions + case strings.HasSuffix(last, "/messages"): + return APIProtocolAnthropic + case strings.HasSuffix(last, "/responses"): + return APIProtocolResponses + default: + return "other:" + last + } +} + +// bodyKind 报告最后一个上游请求体的形状:Chat Completions 上游收到 messages +// 说明 Responses 形状请求体已被转换,收到 input 说明原样透传。 +func (o routingObservation) bodyKind() string { + switch { + case gjson.GetBytes(o.lastBody, "messages").Exists(): + return "messages" + case gjson.GetBytes(o.lastBody, "input").Exists(): + return "input" + default: + return "other" + } +} + +func (o routingObservation) String() string { + if o.panicText != "" { + return "panic: " + o.panicText + } + if len(o.urls) == 0 { + return "no-upstream: " + o.errText + } + return fmt.Sprintf("urls=%s body=%s model=%s", + strings.Join(o.urls, ","), o.bodyKind(), gjson.GetBytes(o.lastBody, "model").String()) +} + +func observeRouting(tc routingMatrixCase) (obs routingObservation) { + upstream := &httpUpstreamRecorder{err: errors.New("stop after capture")} + svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream} + body := tc.body() + defer func() { + if r := recover(); r != nil { + obs.panicText = fmt.Sprint(r) + } + for _, req := range upstream.requests { + obs.urls = append(obs.urls, req.URL.String()) + } + obs.lastBody = upstream.lastBody + }() + err := tc.ingress.forward(svc, adaptiveProtocolTestContext(tc.ingress.path, body), tc.account(), body) + if err != nil { + obs.errText = err.Error() + } + return obs +} + +// legacyUpstreamRouting 复述统一判定前三个入口各自的分流顺序,返回预期的上游协议 +// 以及 Chat Completions 上游是否先把 Responses 形状请求体转换成 messages。 +func legacyUpstreamRouting(account *Account, ingress routingMatrixIngress, model string) (string, bool) { + openCode := account.IsOpenCodeGo() + var openCodeProto string + if openCode { + openCodeProto = openCodeGoNativeProtocol(account, model) + } + switch ingress.name { + case "responses": + if openCode && openCodeProto != APIProtocolResponses { + return openCodeProto, false + } + if account.IsAnthropicProtocol() { + return APIProtocolAnthropic, false + } + // 有意差异:adaptive 且供应商无原生 Responses 端点时,统一判定对任何账号类型 + // 都回落 Chat Completions(旧 /v1/responses 入口对非 API Key 账号会误发到 + // 不存在的 /responses;Chat Completions 入口本就如此处理)。 + if account.IsAdaptiveAPIProtocol() && !account.SupportsNativeCNResponses() { + return APIProtocolChatCompletions, false + } + if shouldForwardOpenAIResponsesViaRawChatCompletions(account) { + return APIProtocolChatCompletions, false + } + return APIProtocolResponses, false + case "chat", "chat_responses_shape": + shape := ingress.responsesBody + if openCode && openCodeProto != APIProtocolResponses { + return openCodeProto, shape + } + if account.IsAdaptiveAPIProtocol() && !openCode { + if !shape { + return APIProtocolChatCompletions, false + } + if !account.SupportsNativeCNResponses() { + return APIProtocolChatCompletions, true + } + } + if account.IsAnthropicProtocol() { + return APIProtocolAnthropic, false + } + if shouldForwardOpenAIResponsesViaRawChatCompletions(account) { + return APIProtocolChatCompletions, false + } + return APIProtocolResponses, false + case "messages": + if openCode { + if openCodeProto != APIProtocolResponses { + return openCodeProto, false + } + } else if account.IsAnthropicProtocol() || account.IsAdaptiveAPIProtocol() { + return APIProtocolAnthropic, false + } + if shouldForwardOpenAIResponsesViaRawChatCompletions(account) { + return APIProtocolChatCompletions, false + } + return APIProtocolResponses, false + } + panic("unknown ingress " + ingress.name) +} + +func TestUpstreamProtocolRoutingMatrixMatchesLegacy(t *testing.T) { + gin.SetMode(gin.TestMode) + + cases := routingMatrixCases() + observations := make([]routingObservation, len(cases)) + dump := make([]string, 0, len(cases)) + for i, tc := range cases { + observations[i] = observeRouting(tc) + dump = append(dump, tc.key()+" => "+observations[i].String()) + } + if path := os.Getenv("ROUTING_MATRIX_DUMP"); path != "" { + sort.Strings(dump) + require.NoError(t, os.WriteFile(path, []byte(strings.Join(dump, "\n")+"\n"), 0o644)) + } + + compared := 0 + for i, tc := range cases { + obs := observations[i] + if tc.accountType == AccountTypeAPIKey && tc.platform != PlatformGrok { + require.NotEmpty(t, obs.urls, "API Key 账号应到达上游:%s\n%s", tc.key(), obs) + } + if obs.panicText != "" || len(obs.urls) == 0 { + // 请求在到达上游前就失败(凭证/类型不适配),无法从 URL 推断协议; + // 这类组合由 ROUTING_MATRIX_DUMP 的跨版本 diff 覆盖。 + continue + } + compared++ + account := tc.account() + model := resolveMappedUpstreamModel(account, tc.body(), "") + wantProto, wantConverted := legacyUpstreamRouting(account, tc.ingress, model) + require.Equal(t, wantProto, obs.protocol(), "%s\n%s", tc.key(), obs) + if wantProto == APIProtocolChatCompletions && tc.ingress.name == "chat_responses_shape" { + wantKind := "input" + if wantConverted { + wantKind = "messages" + } + require.Equal(t, wantKind, obs.bodyKind(), "%s\n%s", tc.key(), obs) + } + } + require.Positive(t, compared) +} diff --git a/backend/internal/service/upstream_protocol_routing_test.go b/backend/internal/service/upstream_protocol_routing_test.go new file mode 100644 index 0000000000..df487b1f2a --- /dev/null +++ b/backend/internal/service/upstream_protocol_routing_test.go @@ -0,0 +1,119 @@ +//go:build unit + +package service + +import ( + "testing" + + "github.com/Wei-Shaw/sub2api/internal/pkg/openai_compat" + "github.com/stretchr/testify/require" +) + +func routingTestAccount(platform, accountType string, credentials, extra map[string]any) *Account { + if credentials == nil { + credentials = map[string]any{} + } + credentials["api_key"] = "sk-test" + return &Account{Platform: platform, Type: accountType, Credentials: credentials, Extra: extra} +} + +func TestResolveUpstreamProtocol(t *testing.T) { + t.Parallel() + + const ( + cc = APIProtocolChatCompletions + responses = APIProtocolResponses + anthropic = APIProtocolAnthropic + ) + adaptive := func(platform string) *Account { + return routingTestAccount(platform, AccountTypeAPIKey, map[string]any{"api_protocol": APIProtocolAdaptive}, nil) + } + pinned := func(platform, protocol string) *Account { + return routingTestAccount(platform, AccountTypeAPIKey, map[string]any{"api_protocol": protocol}, nil) + } + openCode := func(mode string, credentials map[string]any) *Account { + if credentials == nil { + credentials = map[string]any{} + } + credentials["account_mode"] = mode + return routingTestAccount(PlatformOpenCodeGo, AccountTypeAPIKey, credentials, nil) + } + openAIWithProbe := func(accountType string, supported any) *Account { + extra := map[string]any{} + if supported != nil { + extra[openai_compat.ExtraKeyResponsesSupported] = supported + } + return routingTestAccount(PlatformOpenAI, accountType, nil, extra) + } + + cases := []struct { + name string + account *Account + inbound string + model string + want string + }{ + // 按入站协议分流(国产单一厂商 adaptive) + {"kimi adaptive anthropic inbound", adaptive(PlatformKimi), anthropic, "", anthropic}, + {"kimi adaptive cc inbound", adaptive(PlatformKimi), cc, "", cc}, + {"kimi adaptive responses inbound", adaptive(PlatformKimi), responses, "", responses}, + {"zhipu adaptive responses inbound falls back to cc", adaptive(PlatformZhipu), responses, "", cc}, + {"zhipu adaptive anthropic inbound", adaptive(PlatformZhipu), anthropic, "", anthropic}, + + // 显式固定协议,与入站无关 + {"kimi pinned anthropic", pinned(PlatformKimi, anthropic), cc, "", anthropic}, + {"kimi pinned cc", pinned(PlatformKimi, cc), responses, "", cc}, + {"kimi pinned responses", pinned(PlatformKimi, responses), anthropic, "", responses}, + {"zhipu pinned responses is unsupported and stays cc", pinned(PlatformZhipu, responses), responses, "", cc}, + + // 按模型分流(多模型聚合平台),与入站无关 + {"opencode go gpt", openCode(AccountModeGo, nil), anthropic, "gpt-5.6-luna", responses}, + {"opencode go minimax", openCode(AccountModeGo, nil), responses, "minimax-m3", anthropic}, + {"opencode go glm falls back to cc", openCode(AccountModeGo, nil), anthropic, "glm-5.3", cc}, + {"opencode go claude has no rule", openCode(AccountModeGo, nil), anthropic, "claude-sonnet-4", cc}, + {"opencode zen claude", openCode(AccountModeZen, nil), cc, "claude-sonnet-4", anthropic}, + {"opencode account rules override defaults", openCode(AccountModeGo, map[string]any{ + "protocol_rules": []any{map[string]any{"pattern": "glm-*", "protocol": anthropic}}, + }), cc, "glm-5.3", anthropic}, + {"opencode account rules miss falls back to cc", openCode(AccountModeGo, map[string]any{ + "protocol_rules": []any{map[string]any{"pattern": "glm-*", "protocol": anthropic}}, + }), cc, "gpt-5.6-luna", cc}, + {"opencode pinned protocol beats rules", openCode(AccountModeGo, map[string]any{"api_protocol": cc}), anthropic, "gpt-5.6-luna", cc}, + {"opencode ignores responses probe", func() *Account { + account := openCode(AccountModeGo, nil) + account.Extra = map[string]any{openai_compat.ExtraKeyResponsesSupported: false} + return account + }(), cc, "gpt-5.6-luna", responses}, + + // 无 profile 的账号按探针决定 Responses / CC + {"openai apikey unknown probe", openAIWithProbe(AccountTypeAPIKey, nil), cc, "", responses}, + {"openai apikey probe unsupported", openAIWithProbe(AccountTypeAPIKey, false), anthropic, "", cc}, + {"openai oauth ignores probe", openAIWithProbe(AccountTypeOAuth, false), cc, "", responses}, + } + for _, tc := range cases { + require.Equal(t, tc.want, resolveUpstreamProtocol(tc.account, tc.inbound, tc.model), tc.name) + } +} + +func TestRoutesByModelOnlyForAggregators(t *testing.T) { + t.Parallel() + + for platform, profile := range providerProfiles { + account := &Account{Platform: platform} + require.Equal(t, platform == PlatformOpenCodeGo, account.routesByModel(), platform) + require.Equal(t, account.IsOpenCodeGo(), profile.Routing == ProviderRoutingByModel, platform) + } + require.False(t, (&Account{Platform: PlatformOpenAI}).routesByModel()) + require.False(t, (*Account)(nil).routesByModel()) +} + +func TestUpstreamRoutingModelOnlyForModelRoutedAccounts(t *testing.T) { + t.Parallel() + + body := []byte(`{"model":"gpt-5.6-luna","input":"hi"}`) + openCode := routingTestAccount(PlatformOpenCodeGo, AccountTypeAPIKey, map[string]any{ + "model_mapping": map[string]any{"gpt-5.6-luna": "glm-5.3"}, + }, nil) + require.Equal(t, "glm-5.3", upstreamRoutingModel(openCode, body, "")) + require.Empty(t, upstreamRoutingModel(routingTestAccount(PlatformKimi, AccountTypeAPIKey, nil, nil), body, "")) +} From 105c955c8856a0ac842094d0cb1b030fd33ad37e Mon Sep 17 00:00:00 2001 From: SavitarC <71271200+SavitarC@users.noreply.github.com> Date: Sun, 27 Sep 2026 11:08:41 +0800 Subject: [PATCH 04/19] =?UTF-8?q?fix(gateway):=20/v1/responses=20=E8=BD=AC?= =?UTF-8?q?=20Anthropic=20=E6=97=B6=E7=BB=9F=E4=B8=80=E4=BB=A5=E5=8E=BB?= =?UTF-8?q?=E7=A9=BA=E7=99=BD=E7=9A=84=E8=AF=B7=E6=B1=82=E6=A8=A1=E5=9E=8B?= =?UTF-8?q?=E5=85=9C=E5=BA=95=E6=98=A0=E5=B0=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit forwardResponsesViaNativeAnthropic 的 defaultMappedModel 是账号 model_mapping 未命中时的兜底模型。此前按模型分流的账号(OpenCode)传空串、其余账号传 reqModel,源自两处分支各自实现。映射未命中且请求模型带首尾空白时,前者的 计费模型名保留空白(上游模型名因 normalizeOpenAIModelForUpstream 已去空白, 两者不一致,定价查找可能落空),后者为去空白的名字。 统一传 reqModel,并移除入口里最后一处 routesByModel 分支。仅影响按模型 分流账号收到带首尾空白模型名的请求:计费模型名改为去空白后的名字;发往 上游的请求不变。新增测试覆盖 OpenCode 与 Kimi 两类账号。 Co-Authored-By: Claude Opus 5.5 --- .../service/openai_gateway_forward.go | 8 +--- .../service/upstream_protocol_routing_test.go | 45 +++++++++++++++++++ 2 files changed, 47 insertions(+), 6 deletions(-) diff --git a/backend/internal/service/openai_gateway_forward.go b/backend/internal/service/openai_gateway_forward.go index 03d239774b..3825507b85 100644 --- a/backend/internal/service/openai_gateway_forward.go +++ b/backend/internal/service/openai_gateway_forward.go @@ -187,12 +187,8 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco case APIProtocolAnthropic: // Responses 客户端 × Anthropic 上游:转成 Anthropic 请求走原生端点。不能落到 // raw-CC 分支——其 URL 构造会把 anthropic base 当 CC base 用。 - // 按模型分流的账号不以请求模型兜底模型映射。 - defaultMappedModel := reqModel - if account.routesByModel() { - defaultMappedModel = "" - } - return s.forwardResponsesViaNativeAnthropic(ctx, c, account, body, defaultMappedModel) + // 账号映射未命中时以去除首尾空白的请求模型兜底,计费名与上游模型名一致。 + return s.forwardResponsesViaNativeAnthropic(ctx, c, account, body, reqModel) case APIProtocolChatCompletions: return s.forwardResponsesViaRawChatCompletions(ctx, c, account, body) } diff --git a/backend/internal/service/upstream_protocol_routing_test.go b/backend/internal/service/upstream_protocol_routing_test.go index df487b1f2a..2266c1cbf7 100644 --- a/backend/internal/service/upstream_protocol_routing_test.go +++ b/backend/internal/service/upstream_protocol_routing_test.go @@ -3,10 +3,14 @@ package service import ( + "context" + "strings" "testing" "github.com/Wei-Shaw/sub2api/internal/pkg/openai_compat" + "github.com/gin-gonic/gin" "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" ) func routingTestAccount(platform, accountType string, credentials, extra map[string]any) *Account { @@ -117,3 +121,44 @@ func TestUpstreamRoutingModelOnlyForModelRoutedAccounts(t *testing.T) { require.Equal(t, "glm-5.3", upstreamRoutingModel(openCode, body, "")) require.Empty(t, upstreamRoutingModel(routingTestAccount(PlatformKimi, AccountTypeAPIKey, nil, nil), body, "")) } + +// /v1/responses 转 Anthropic 上游时,计费模型名与上游模型名都应是去除首尾空白的 +// 请求模型;按模型分流(OpenCode)与显式 anthropic 协议(Kimi)账号行为一致。 +func TestResponsesToNativeAnthropicTrimsBillingModel(t *testing.T) { + gin.SetMode(gin.TestMode) + + openCode := &Account{ + ID: 703, + Name: "opencode-go", + Platform: PlatformOpenCodeGo, + Type: AccountTypeAPIKey, + Concurrency: 1, + Credentials: map[string]any{ + "api_key": "sk-test", + "account_mode": AccountModeGo, + "api_base_urls": map[string]any{ + APIProtocolAnthropic: "http://anthropic.example", + }, + }, + } + for _, tc := range []struct { + name string + account *Account + model string + }{ + {"opencode by model", openCode, "minimax-m3"}, + {"kimi pinned anthropic", nativeAnthropicTestAccount(), "kimi-k2"}, + } { + t.Run(tc.name, func(t *testing.T) { + body := []byte(`{"model":" ` + tc.model + ` ","input":"hello","stream":false}`) + upstream := &httpUpstreamRecorder{resp: nativeAnthropicStreamResponse()} + svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream} + + result, err := svc.Forward(context.Background(), adaptiveProtocolTestContext("/v1/responses", body), tc.account, body) + require.NoError(t, err) + require.True(t, strings.HasSuffix(upstream.lastReq.URL.Path, "/v1/messages"), upstream.lastReq.URL.String()) + require.Equal(t, tc.model, gjson.GetBytes(upstream.lastBody, "model").String()) + require.Equal(t, tc.model, result.BillingModel) + }) + } +} From 3b89cc08dd732b208b27351f77796912855dbb55 Mon Sep 17 00:00:00 2001 From: SavitarC <71271200+SavitarC@users.noreply.github.com> Date: Fri, 2 Oct 2026 15:23:55 +0800 Subject: [PATCH 05/19] =?UTF-8?q?refactor(platform):=20=E5=90=8E=E7=AB=AF?= =?UTF-8?q?=E5=B9=B3=E5=8F=B0=E5=88=97=E8=A1=A8=E6=94=B9=E7=94=B1=E5=B9=B3?= =?UTF-8?q?=E5=8F=B0=E6=B8=85=E5=8D=95=E6=B4=BE=E7=94=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 新增 domain/platforms.go 作为具体平台的单一数据来源:每个平台一条登记, 写明展示名、所走网关(anthropic / openai / gemini / antigravity)、是否国产 单一厂商、定价目录 provider 名,顺序即展示顺序。 以下列表与判断改为查平台清单: - "全部具体平台":用户平台额度白名单、错误透传规则平台列表、组合路由目标 校验、上游计费探测资格、调度快照遍历、组合分组的定价 / 模型映射回退、 组合分组默认模型列表; - "OpenAI 网关族":IsOpenAICompatible、NormalizeOpenAICompatiblePlatform、 Responses 兼容路由判断、count_tokens 分发、组合分组的 OpenAI 文本目标; - 国产厂商判断、渠道定价同步的 provider 映射; - 多协议 API Key 供应商相关的请求头覆盖资格、凭证测试、OpenAI 基址回退改用 IsMultiProtocolAPIKeyProvider; - 分组平台与组合路由目标的请求校验改为自定义校验标签 group_platform / concrete_platform,拒绝规则不变(大小写、首尾空格、别名一律拒绝)。 组合分组的逐平台回退是先命中者生效,CompositePrecedencePlatformIDs 保持 原有顺序 anthropic、gemini、openai,其余按登记顺序追加。依赖具体实现的 能力(OAuth、渠道监控、调度阈值、余额 / 用量窗口、Codex 模型目录等)仍在 各自代码中显式列出。 等价性测试把改动前的每个列表与 switch 原样保留为基准,逐一比较派生结果 (含顺序),谓词覆盖全部平台、composite 与非法值 × 全部账号类型。 Co-Authored-By: Claude Opus 5.5 --- backend/go.mod | 2 +- backend/internal/domain/platforms.go | 135 ++++++++++++++++++ backend/internal/domain/platforms_test.go | 67 +++++++++ .../internal/handler/admin/channel_handler.go | 25 ++-- .../internal/handler/admin/group_handler.go | 6 +- .../handler/admin/platform_validation.go | 24 ++++ backend/internal/handler/gateway_handler.go | 13 +- .../handler/openai_gateway_handler.go | 7 +- .../internal/model/error_passthrough_rule.go | 16 +-- backend/internal/server/routes/gateway.go | 20 +-- backend/internal/service/account.go | 4 +- .../service/account_header_override.go | 6 +- backend/internal/service/account_service.go | 8 +- backend/internal/service/admin_group.go | 12 +- backend/internal/service/channel_service.go | 3 +- .../internal/service/composite_platform.go | 9 +- backend/internal/service/domain_constants.go | 29 +--- .../service/openai_gateway_scheduling.go | 11 +- .../internal/service/platform_list_test.go | 118 +++++++++++++++ .../service/scheduler_snapshot_service.go | 12 +- .../service/upstream_billing_probe.go | 13 +- 21 files changed, 421 insertions(+), 119 deletions(-) create mode 100644 backend/internal/domain/platforms.go create mode 100644 backend/internal/domain/platforms_test.go create mode 100644 backend/internal/handler/admin/platform_validation.go create mode 100644 backend/internal/service/platform_list_test.go diff --git a/backend/go.mod b/backend/go.mod index 941f519d08..1c735301d6 100644 --- a/backend/go.mod +++ b/backend/go.mod @@ -19,6 +19,7 @@ require ( github.com/coder/websocket v1.8.14 github.com/dgraph-io/ristretto v0.2.0 github.com/gin-gonic/gin v1.9.1 + github.com/go-playground/validator/v10 v10.14.0 github.com/go-webauthn/webauthn v0.17.4 github.com/golang-jwt/jwt/v5 v5.3.1 github.com/google/uuid v1.6.0 @@ -120,7 +121,6 @@ require ( github.com/go-openapi/inflect v0.19.0 // indirect github.com/go-playground/locales v0.14.1 // indirect github.com/go-playground/universal-translator v0.18.1 // indirect - github.com/go-playground/validator/v10 v10.14.0 // indirect github.com/go-viper/mapstructure/v2 v2.5.0 // indirect github.com/go-webauthn/x v0.2.6 // indirect github.com/goccy/go-json v0.10.2 // indirect diff --git a/backend/internal/domain/platforms.go b/backend/internal/domain/platforms.go new file mode 100644 index 0000000000..f84801ad6b --- /dev/null +++ b/backend/internal/domain/platforms.go @@ -0,0 +1,135 @@ +package domain + +// 平台清单:平台的单一数据来源。"所有平台"类列表(分组平台、用户额度、组合 +// 路由目标、调度快照、定价匹配等)与"某网关族"类列表都从这里派生;新增平台 +// 登记一条即可在这些位置生效,无需逐处修改或新增数据库约束迁移。 +// +// 依赖具体实现的能力(OAuth、渠道监控、余额 / Coding Plan 探测、用量窗口、 +// Codex 模型目录等)仍由各自的代码显式列出,不在此处声明。 + +// PlatformGateway 标识平台请求由哪个网关服务处理。 +type PlatformGateway string + +const ( + // PlatformGatewayAnthropic 由 GatewayService 处理(Claude Messages 协议,以及 TypeSafe 的 /v1/systemone)。 + PlatformGatewayAnthropic PlatformGateway = "anthropic" + // PlatformGatewayOpenAI 由 OpenAIGatewayService 处理(OpenAI、Grok 与多协议 API Key 供应商)。 + PlatformGatewayOpenAI PlatformGateway = "openai" + // PlatformGatewayGemini 由 Gemini 兼容网关处理。 + PlatformGatewayGemini PlatformGateway = "gemini" + // PlatformGatewayAntigravity 由 Antigravity 网关处理。 + PlatformGatewayAntigravity PlatformGateway = "antigravity" +) + +// PlatformSpec 描述一个具体(非 composite)平台。 +type PlatformSpec struct { + ID string `json:"id"` + DisplayName string `json:"display_name"` + Gateway PlatformGateway `json:"gateway"` + // CNProvider 标识国产单一厂商(Kimi / 智谱 / DeepSeek / MiniMax),共享国产 + // 供应商的余额 / Coding Plan 等能力。 + CNProvider bool `json:"cn_provider"` + // LiteLLMProvider 是定价目录中的 provider 名;空表示不支持从定价目录同步模型。 + LiteLLMProvider string `json:"litellm_provider,omitempty"` +} + +// platformList 的顺序即平台的展示顺序。 +var platformList = []PlatformSpec{ + {ID: PlatformAnthropic, DisplayName: "Anthropic", Gateway: PlatformGatewayAnthropic, LiteLLMProvider: "anthropic"}, + {ID: PlatformOpenAI, DisplayName: "OpenAI", Gateway: PlatformGatewayOpenAI, LiteLLMProvider: "openai"}, + {ID: PlatformGemini, DisplayName: "Gemini", Gateway: PlatformGatewayGemini, LiteLLMProvider: "gemini"}, + {ID: PlatformAntigravity, DisplayName: "Antigravity", Gateway: PlatformGatewayAntigravity, LiteLLMProvider: "anthropic"}, + {ID: PlatformGrok, DisplayName: "Grok", Gateway: PlatformGatewayOpenAI, LiteLLMProvider: "xai"}, + {ID: PlatformKimi, DisplayName: "Kimi", Gateway: PlatformGatewayOpenAI, CNProvider: true, LiteLLMProvider: "moonshot"}, + {ID: PlatformZhipu, DisplayName: "Zhipu GLM", Gateway: PlatformGatewayOpenAI, CNProvider: true, LiteLLMProvider: "zhipu"}, + {ID: PlatformDeepseek, DisplayName: "DeepSeek", Gateway: PlatformGatewayOpenAI, CNProvider: true, LiteLLMProvider: "deepseek"}, + {ID: PlatformMiniMax, DisplayName: "MiniMax", Gateway: PlatformGatewayOpenAI, CNProvider: true, LiteLLMProvider: "minimax"}, + {ID: PlatformOpenCodeGo, DisplayName: "OpenCode", Gateway: PlatformGatewayOpenAI, LiteLLMProvider: "opencode-go"}, + {ID: PlatformTypeSafe, DisplayName: "TypeSafe / Jev", Gateway: PlatformGatewayAnthropic, LiteLLMProvider: "typesafe"}, +} + +var platformIndex = func() map[string]int { + index := make(map[string]int, len(platformList)) + for i, spec := range platformList { + index[spec.ID] = i + } + return index +}() + +// Platforms 返回全部具体平台(副本),按展示顺序。 +func Platforms() []PlatformSpec { + out := make([]PlatformSpec, len(platformList)) + copy(out, platformList) + return out +} + +// LookupPlatform 返回具体平台的登记信息;composite 与未知值返回 false。 +func LookupPlatform(id string) (PlatformSpec, bool) { + i, ok := platformIndex[id] + if !ok { + return PlatformSpec{}, false + } + return platformList[i], true +} + +// IsConcretePlatform 报告 id 是否为已登记的具体平台(不含 composite)。 +func IsConcretePlatform(id string) bool { + _, ok := platformIndex[id] + return ok +} + +// IsGroupPlatform 报告 id 是否可作为分组平台(具体平台或 composite)。 +func IsGroupPlatform(id string) bool { + return id == PlatformComposite || IsConcretePlatform(id) +} + +// ConcretePlatformIDs 返回全部具体平台标识,按展示顺序。 +func ConcretePlatformIDs() []string { + return PlatformIDsWhere(func(PlatformSpec) bool { return true }) +} + +// PlatformIDsWhere 返回满足条件的具体平台标识,按展示顺序。 +func PlatformIDsWhere(match func(PlatformSpec) bool) []string { + out := make([]string, 0, len(platformList)) + for _, spec := range platformList { + if match(spec) { + out = append(out, spec.ID) + } + } + return out +} + +// compositePrecedenceHead 是组合分组查找顺序的固定前缀(历史顺序:Gemini 先于 OpenAI)。 +var compositePrecedenceHead = []string{PlatformAnthropic, PlatformGemini, PlatformOpenAI} + +// CompositePrecedencePlatformIDs 返回按平台依次回退时的顺序:组合分组在请求目标 +// 解析前逐平台查找定价 / 模型映射(先命中者生效)、拼接默认模型列表,以及调度快照 +// 遍历。沿用历史顺序 anthropic、gemini、openai,其余按展示顺序,新登记的平台追加在末尾。 +func CompositePrecedencePlatformIDs() []string { + out := make([]string, 0, len(platformList)) + seen := make(map[string]struct{}, len(platformList)) + for _, id := range compositePrecedenceHead { + if IsConcretePlatform(id) { + out = append(out, id) + seen[id] = struct{}{} + } + } + for _, spec := range platformList { + if _, ok := seen[spec.ID]; !ok { + out = append(out, spec.ID) + } + } + return out +} + +// UsesOpenAIGateway 报告平台是否由 OpenAI 网关处理。 +func UsesOpenAIGateway(id string) bool { + spec, ok := LookupPlatform(id) + return ok && spec.Gateway == PlatformGatewayOpenAI +} + +// IsCNProviderPlatform 报告平台是否为国产单一厂商。 +func IsCNProviderPlatform(id string) bool { + spec, ok := LookupPlatform(id) + return ok && spec.CNProvider +} diff --git a/backend/internal/domain/platforms_test.go b/backend/internal/domain/platforms_test.go new file mode 100644 index 0000000000..327fc1c315 --- /dev/null +++ b/backend/internal/domain/platforms_test.go @@ -0,0 +1,67 @@ +package domain + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +// 重构前各处手写的平台列表,作为平台清单派生结果的等价基准。 +var ( + legacyDisplayOrder = []string{ + PlatformAnthropic, PlatformOpenAI, PlatformGemini, PlatformAntigravity, PlatformGrok, + PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformTypeSafe, + } + legacyCompositePrecedence = []string{ + PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok, + PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformTypeSafe, + } + legacyOpenAIGateway = []string{ + PlatformOpenAI, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, + } + legacyCNProviders = []string{PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax} + legacyLiteLLMByPlatf = map[string]string{ + PlatformAnthropic: "anthropic", PlatformOpenAI: "openai", PlatformGemini: "gemini", + PlatformAntigravity: "anthropic", PlatformGrok: "xai", PlatformKimi: "moonshot", + PlatformZhipu: "zhipu", PlatformDeepseek: "deepseek", PlatformMiniMax: "minimax", + PlatformOpenCodeGo: "opencode-go", PlatformTypeSafe: "typesafe", + } +) + +func TestPlatformListMatchesLegacyLists(t *testing.T) { + require.Equal(t, legacyDisplayOrder, ConcretePlatformIDs()) + require.Equal(t, legacyCompositePrecedence, CompositePrecedencePlatformIDs()) + require.Equal(t, legacyOpenAIGateway, PlatformIDsWhere(func(spec PlatformSpec) bool { + return spec.Gateway == PlatformGatewayOpenAI + })) + require.Equal(t, legacyCNProviders, PlatformIDsWhere(func(spec PlatformSpec) bool { return spec.CNProvider })) + for platform, provider := range legacyLiteLLMByPlatf { + spec, ok := LookupPlatform(platform) + require.True(t, ok, platform) + require.Equal(t, provider, spec.LiteLLMProvider, platform) + } +} + +func TestPlatformListPredicates(t *testing.T) { + for _, platform := range legacyDisplayOrder { + require.True(t, IsConcretePlatform(platform), platform) + require.True(t, IsGroupPlatform(platform), platform) + spec, ok := LookupPlatform(platform) + require.True(t, ok, platform) + require.NotEmpty(t, spec.DisplayName, platform) + require.NotEmpty(t, spec.Gateway, platform) + } + require.False(t, IsConcretePlatform(PlatformComposite)) + require.True(t, IsGroupPlatform(PlatformComposite)) + for _, invalid := range []string{"", "moonshot", "Kimi", "openai ", "glm", "bogus"} { + require.False(t, IsConcretePlatform(invalid), invalid) + require.False(t, IsGroupPlatform(invalid), invalid) + require.False(t, UsesOpenAIGateway(invalid), invalid) + } +} + +func TestPlatformsReturnsCopy(t *testing.T) { + platforms := Platforms() + platforms[0].ID = "mutated" + require.Equal(t, PlatformAnthropic, Platforms()[0].ID) +} diff --git a/backend/internal/handler/admin/channel_handler.go b/backend/internal/handler/admin/channel_handler.go index 065aedb2f4..4d2aa03e15 100644 --- a/backend/internal/handler/admin/channel_handler.go +++ b/backend/internal/handler/admin/channel_handler.go @@ -5,6 +5,7 @@ import ( "strconv" "strings" + "github.com/Wei-Shaw/sub2api/internal/domain" infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" "github.com/Wei-Shaw/sub2api/internal/pkg/pagination" "github.com/Wei-Shaw/sub2api/internal/pkg/response" @@ -631,20 +632,14 @@ func (h *ChannelHandler) GetModelDefaultPricing(c *gin.Context) { }) } -// platformToLiteLLMProvider maps a channel platform name to the corresponding -// LiteLLM provider string used as the key in the pricing catalog. -var platformToLiteLLMProvider = map[string]string{ - service.PlatformAnthropic: "anthropic", - service.PlatformOpenAI: "openai", - service.PlatformGemini: "gemini", - service.PlatformAntigravity: "anthropic", - service.PlatformGrok: "xai", - service.PlatformKimi: "moonshot", - service.PlatformZhipu: "zhipu", - service.PlatformDeepseek: "deepseek", - service.PlatformMiniMax: "minimax", - service.PlatformOpenCodeGo: "opencode-go", - service.PlatformTypeSafe: "typesafe", +// platformLiteLLMProvider maps a channel platform name to the corresponding +// LiteLLM provider string used as the key in the pricing catalog (platform list). +func platformLiteLLMProvider(platform string) (string, bool) { + spec, ok := domain.LookupPlatform(platform) + if !ok || spec.LiteLLMProvider == "" { + return "", false + } + return spec.LiteLLMProvider, true } // SyncPricingModels 返回 LiteLLM 定价目录中指定平台的最新模型列表 @@ -657,7 +652,7 @@ func (h *ChannelHandler) SyncPricingModels(c *gin.Context) { return } - provider, ok := platformToLiteLLMProvider[platform] + provider, ok := platformLiteLLMProvider(platform) if !ok { response.ErrorFrom(c, infraerrors.BadRequest("UNSUPPORTED_PLATFORM", fmt.Sprintf("unsupported platform: %s", platform)). diff --git a/backend/internal/handler/admin/group_handler.go b/backend/internal/handler/admin/group_handler.go index 774a00f882..e35ed66571 100644 --- a/backend/internal/handler/admin/group_handler.go +++ b/backend/internal/handler/admin/group_handler.go @@ -184,7 +184,7 @@ func sanitizeUpdateGroupRequestForSimpleMode(req *UpdateGroupRequest) { type CreateGroupRequest struct { Name string `json:"name" binding:"required"` Description string `json:"description"` - Platform string `json:"platform" binding:"omitempty,oneof=anthropic openai gemini antigravity grok kimi zhipu deepseek minimax opencode_go typesafe composite"` + Platform string `json:"platform" binding:"omitempty,group_platform"` RateMultiplier float64 `json:"rate_multiplier"` IsExclusive bool `json:"is_exclusive"` SubscriptionType string `json:"subscription_type" binding:"omitempty,oneof=standard subscription"` @@ -258,7 +258,7 @@ type CreateGroupRequest struct { type UpdateGroupRequest struct { Name string `json:"name"` Description *string `json:"description"` - Platform string `json:"platform" binding:"omitempty,oneof=anthropic openai gemini antigravity grok kimi zhipu deepseek minimax opencode_go typesafe composite"` + Platform string `json:"platform" binding:"omitempty,group_platform"` RateMultiplier *float64 `json:"rate_multiplier"` IsExclusive *bool `json:"is_exclusive"` Status string `json:"status" binding:"omitempty,oneof=active inactive"` @@ -332,7 +332,7 @@ type UpdateGroupRequest struct { type CompositeRouteRequest struct { PublicModel string `json:"public_model" binding:"required"` MatchType string `json:"match_type" binding:"omitempty,oneof=exact prefix"` - TargetPlatform string `json:"target_platform" binding:"required,oneof=anthropic openai gemini antigravity grok kimi zhipu deepseek minimax opencode_go typesafe"` + TargetPlatform string `json:"target_platform" binding:"required,concrete_platform"` UpstreamModel string `json:"upstream_model"` Endpoint string `json:"endpoint" binding:"omitempty,oneof=any messages count_tokens responses chat_completions embeddings images gemini"` Priority int `json:"priority"` diff --git a/backend/internal/handler/admin/platform_validation.go b/backend/internal/handler/admin/platform_validation.go new file mode 100644 index 0000000000..7eff99b88d --- /dev/null +++ b/backend/internal/handler/admin/platform_validation.go @@ -0,0 +1,24 @@ +package admin + +import ( + "github.com/Wei-Shaw/sub2api/internal/domain" + "github.com/gin-gonic/gin/binding" + "github.com/go-playground/validator/v10" +) + +// 平台相关的请求绑定校验标签,由平台清单(domain/platforms.go)驱动,替代在 +// binding 标签里手写 oneof 白名单(新增平台时易漏加,导致分组无法创建): +// - group_platform:已登记的具体平台或 composite; +// - concrete_platform:已登记的具体平台。 +func init() { + engine, ok := binding.Validator.Engine().(*validator.Validate) + if !ok { + return + } + _ = engine.RegisterValidation("group_platform", func(fl validator.FieldLevel) bool { + return domain.IsGroupPlatform(fl.Field().String()) + }) + _ = engine.RegisterValidation("concrete_platform", func(fl validator.FieldLevel) bool { + return domain.IsConcretePlatform(fl.Field().String()) + }) +} diff --git a/backend/internal/handler/gateway_handler.go b/backend/internal/handler/gateway_handler.go index beb9400d11..0b58876d8d 100644 --- a/backend/internal/handler/gateway_handler.go +++ b/backend/internal/handler/gateway_handler.go @@ -1301,7 +1301,7 @@ func (h *GatewayHandler) compositeAvailableModels(ctx context.Context, groupID * seen := make(map[string]struct{}) models := make([]string, 0) schedulablePlatforms := h.gatewayService.GetSchedulablePlatforms(ctx, groupID) - for _, platform := range []string{service.PlatformAnthropic, service.PlatformGemini, service.PlatformOpenAI, service.PlatformAntigravity, service.PlatformGrok, service.PlatformKimi, service.PlatformZhipu, service.PlatformDeepseek, service.PlatformMiniMax, service.PlatformOpenCodeGo, service.PlatformTypeSafe} { + for _, platform := range domain.CompositePrecedencePlatformIDs() { if platform == service.PlatformTypeSafe && !includeSystemOne { continue } @@ -1503,10 +1503,13 @@ func defaultModelIDsForPlatform(platform string) []string { case service.PlatformComposite: ids := make([]string, 0) seen := make(map[string]struct{}) - // TypeSafe is deliberately absent: jev-latest only works through - // /v1/systemone, so the static fallback never advertises it to LLM - // clients. compositeAvailableModels lists it when the group can serve it. - for _, concretePlatform := range []string{service.PlatformAnthropic, service.PlatformGemini, service.PlatformOpenAI, service.PlatformAntigravity, service.PlatformGrok, service.PlatformKimi, service.PlatformZhipu, service.PlatformDeepseek, service.PlatformMiniMax, service.PlatformOpenCodeGo} { + for _, concretePlatform := range domain.CompositePrecedencePlatformIDs() { + // TypeSafe is deliberately skipped: jev-latest only works through + // /v1/systemone, so the static fallback never advertises it to LLM + // clients. compositeAvailableModels lists it when the group can serve it. + if concretePlatform == service.PlatformTypeSafe { + continue + } for _, id := range defaultModelIDsForPlatform(concretePlatform) { if _, ok := seen[id]; ok { continue diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index 21f0cace70..65d002e54b 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -17,6 +17,7 @@ import ( "time" "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/domain" "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey" "github.com/Wei-Shaw/sub2api/internal/pkg/ip" "github.com/Wei-Shaw/sub2api/internal/pkg/logger" @@ -330,9 +331,9 @@ func allowOpenAICompatibleMessagesDispatch(c *gin.Context, apiKey *service.APIKe func openAICompatibleTextTargetAllowed(c *gin.Context, apiKey *service.APIKey, model string) bool { return compositeTargetPlatformAllowed(c, apiKey, model, - service.PlatformOpenAI, service.PlatformGrok, - service.PlatformKimi, service.PlatformZhipu, service.PlatformDeepseek, - service.PlatformMiniMax, service.PlatformOpenCodeGo) + domain.PlatformIDsWhere(func(spec domain.PlatformSpec) bool { + return spec.Gateway == domain.PlatformGatewayOpenAI + })...) } // isResponsesWebSocketCompositePlatform 限定 composite 分组在 Responses WebSocket diff --git a/backend/internal/model/error_passthrough_rule.go b/backend/internal/model/error_passthrough_rule.go index da928125f2..c4ca164dc0 100644 --- a/backend/internal/model/error_passthrough_rule.go +++ b/backend/internal/model/error_passthrough_rule.go @@ -49,21 +49,9 @@ const ( PlatformTypeSafe = domain.PlatformTypeSafe ) -// AllPlatforms 返回所有支持的平台列表 +// AllPlatforms 返回所有支持的平台列表(平台清单,按展示顺序)。 func AllPlatforms() []string { - return []string{ - PlatformAnthropic, - PlatformOpenAI, - PlatformGemini, - PlatformAntigravity, - PlatformGrok, - PlatformKimi, - PlatformZhipu, - PlatformDeepseek, - PlatformMiniMax, - PlatformOpenCodeGo, - PlatformTypeSafe, - } + return domain.ConcretePlatformIDs() } // Validate 验证规则配置的有效性 diff --git a/backend/internal/server/routes/gateway.go b/backend/internal/server/routes/gateway.go index 870ae14c5c..a921a42d44 100644 --- a/backend/internal/server/routes/gateway.go +++ b/backend/internal/server/routes/gateway.go @@ -6,6 +6,7 @@ import ( "strings" "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/domain" "github.com/Wei-Shaw/sub2api/internal/handler" pkghttputil "github.com/Wei-Shaw/sub2api/internal/pkg/httputil" "github.com/Wei-Shaw/sub2api/internal/pkg/requestmodel" @@ -46,22 +47,15 @@ func RegisterGatewayRoutes( groupModelAllowlist := middleware.GroupModelAllowlist() isOpenAIResponsesCompatibleGatewayPlatform := func(c *gin.Context) bool { - switch getGroupPlatform(c) { - case service.PlatformOpenAI, service.PlatformGrok, - service.PlatformKimi, service.PlatformZhipu, service.PlatformDeepseek, - service.PlatformMiniMax, service.PlatformOpenCodeGo: - // 国产 OpenAI 兼容供应商与 openai/grok 一样经 OpenAI 网关转发。 - return true - default: - return false - } + // openai、grok 与多协议 API Key 供应商经 OpenAI 网关转发(平台清单)。 + return domain.UsesOpenAIGateway(getGroupPlatform(c)) } countTokensHandler := func(c *gin.Context) { - switch getGroupPlatform(c) { - case service.PlatformOpenAI, service.PlatformKimi, service.PlatformZhipu, service.PlatformDeepseek, service.PlatformMiniMax, service.PlatformOpenCodeGo: - h.OpenAIGateway.CountTokens(c) - case service.PlatformGrok: + switch platform := getGroupPlatform(c); { + case platform == service.PlatformGrok: h.OpenAIGateway.GrokCountTokens(c) + case domain.UsesOpenAIGateway(platform): + h.OpenAIGateway.CountTokens(c) default: h.Gateway.CountTokens(c) } diff --git a/backend/internal/service/account.go b/backend/internal/service/account.go index 97a797580c..04b609e9e5 100644 --- a/backend/internal/service/account.go +++ b/backend/internal/service/account.go @@ -303,7 +303,7 @@ func (a *Account) IsCNProvider() bool { // openai/grok 原生走 OpenAI 网关;国产供应商同为 OpenAI Chat Completions // 兼容上游,也经 OpenAI 网关转发。OpenCode 同样经 OpenAI 网关按模型分流。 func (a *Account) IsOpenAICompatible() bool { - return a != nil && (a.Platform == PlatformOpenAI || a.Platform == PlatformGrok || a.IsCNProvider() || a.IsOpenCodeGo()) + return a != nil && domain.UsesOpenAIGateway(a.Platform) } func (a *Account) GeminiOAuthType() string { @@ -1384,7 +1384,7 @@ func (a *Account) IsOpenAIApiKey() bool { // 适用 openai、国产 OpenAI 兼容供应商(kimi/zhipu/deepseek)与 OpenCode Go; // grok 走 GetGrokBaseURL,此处对 grok 返回 "" 以保持原有行为。 func (a *Account) GetOpenAIBaseURL() string { - if !a.IsOpenAI() && !a.IsCNProvider() && !a.IsOpenCodeGo() { + if !a.IsOpenAI() && !a.IsMultiProtocolAPIKey() { return "" } if a.IsMultiProtocolAPIKey() && a.IsAdaptiveAPIProtocol() { diff --git a/backend/internal/service/account_header_override.go b/backend/internal/service/account_header_override.go index 7f05e253ac..e807cac15d 100644 --- a/backend/internal/service/account_header_override.go +++ b/backend/internal/service/account_header_override.go @@ -77,10 +77,10 @@ func (a *Account) IsHeaderOverrideEligible() bool { if a == nil { return false } - switch a.Platform { - case PlatformAnthropic, PlatformOpenAI, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo: + switch { + case a.Platform == PlatformAnthropic, a.Platform == PlatformOpenAI, IsMultiProtocolAPIKeyProvider(a.Platform): return a.Type == AccountTypeAPIKey - case PlatformGrok: + case a.Platform == PlatformGrok: return a.Type == AccountTypeAPIKey || a.Type == AccountTypeOAuth default: return false diff --git a/backend/internal/service/account_service.go b/backend/internal/service/account_service.go index bbf668eaff..7980a5c447 100644 --- a/backend/internal/service/account_service.go +++ b/backend/internal/service/account_service.go @@ -522,10 +522,12 @@ func (s *AccountService) TestCredentials(ctx context.Context, id int64) error { case PlatformTypeSafe: // TypeSafe credentials are API keys; inference failures drive health and cooldown state. return nil - case PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo: - // 国产 OpenAI 兼容供应商与 OpenCode:凭证为 API Key,实际可用性经余额/额度探测与转发路径验证。 - return nil default: + if IsMultiProtocolAPIKeyProvider(account.Platform) { + // 多协议 API Key 供应商(国产厂商与聚合平台):凭证为 API Key,实际可用性 + // 经余额/额度探测与转发路径验证。 + return nil + } return fmt.Errorf("unsupported platform: %s", account.Platform) } } diff --git a/backend/internal/service/admin_group.go b/backend/internal/service/admin_group.go index 103c9edc25..41d16bb6c9 100644 --- a/backend/internal/service/admin_group.go +++ b/backend/internal/service/admin_group.go @@ -10,6 +10,7 @@ import ( dbent "github.com/Wei-Shaw/sub2api/ent" "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/domain" "github.com/Wei-Shaw/sub2api/internal/pkg/antigravity" "github.com/Wei-Shaw/sub2api/internal/pkg/claude" infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" @@ -319,10 +320,13 @@ func defaultAllowImageGenerationForPlatform(platform string) bool { func compositeDefaultModelsListCandidateIDs() []string { seen := make(map[string]struct{}) ids := make([]string, 0) - // TypeSafe stays out of the static composite candidates (jev-latest only works - // through /v1/systemone); groups with TypeSafe accounts still get it from the - // account model mappings collected by GetGroupModelsListCandidates. - for _, platform := range []string{PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo} { + for _, platform := range domain.CompositePrecedencePlatformIDs() { + // TypeSafe stays out of the static composite candidates (jev-latest only works + // through /v1/systemone); groups with TypeSafe accounts still get it from the + // account model mappings collected by GetGroupModelsListCandidates. + if platform == PlatformTypeSafe { + continue + } for _, id := range defaultModelsListCandidateIDs(platform) { if _, ok := seen[id]; ok { continue diff --git a/backend/internal/service/channel_service.go b/backend/internal/service/channel_service.go index b2c605cd80..85d6409301 100644 --- a/backend/internal/service/channel_service.go +++ b/backend/internal/service/channel_service.go @@ -9,6 +9,7 @@ import ( "sync/atomic" "time" + "github.com/Wei-Shaw/sub2api/internal/domain" "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey" infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" "github.com/Wei-Shaw/sub2api/internal/pkg/pagination" @@ -368,7 +369,7 @@ func isPlatformPricingMatch(groupPlatform, pricingPlatform string) bool { // fallback used before a request target has been resolved. func matchingPlatforms(groupPlatform string) []string { if groupPlatform == PlatformComposite { - return []string{PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformTypeSafe} + return domain.CompositePrecedencePlatformIDs() } return []string{groupPlatform} } diff --git a/backend/internal/service/composite_platform.go b/backend/internal/service/composite_platform.go index c10e335cbe..b7fcfd3451 100644 --- a/backend/internal/service/composite_platform.go +++ b/backend/internal/service/composite_platform.go @@ -4,6 +4,7 @@ import ( "context" "strings" + "github.com/Wei-Shaw/sub2api/internal/domain" "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey" ) @@ -204,11 +205,5 @@ func (s *GatewayService) resolveCompositeRouteDecision(ctx context.Context, grou } func isConcreteRequestPlatform(platform string) bool { - switch platform { - case PlatformAnthropic, PlatformOpenAI, PlatformGemini, PlatformAntigravity, PlatformGrok, - PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformTypeSafe: - return true - default: - return false - } + return domain.IsConcretePlatform(platform) } diff --git a/backend/internal/service/domain_constants.go b/backend/internal/service/domain_constants.go index 014e6f6bb9..c6fc312753 100644 --- a/backend/internal/service/domain_constants.go +++ b/backend/internal/service/domain_constants.go @@ -101,14 +101,10 @@ const ( DefaultOpenCodeZenAnthropicBaseURL = "https://opencode.ai/zen" ) -// IsCNProvider 报告 platform 是否为国产 OpenAI 兼容供应商(kimi/zhipu/deepseek/minimax)。 +// IsCNProvider 报告 platform 是否为国产 OpenAI 兼容供应商(kimi/zhipu/deepseek/minimax), +// 以平台清单(domain/platforms.go)为准。 func IsCNProvider(platform string) bool { - switch platform { - case PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax: - return true - default: - return false - } + return domain.IsCNProviderPlatform(platform) } // IsOpenCodeGo 报告 platform 是否为 OpenCode Go 订阅网关。 @@ -123,22 +119,9 @@ func IsMultiProtocolAPIKeyProvider(platform string) bool { return LookupProviderProfile(platform) != nil } -// AllowedQuotaPlatforms 是允许设置 user × platform quota 的平台列表(单一权威来源)。 -// ent/schema/user_platform_quota.go 的 Validate 函数独立维护(构建期约束), -// 若新增平台需同步修改该 schema。 -var AllowedQuotaPlatforms = []string{ - PlatformAnthropic, - PlatformOpenAI, - PlatformGemini, - PlatformAntigravity, - PlatformGrok, - PlatformKimi, - PlatformZhipu, - PlatformDeepseek, - PlatformMiniMax, - PlatformOpenCodeGo, - PlatformTypeSafe, -} +// AllowedQuotaPlatforms 是允许设置 user × platform quota 的平台列表:全部已登记的 +// 具体平台(domain/platforms.go),ent/schema/user_platform_quota.go 的校验同源。 +var AllowedQuotaPlatforms = domain.ConcretePlatformIDs() // AllowedSchedulingThresholdPlatforms 是允许设置账号自动停调阈值的平台列表。 // openai/anthropic/grok 有原生用量窗口;kimi/zhipu/minimax 的 Coding Plan 同样暴露 diff --git a/backend/internal/service/openai_gateway_scheduling.go b/backend/internal/service/openai_gateway_scheduling.go index fe93880ee0..04fc18bb94 100644 --- a/backend/internal/service/openai_gateway_scheduling.go +++ b/backend/internal/service/openai_gateway_scheduling.go @@ -14,6 +14,7 @@ import ( "time" "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/domain" "github.com/Wei-Shaw/sub2api/internal/pkg/openai" "github.com/Wei-Shaw/sub2api/internal/pkg/xai" "github.com/gin-gonic/gin" @@ -285,18 +286,16 @@ func (s *OpenAIGatewayService) SelectAccountForTokenCount( ) } -// NormalizeOpenAICompatiblePlatform 保留 grok 与国产 OpenAI 兼容供应商(kimi/zhipu/ -// deepseek)的原值,其他值一律归一为 openai。调度器据此对账号与请求做精确平台匹配: +// NormalizeOpenAICompatiblePlatform 保留走 OpenAI 网关的平台(openai、grok 与多协议 +// API Key 供应商,见平台清单)的原值,其他值一律归一为 openai。调度器据此对账号与请求做精确平台匹配: // kimi 分组请求只命中 kimi 账号,语义与 openai/grok 一致。 // (upstream 曾将本函数改为未导出 normalizeOpenAICompatiblePlatform,本分支的 // handler 调度入口仍需导出,保持导出名。) func NormalizeOpenAICompatiblePlatform(platform string) string { - switch platform { - case PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo: + if domain.UsesOpenAIGateway(platform) { return platform - default: - return PlatformOpenAI } + return PlatformOpenAI } // noAvailableOpenAISelectionError builds the standard "no account available" error diff --git a/backend/internal/service/platform_list_test.go b/backend/internal/service/platform_list_test.go new file mode 100644 index 0000000000..09cc70b090 --- /dev/null +++ b/backend/internal/service/platform_list_test.go @@ -0,0 +1,118 @@ +//go:build unit + +package service + +import ( + "testing" + + "github.com/Wei-Shaw/sub2api/internal/domain" + "github.com/stretchr/testify/require" +) + +// 以下为重构前各处手写的平台列表 / switch,作为平台清单派生结果的等价基准。 +var ( + legacyAllPlatforms = []string{ + PlatformAnthropic, PlatformOpenAI, PlatformGemini, PlatformAntigravity, PlatformGrok, + PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformTypeSafe, + } + legacySchedulerSnapshotPlatforms = []string{ + PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok, + PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformTypeSafe, + } + legacyCompositeMatchingPlatforms = legacySchedulerSnapshotPlatforms + legacyMultiProtocolProviders = []string{PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo} + platformProbeValues = append(append([]string{}, legacyAllPlatforms...), PlatformComposite, "", "moonshot", "Kimi", "openai ", "glm", "bogus") + platformProbeAccountTypes = []string{AccountTypeAPIKey, AccountTypeOAuth, AccountTypeSetupToken, AccountTypeUpstream, ""} +) + +func legacyIsCNProvider(platform string) bool { + switch platform { + case PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax: + return true + } + return false +} + +func legacyIsOpenAICompatible(platform string) bool { + return platform == PlatformOpenAI || platform == PlatformGrok || legacyIsCNProvider(platform) || platform == PlatformOpenCodeGo +} + +func legacyNormalizeOpenAICompatiblePlatform(platform string) string { + switch platform { + case PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo: + return platform + } + return PlatformOpenAI +} + +func legacyIsUpstreamBillingProbeIdentity(platform, accountType string) bool { + if accountType != AccountTypeAPIKey { + return false + } + switch platform { + case PlatformOpenAI, PlatformAnthropic, PlatformGemini, PlatformAntigravity, PlatformGrok, + PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, + PlatformTypeSafe: + return true + } + return false +} + +func legacyIsHeaderOverrideEligible(platform, accountType string) bool { + switch platform { + case PlatformAnthropic, PlatformOpenAI, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo: + return accountType == AccountTypeAPIKey + case PlatformGrok: + return accountType == AccountTypeAPIKey || accountType == AccountTypeOAuth + } + return false +} + +func legacyIsConcreteRequestPlatform(platform string) bool { + for _, p := range legacyAllPlatforms { + if p == platform { + return true + } + } + return false +} + +func TestPlatformListDerivedListsMatchLegacy(t *testing.T) { + require.Equal(t, legacyAllPlatforms, AllowedQuotaPlatforms) + require.Equal(t, legacySchedulerSnapshotPlatforms, schedulerSnapshotPlatforms()) + require.Equal(t, legacyCompositeMatchingPlatforms, matchingPlatforms(PlatformComposite)) + require.Equal(t, []string{PlatformKimi}, matchingPlatforms(PlatformKimi)) + + var multiProtocol []string + for _, platform := range legacyAllPlatforms { + if IsMultiProtocolAPIKeyProvider(platform) { + multiProtocol = append(multiProtocol, platform) + } + } + require.Equal(t, legacyMultiProtocolProviders, multiProtocol) +} + +func TestPlatformListDerivedPredicatesMatchLegacy(t *testing.T) { + for _, platform := range platformProbeValues { + require.Equal(t, legacyIsCNProvider(platform), IsCNProvider(platform), platform) + require.Equal(t, legacyIsConcreteRequestPlatform(platform), isConcreteRequestPlatform(platform), platform) + require.Equal(t, legacyNormalizeOpenAICompatiblePlatform(platform), NormalizeOpenAICompatiblePlatform(platform), platform) + require.Equal(t, legacyIsOpenAICompatible(platform), (&Account{Platform: platform}).IsOpenAICompatible(), platform) + for _, accountType := range platformProbeAccountTypes { + require.Equal(t, legacyIsUpstreamBillingProbeIdentity(platform, accountType), + IsUpstreamBillingProbeIdentity(platform, accountType), "%s/%s", platform, accountType) + require.Equal(t, legacyIsHeaderOverrideEligible(platform, accountType), + (&Account{Platform: platform, Type: accountType}).IsHeaderOverrideEligible(), "%s/%s", platform, accountType) + } + } +} + +// 多协议 API Key 供应商经 OpenAI 网关转发(NormalizeOpenAICompatiblePlatform、 +// countTokens 路由等依赖此约束),ProviderProfile 登记的平台必须在平台清单中声明 openai 网关。 +func TestProviderProfilesUseOpenAIGateway(t *testing.T) { + for platform := range providerProfiles { + spec, ok := domain.LookupPlatform(platform) + require.True(t, ok, platform) + require.Equal(t, domain.PlatformGatewayOpenAI, spec.Gateway, platform) + } +} diff --git a/backend/internal/service/scheduler_snapshot_service.go b/backend/internal/service/scheduler_snapshot_service.go index 6f999c189c..2073ad0f53 100644 --- a/backend/internal/service/scheduler_snapshot_service.go +++ b/backend/internal/service/scheduler_snapshot_service.go @@ -12,6 +12,7 @@ import ( "time" "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/domain" "github.com/Wei-Shaw/sub2api/internal/pkg/logger" ) @@ -608,10 +609,10 @@ func (s *SchedulerSnapshotService) handleBulkAccountEvent(ctx context.Context, p continue } accountGroupIDs := s.normalizeGroupIDs(account.GroupIDs) - switch account.Platform { - case PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformTypeSafe: + switch { + case account.Platform != PlatformAntigravity && isConcreteRequestPlatform(account.Platform): addPlatformGroups(account.Platform, accountGroupIDs) - case PlatformAntigravity: + case account.Platform == PlatformAntigravity: // 批量更新可能刚关闭 mixed_scheduling,仍需清理两个兼容平台的旧快照。 addPlatformGroups(PlatformAntigravity, accountGroupIDs) addPlatformGroups(PlatformAnthropic, accountGroupIDs) @@ -824,8 +825,9 @@ func (s *SchedulerSnapshotService) rebuildByAccount(ctx context.Context, account return s.rebuildBuckets(ctx, buckets, reason) } -func schedulerSnapshotPlatforms() [11]string { - return [11]string{PlatformAnthropic, PlatformGemini, PlatformOpenAI, PlatformAntigravity, PlatformGrok, PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, PlatformTypeSafe} +// schedulerSnapshotPlatforms 返回需要维护调度快照的全部具体平台(平台清单)。 +func schedulerSnapshotPlatforms() []string { + return domain.CompositePrecedencePlatformIDs() } // 生命周期辅助函数有意排除 group0;full rebuild 构造 group0 canonical 集时必须显式调用 canonical helper。 diff --git a/backend/internal/service/upstream_billing_probe.go b/backend/internal/service/upstream_billing_probe.go index b34900f4f5..a53fca5597 100644 --- a/backend/internal/service/upstream_billing_probe.go +++ b/backend/internal/service/upstream_billing_probe.go @@ -19,6 +19,7 @@ import ( "sync" "time" + "github.com/Wei-Shaw/sub2api/internal/domain" infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" "github.com/Wei-Shaw/sub2api/internal/pkg/logger" "github.com/Wei-Shaw/sub2api/internal/pkg/tlsfingerprint" @@ -1008,17 +1009,7 @@ func decodeUpstreamBillingProbeSnapshot(extra map[string]any) *UpstreamBillingPr // type=apikey by the admin form, so only pre-existing type=upstream rows // cannot turn the probe on. func IsUpstreamBillingProbeIdentity(platform, accountType string) bool { - if accountType != AccountTypeAPIKey { - return false - } - switch platform { - case PlatformOpenAI, PlatformAnthropic, PlatformGemini, PlatformAntigravity, PlatformGrok, - PlatformKimi, PlatformZhipu, PlatformDeepseek, PlatformMiniMax, PlatformOpenCodeGo, - PlatformTypeSafe: - return true - default: - return false - } + return accountType == AccountTypeAPIKey && domain.IsConcretePlatform(platform) } func isUpstreamBillingProbeAccount(account *Account) bool { From eefa7dd9dc90e5bddb40a3f0dc2ea8df0dcf1476 Mon Sep 17 00:00:00 2001 From: SavitarC <71271200+SavitarC@users.noreply.github.com> Date: Fri, 2 Oct 2026 15:26:04 +0800 Subject: [PATCH 06/19] =?UTF-8?q?refactor(platform):=20=E5=B9=B3=E5=8F=B0?= =?UTF-8?q?=E7=99=BD=E5=90=8D=E5=8D=95=E7=94=B1=E6=95=B0=E6=8D=AE=E5=BA=93?= =?UTF-8?q?=E7=BA=A6=E6=9D=9F=E6=94=B9=E4=B8=BA=E5=BA=94=E7=94=A8=E5=B1=82?= =?UTF-8?q?=E6=A0=A1=E9=AA=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 新增迁移 242 删除 user_platform_quotas_platform_check 与 composite_model_routes_target_platform_check(DROP ... IF EXISTS,可重入)。 此后新增平台只需在平台清单中登记,不再需要改约束的迁移;此前 Grok、国产 厂商、MiniMax、OpenCode 共写过 5 次。 平台合法性改由应用层保证,与原约束的拒绝范围相同: - user_platform_quotas 用原生 SQL 写入,不经过 ent Validate,repository 在 BulkInsertInitial / UpsertForUser 写入前校验平台,非法值在发出任何 SQL 前 返回错误(此前由数据库拒绝并回滚); - ent schema 的 platform / target_platform 校验改查平台清单,组合路由新增 target_platform 校验(service 层与 admin 接口的原有校验保留)。 渠道监控的 provider 约束表示已实现的探测能力,不属于平台清单,保留不动。 集成测试(真实 PostgreSQL):在还原旧约束的库上重复执行迁移、约束被移除、 渠道监控约束保留、数据库层可写入未来的新平台值;repository 拒绝未登记平台 且不产生副作用(去掉校验后该测试失败)。全部仓储集成测试通过。 Co-Authored-By: Claude Opus 5.5 --- backend/ent/runtime/runtime.go | 16 +- backend/ent/schema/composite_model_route.go | 9 ++ backend/ent/schema/user_platform_quota.go | 12 +- backend/internal/domain/constants.go | 2 +- .../platform_list_db_integration_test.go | 143 ++++++++++++++++++ .../repository/user_platform_quota_repo.go | 18 +++ backend/internal/service/auth_service.go | 6 +- .../242_drop_platform_check_constraints.sql | 18 +++ ...m_check_constraints_drop_migration_test.go | 22 +++ 9 files changed, 234 insertions(+), 12 deletions(-) create mode 100644 backend/internal/repository/platform_list_db_integration_test.go create mode 100644 backend/migrations/242_drop_platform_check_constraints.sql create mode 100644 backend/migrations/platform_check_constraints_drop_migration_test.go diff --git a/backend/ent/runtime/runtime.go b/backend/ent/runtime/runtime.go index 375e749c73..6253e31dad 100644 --- a/backend/ent/runtime/runtime.go +++ b/backend/ent/runtime/runtime.go @@ -906,7 +906,21 @@ func init() { // compositemodelroute.DefaultTargetPlatform holds the default value on creation for the target_platform field. compositemodelroute.DefaultTargetPlatform = compositemodelrouteDescTargetPlatform.Default.(string) // compositemodelroute.TargetPlatformValidator is a validator for the "target_platform" field. It is called by the builders before save. - compositemodelroute.TargetPlatformValidator = compositemodelrouteDescTargetPlatform.Validators[0].(func(string) error) + compositemodelroute.TargetPlatformValidator = func() func(string) error { + validators := compositemodelrouteDescTargetPlatform.Validators + fns := [...]func(string) error{ + validators[0].(func(string) error), + validators[1].(func(string) error), + } + return func(target_platform string) error { + for _, fn := range fns { + if err := fn(target_platform); err != nil { + return err + } + } + return nil + } + }() // compositemodelrouteDescUpstreamModel is the schema descriptor for upstream_model field. compositemodelrouteDescUpstreamModel := compositemodelrouteFields[4].Descriptor() // compositemodelroute.DefaultUpstreamModel holds the default value on creation for the upstream_model field. diff --git a/backend/ent/schema/composite_model_route.go b/backend/ent/schema/composite_model_route.go index 82b5bb274b..3e44aa5101 100644 --- a/backend/ent/schema/composite_model_route.go +++ b/backend/ent/schema/composite_model_route.go @@ -1,6 +1,8 @@ package schema import ( + "fmt" + "github.com/Wei-Shaw/sub2api/ent/schema/mixins" "github.com/Wei-Shaw/sub2api/internal/domain" @@ -45,6 +47,13 @@ func (CompositeModelRoute) Fields() []ent.Field { field.String("target_platform"). MaxLen(50). Default(domain.PlatformOpenAI). + Validate(func(s string) error { + // 目标平台须为平台清单中的具体平台;数据库不再维护 CHECK 约束。 + if !domain.IsConcretePlatform(s) { + return fmt.Errorf("target_platform %q is not a concrete platform", s) + } + return nil + }). Comment("Concrete provider platform."), field.String("upstream_model"). MaxLen(200). diff --git a/backend/ent/schema/user_platform_quota.go b/backend/ent/schema/user_platform_quota.go index 663be0a6ec..3949a09721 100644 --- a/backend/ent/schema/user_platform_quota.go +++ b/backend/ent/schema/user_platform_quota.go @@ -11,6 +11,7 @@ import ( "entgo.io/ent/schema/field" "entgo.io/ent/schema/index" "github.com/Wei-Shaw/sub2api/ent/schema/mixins" + "github.com/Wei-Shaw/sub2api/internal/domain" ) // UserPlatformQuota holds the schema definition for per-user per-platform quota. @@ -38,15 +39,12 @@ func (UserPlatformQuota) Fields() []ent.Field { MaxLen(32). NotEmpty(). Validate(func(s string) error { - // 注意:平台列表的单一权威源为 service.AllowedQuotaPlatforms; - // 此处为 ent 构建期约束,需与 service.AllowedQuotaPlatforms 保持同步。 - switch s { - case "anthropic", "openai", "gemini", "antigravity", "grok", - "kimi", "zhipu", "deepseek", "minimax", "opencode_go", "typesafe": - return nil - default: + // 平台白名单为平台清单(domain/platforms.go)中的全部具体平台, + // 与 service.AllowedQuotaPlatforms 同源;数据库不再维护 CHECK 约束。 + if !domain.IsConcretePlatform(s) { return fmt.Errorf("platform %q is not allowed", s) } + return nil }), // 日 / 周 / 月 USD 上限: diff --git a/backend/internal/domain/constants.go b/backend/internal/domain/constants.go index 37cb3a738f..95d65c91e4 100644 --- a/backend/internal/domain/constants.go +++ b/backend/internal/domain/constants.go @@ -30,7 +30,7 @@ const ( PlatformMiniMax = "minimax" // MiniMax (M 系列) PlatformTypeSafe = "typesafe" // TypeSafe AI System One (Jev) // PlatformOpenCodeGo 是 OpenCode 平台(账号类型 Zen 按量 / Go 订阅)。 - // 值保持 opencode_go 以兼容已落库的分组、配额与 Composite 路由 CHECK。 + // 值保持 opencode_go 以兼容已落库的账号、分组、配额与 Composite 路由。 PlatformOpenCodeGo = "opencode_go" PlatformComposite = "composite" ) diff --git a/backend/internal/repository/platform_list_db_integration_test.go b/backend/internal/repository/platform_list_db_integration_test.go new file mode 100644 index 0000000000..2bfb68861c --- /dev/null +++ b/backend/internal/repository/platform_list_db_integration_test.go @@ -0,0 +1,143 @@ +//go:build integration + +package repository + +import ( + "context" + "testing" + + dbent "github.com/Wei-Shaw/sub2api/ent" + "github.com/Wei-Shaw/sub2api/internal/service" + dbmigrations "github.com/Wei-Shaw/sub2api/migrations" + "github.com/stretchr/testify/require" +) + +func platformConstraintExists(t *testing.T, ctx context.Context, client *dbent.Client, table, constraint string) bool { + t.Helper() + rows, err := client.QueryContext(ctx, ` +SELECT 1 +FROM pg_constraint c +JOIN pg_class tbl ON tbl.oid = c.conrelid +JOIN pg_namespace ns ON ns.oid = tbl.relnamespace +WHERE ns.nspname = 'public' AND tbl.relname = $1 AND c.conname = $2`, table, constraint) + require.NoError(t, err) + defer func() { _ = rows.Close() }() + exists := rows.Next() + require.NoError(t, rows.Err()) + return exists +} + +// 迁移 242 删除平台白名单 CHECK 约束:旧库(约束仍在)上可重复执行,执行后 +// 新登记的平台无需再做数据库迁移即可写入。 +func TestMigration242DropsPlatformCheckConstraints(t *testing.T) { + ctx := context.Background() + tx := testEntTx(t) + client := tx.Client() + + // 还原迁移 241_add_typesafe_platform 之后、242 之前的约束状态。 + for _, stmt := range []string{ + `ALTER TABLE user_platform_quotas DROP CONSTRAINT IF EXISTS user_platform_quotas_platform_check`, + `ALTER TABLE user_platform_quotas ADD CONSTRAINT user_platform_quotas_platform_check + CHECK (platform IN ('anthropic', 'openai', 'gemini', 'antigravity', 'grok', + 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', 'typesafe'))`, + `ALTER TABLE composite_model_routes DROP CONSTRAINT IF EXISTS composite_model_routes_target_platform_check`, + `ALTER TABLE composite_model_routes ADD CONSTRAINT composite_model_routes_target_platform_check + CHECK (target_platform IN ('anthropic', 'openai', 'gemini', 'antigravity', 'grok', + 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', 'typesafe'))`, + } { + _, err := client.ExecContext(ctx, stmt) + require.NoError(t, err) + } + require.True(t, platformConstraintExists(t, ctx, client, "user_platform_quotas", "user_platform_quotas_platform_check")) + require.True(t, platformConstraintExists(t, ctx, client, "composite_model_routes", "composite_model_routes_target_platform_check")) + + migrationSQL, err := dbmigrations.FS.ReadFile("242_drop_platform_check_constraints.sql") + require.NoError(t, err) + for range 2 { + _, err = client.ExecContext(ctx, string(migrationSQL)) + require.NoError(t, err) + } + require.False(t, platformConstraintExists(t, ctx, client, "user_platform_quotas", "user_platform_quotas_platform_check")) + require.False(t, platformConstraintExists(t, ctx, client, "composite_model_routes", "composite_model_routes_target_platform_check")) + // 渠道监控的 provider 约束表示探测能力,保留。 + require.True(t, platformConstraintExists(t, ctx, client, "channel_monitors", "channel_monitors_provider_check")) + require.True(t, platformConstraintExists(t, ctx, client, "channel_monitor_request_templates", "channel_monitor_request_templates_provider_check")) + + // 数据库层不再限制平台取值:模拟未来新登记的平台。 + userID := mustCreateUserForQuota(t, client) + _, err = client.ExecContext(ctx, ` +INSERT INTO user_platform_quotas (user_id, platform, daily_limit_usd, daily_usage_usd, weekly_usage_usd, monthly_usage_usd, created_at, updated_at) +VALUES ($1, 'future_platform', 1, 0, 0, 0, NOW(), NOW())`, userID) + require.NoError(t, err) + group := mustCreateGroup(t, client, &service.Group{Name: "platform-list-composite", Platform: service.PlatformComposite}) + _, err = client.ExecContext(ctx, ` +INSERT INTO composite_model_routes (group_id, public_model, target_platform) +VALUES ($1, 'future-model', 'future_platform')`, group.ID) + require.NoError(t, err) +} + +// 删除 CHECK 约束后,平台合法性由应用层保证:原生 SQL 写入前的 repository 校验。 +func TestUserPlatformQuotaRepository_RejectsUnregisteredPlatform(t *testing.T) { + ctx := context.Background() + tx := testEntTx(t) + txCtx := dbent.NewTxContext(ctx, tx) + client := tx.Client() + + userID := mustCreateUserForQuota(t, client) + repo := NewUserPlatformQuotaRepository(client) + daily := 5.0 + require.NoError(t, repo.UpsertForUser(txCtx, userID, []UserPlatformQuotaRecord{ + {UserID: userID, Platform: service.PlatformOpenCodeGo, DailyLimitUSD: &daily}, + })) + + for _, platform := range []string{"bogus", "moonshot", "Kimi", service.PlatformComposite} { + err := repo.BulkInsertInitial(txCtx, []UserPlatformQuotaRecord{ + {UserID: userID, Platform: service.PlatformAnthropic, DailyLimitUSD: &daily}, + {UserID: userID, Platform: platform, DailyLimitUSD: &daily}, + }) + require.ErrorContains(t, err, "is not allowed", platform) + err = repo.UpsertForUser(txCtx, userID, []UserPlatformQuotaRecord{ + {UserID: userID, Platform: platform, DailyLimitUSD: &daily}, + }) + require.ErrorContains(t, err, "is not allowed", platform) + } + + // 被拒绝的写入不产生任何副作用:既有记录保留、未新增任何行。 + got, err := repo.ListByUser(txCtx, userID) + require.NoError(t, err) + require.Len(t, got, 1) + require.Equal(t, service.PlatformOpenCodeGo, got[0].Platform) + + // 三档全空的记录不写入,也不参与校验(与既有 configuredRecords 语义一致)。 + require.NoError(t, repo.BulkInsertInitial(txCtx, []UserPlatformQuotaRecord{{UserID: userID, Platform: "bogus"}})) +} + +func TestCompositeModelRouteRepository_RejectsUnregisteredTargetPlatform(t *testing.T) { + ctx := context.Background() + tx := testEntTx(t) + txCtx := dbent.NewTxContext(ctx, tx) + client := tx.Client() + + group := mustCreateGroup(t, client, &service.Group{Name: "platform-list-routes", Platform: service.PlatformComposite}) + repo := NewCompositeModelRouteRepository(client) + + route := &service.CompositeModelRoute{ + GroupID: group.ID, PublicModel: "glm-5", MatchType: "exact", TargetPlatform: service.PlatformZhipu, + UpstreamModel: "glm-5", Endpoint: "any", Priority: 100, Enabled: true, + } + require.NoError(t, repo.Create(txCtx, route)) + + bad := &service.CompositeModelRoute{ + GroupID: group.ID, PublicModel: "bogus-model", MatchType: "exact", TargetPlatform: "bogus", + UpstreamModel: "bogus-model", Endpoint: "any", Priority: 100, Enabled: true, + } + require.Error(t, repo.Create(txCtx, bad)) + + route.TargetPlatform = service.PlatformComposite + require.Error(t, repo.Update(txCtx, route)) + + routes, err := repo.ListByGroup(txCtx, group.ID, true) + require.NoError(t, err) + require.Len(t, routes, 1) + require.Equal(t, service.PlatformZhipu, routes[0].TargetPlatform) +} diff --git a/backend/internal/repository/user_platform_quota_repo.go b/backend/internal/repository/user_platform_quota_repo.go index 2e085ba4bc..75b3fbbd75 100644 --- a/backend/internal/repository/user_platform_quota_repo.go +++ b/backend/internal/repository/user_platform_quota_repo.go @@ -9,6 +9,7 @@ import ( dbent "github.com/Wei-Shaw/sub2api/ent" "github.com/Wei-Shaw/sub2api/ent/userplatformquota" + "github.com/Wei-Shaw/sub2api/internal/domain" "github.com/Wei-Shaw/sub2api/internal/pkg/timezone" ) @@ -95,6 +96,9 @@ func (r *userPlatformQuotaRepository) BulkInsertInitial(ctx context.Context, rec if len(records) == 0 { return nil } + if err := validateQuotaPlatforms(records); err != nil { + return err + } client := clientFromContext(ctx, r.client) @@ -318,6 +322,9 @@ func monthlyMaybeReset(prevUsage float64, prevStart *time.Time, cost float64, no // 清空某平台的限额即软删该行并放弃其累计用量;之后再次配置限额会新建行、从新窗口起算。 func (r *userPlatformQuotaRepository) UpsertForUser(ctx context.Context, userID int64, records []UserPlatformQuotaRecord) error { records = configuredRecords(records) + if err := validateQuotaPlatforms(records); err != nil { + return err + } return r.withTx(ctx, func(txCtx context.Context, txClient *dbent.Client) error { platforms := make([]string, 0, len(records)) for _, rec := range records { @@ -484,6 +491,17 @@ func (r *userPlatformQuotaRepository) BatchSnapshotUsage(ctx context.Context, sn return nil } +// validateQuotaPlatforms 在原生 SQL 写入前校验平台须为平台清单中的具体平台, +// 取代迁移 242 删除的 user_platform_quotas_platform_check 约束(原生 SQL 不经过 ent Validate)。 +func validateQuotaPlatforms(records []UserPlatformQuotaRecord) error { + for _, rec := range records { + if !domain.IsConcretePlatform(rec.Platform) { + return fmt.Errorf("user_platform_quotas: platform %q is not allowed", rec.Platform) + } + } + return nil +} + // configuredRecords 过滤出至少配置了一档限额的记录;三档全空的记录视为未配置。 func configuredRecords(records []UserPlatformQuotaRecord) []UserPlatformQuotaRecord { out := make([]UserPlatformQuotaRecord, 0, len(records)) diff --git a/backend/internal/service/auth_service.go b/backend/internal/service/auth_service.go index f2a76ccb9d..0774923e6c 100644 --- a/backend/internal/service/auth_service.go +++ b/backend/internal/service/auth_service.go @@ -1937,9 +1937,9 @@ func (s *AuthService) snapshotPlatformQuotaDefaults(ctx context.Context, userID return nil } // 平台配额快照是 best-effort(fail-open):必须脱离调用方事务执行。 - // 否则某平台违反 user_platform_quotas 的 CHECK 约束(如尚未进约束的新平台)会让 - // 整个调用方事务被 Postgres 标记 aborted,把"无关紧要的默认配额快照"放大成 - // "整笔注册失败"(OAuth pending 路径曾因此 500 → 清 cookie → 404)。 + // 否则写入时的任何数据库错误(历史上是新平台尚未加入 user_platform_quotas 的 + // CHECK 约束)都会让整个调用方事务被 Postgres 标记 aborted,把"无关紧要的默认 + // 配额快照"放大成"整笔注册失败"(OAuth pending 路径曾因此 500 → 清 cookie → 404)。 ctx = dbent.WithoutTx(ctx) // 仅为至少配置了一档限额的平台建行:user_platform_quotas 中不存在的行等价于不限额, // 三档全空的记录不携带任何可执行的限额。 diff --git a/backend/migrations/242_drop_platform_check_constraints.sql b/backend/migrations/242_drop_platform_check_constraints.sql new file mode 100644 index 0000000000..7307be715e --- /dev/null +++ b/backend/migrations/242_drop_platform_check_constraints.sql @@ -0,0 +1,18 @@ +-- 平台白名单改由应用层的平台清单(internal/domain/platforms.go)统一校验, +-- 新增平台不再需要修改数据库约束的迁移。 +-- +-- 1. user_platform_quotas.platform:admin 接口 / 设置校验 service.AllowedQuotaPlatforms, +-- repository 写入前校验 domain.IsConcretePlatform,ent schema Validate 同源。 +-- 2. composite_model_routes.target_platform:admin 接口 binding、service +-- compositeRouteFromInput 与 ent schema Validate 均校验为已登记的具体平台。 +-- +-- channel_monitors / channel_monitor_request_templates 的 provider CHECK 表示 +-- 渠道监控已实现的探测能力,不属于平台清单,保留不动。 +-- +-- DROP ... IF EXISTS 保证可重入。 + +ALTER TABLE user_platform_quotas + DROP CONSTRAINT IF EXISTS user_platform_quotas_platform_check; + +ALTER TABLE composite_model_routes + DROP CONSTRAINT IF EXISTS composite_model_routes_target_platform_check; diff --git a/backend/migrations/platform_check_constraints_drop_migration_test.go b/backend/migrations/platform_check_constraints_drop_migration_test.go new file mode 100644 index 0000000000..4449740966 --- /dev/null +++ b/backend/migrations/platform_check_constraints_drop_migration_test.go @@ -0,0 +1,22 @@ +package migrations + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestDropPlatformCheckConstraintsMigration(t *testing.T) { + content, err := FS.ReadFile("242_drop_platform_check_constraints.sql") + require.NoError(t, err) + + sql := strings.Join(strings.Fields(string(content)), " ") + require.Contains(t, sql, + "ALTER TABLE user_platform_quotas DROP CONSTRAINT IF EXISTS user_platform_quotas_platform_check;") + require.Contains(t, sql, + "ALTER TABLE composite_model_routes DROP CONSTRAINT IF EXISTS composite_model_routes_target_platform_check;") + require.NotContains(t, sql, "ADD CONSTRAINT") + require.NotContains(t, sql, "DROP CONSTRAINT IF EXISTS channel_monitors_provider_check") + require.NotContains(t, sql, "DROP CONSTRAINT IF EXISTS channel_monitor_request_templates_provider_check") +} From c556aee8fd37bbe41f8dccc18eca2df594baa5bf Mon Sep 17 00:00:00 2001 From: SavitarC <71271200+SavitarC@users.noreply.github.com> Date: Sun, 27 Sep 2026 11:08:41 +0800 Subject: [PATCH 07/19] =?UTF-8?q?refactor(platform):=20=E5=A4=9A=E5=8D=8F?= =?UTF-8?q?=E8=AE=AE=E4=BE=9B=E5=BA=94=E5=95=86=E7=9A=84=E8=BD=AC=E5=8F=91?= =?UTF-8?q?=E4=B8=8E=E6=8E=A2=E6=B5=8B=E5=88=A4=E6=96=AD=E6=94=B9=E6=9F=A5?= =?UTF-8?q?=20profile?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 平台清单之外,后端还有几处用"国产厂商"或"国产厂商 ∪ OpenCode"表示 多协议供应商,新登记的供应商会被漏掉(例如上游模型同步直接报不支持)。 - 适用于全部多协议供应商的判断改用 IsMultiProtocolAPIKey:上游模型同步与 模型目录基址、Anthropic count_tokens 本地估算、HTML 403 豁免与累计计数、Claude 型号 计费候选过滤; - 新增 RoutesProtocolByInbound(profile 分流方式为按入站协议),替换原来 只针对国产厂商、实际描述"按入站协议分流"的判断:Responses 直转回退、 Responses 能力标记(含创建 / 更新后的异步探测调度)、上游计费探测的 adaptive 基址、Anthropic API Key 鉴权方式、OpenAI 输入 token 本地估算。 按模型分流的供应商(OpenCode)仍走 routesByModel 分支。 依赖各家额度 / 余额接口的逻辑(Coding Plan 窗口、余额不足冷却等)仍按平台 显式判断。现有平台上两组判断与改动前逐一相同(测试覆盖全部平台与非法值); 另测试临时登记的新供应商按分流方式分别获得国产厂商与 OpenCode 的行为。 Co-Authored-By: Claude Opus 5.5 --- .../internal/handler/admin/account_handler.go | 2 +- .../internal/service/anthropic_apikey_auth.go | 2 +- .../service/openai_apikey_responses_probe.go | 4 +- .../service/openai_gateway_count_tokens.go | 6 +- .../service/openai_gateway_forward.go | 7 ++- .../internal/service/openai_gateway_usage.go | 2 +- .../internal/service/platform_list_test.go | 56 +++++++++++++++++++ backend/internal/service/provider_profile.go | 9 +++ backend/internal/service/ratelimit_service.go | 2 +- .../service/upstream_billing_probe.go | 2 +- backend/internal/service/upstream_models.go | 7 +-- 11 files changed, 82 insertions(+), 17 deletions(-) diff --git a/backend/internal/handler/admin/account_handler.go b/backend/internal/handler/admin/account_handler.go index 97ebd9ed35..f954cce572 100644 --- a/backend/internal/handler/admin/account_handler.go +++ b/backend/internal/handler/admin/account_handler.go @@ -1226,7 +1226,7 @@ func (h *AccountHandler) Update(c *gin.Context) { // 网关会按"现状即证据"默认走 Responses。 func (h *AccountHandler) scheduleOpenAIResponsesProbe(account *service.Account) { if account == nil || account.Type != service.AccountTypeAPIKey || - (account.Platform != service.PlatformOpenAI && !service.IsCNProvider(account.Platform)) { + (account.Platform != service.PlatformOpenAI && !account.RoutesProtocolByInbound()) { return } if h.accountTestService == nil { diff --git a/backend/internal/service/anthropic_apikey_auth.go b/backend/internal/service/anthropic_apikey_auth.go index 8bd8c4ba8f..a7f3963071 100644 --- a/backend/internal/service/anthropic_apikey_auth.go +++ b/backend/internal/service/anthropic_apikey_auth.go @@ -21,7 +21,7 @@ func (a *Account) GetAnthropicAPIKeyAuthScheme() string { if a == nil || a.Type != AccountTypeAPIKey { return AnthropicAPIKeyAuthSchemeXAPIKey } - if a.Platform != PlatformAnthropic && !a.IsCNProvider() { + if a.Platform != PlatformAnthropic && !a.RoutesProtocolByInbound() { return AnthropicAPIKeyAuthSchemeXAPIKey } diff --git a/backend/internal/service/openai_apikey_responses_probe.go b/backend/internal/service/openai_apikey_responses_probe.go index d942afab08..e7dc1cb201 100644 --- a/backend/internal/service/openai_apikey_responses_probe.go +++ b/backend/internal/service/openai_apikey_responses_probe.go @@ -130,8 +130,8 @@ func (s *AccountTestService) ProbeOpenAIAPIKeyResponsesSupport(ctx context.Conte if account.Type != AccountTypeAPIKey { return } - if account.IsCNProvider() { - // 国产 OpenAI 兼容上游默认仅支持 /v1/chat/completions。直接落标 false + if account.RoutesProtocolByInbound() { + // 按入站协议分流的供应商(国产厂商等)默认仅支持 /v1/chat/completions。直接落标 false // 走 Chat Completions 直转,跳过网络探测。 // 例外:deepseek / kimi 的固定 responses 和 adaptive 账号使用官方原生 // Responses 端点,落标 force_responses;其余协议显式重置为 auto,避免 diff --git a/backend/internal/service/openai_gateway_count_tokens.go b/backend/internal/service/openai_gateway_count_tokens.go index 9ece2430c8..9579f2054f 100644 --- a/backend/internal/service/openai_gateway_count_tokens.go +++ b/backend/internal/service/openai_gateway_count_tokens.go @@ -150,7 +150,7 @@ func prepareNativeOpenAIInputTokensCountRequest(body []byte, account *Account) ( } func shouldEstimateOpenAIInputTokensLocally(account *Account) bool { - if account == nil || account.IsGrok() || account.IsCNProvider() || account.Type == AccountTypeUpstream { + if account == nil || account.IsGrok() || account.RoutesProtocolByInbound() || account.Type == AccountTypeUpstream { return true } if account.Type != AccountTypeAPIKey { @@ -264,14 +264,14 @@ func (s *OpenAIGatewayService) ForwardCountTokensAsAnthropic( return fmt.Errorf("count_tokens: missing account") } - // 国产供应商与 OpenCode(全部协议,含 anthropic):一律本地估算,不发上游请求。 + // 多协议 API Key 供应商(国产厂商与聚合平台,全部协议,含 anthropic):一律本地估算,不发上游请求。 // 依据(2026-08 核实):三家的 Anthropic 兼容层均未提供 // /v1/messages/count_tokens——DeepSeek 官方 anthropic_api 文档无此端点 // (且注明 anthropic-version 头被忽略),聚合网关 OpenModel 明确标注 // count_tokens 为 "Anthropic only",Kimi/智谱亦无任何文档承诺。转发上游 // 只会常态 404,且错误还会流入账号处置逻辑误伤整账号调度;Claude Code // 高频调用此端点,本地 tiktoken 估算是与 Grok 一致的既有方案。 - if account.IsCNProvider() || account.IsOpenCodeGo() { + if account.IsMultiProtocolAPIKey() { estimated, err := estimateAnthropicCountTokensLocally(body) if err != nil { writeAnthropicCountTokensError(c, http.StatusBadRequest, "invalid_request_error", "Failed to parse request body") diff --git a/backend/internal/service/openai_gateway_forward.go b/backend/internal/service/openai_gateway_forward.go index 3825507b85..3cf10c5c73 100644 --- a/backend/internal/service/openai_gateway_forward.go +++ b/backend/internal/service/openai_gateway_forward.go @@ -1351,9 +1351,10 @@ func shouldForwardOpenAIResponsesViaRawChatCompletions(account *Account) bool { // Grok/GPT/Muse into Chat Completions. return false } - if account.IsCNProvider() { - // CN 的显式协议配置优先于异步探针 Extra;adaptive 仅 DeepSeek / Kimi - // 有原生 Responses,GLM 回退 Chat Completions。 + if account.RoutesProtocolByInbound() { + // 按入站协议分流的供应商(国产厂商等):显式协议配置优先于异步探针 + // Extra;adaptive 仅在供应商有原生 Responses 端点时直转,否则回退 + // Chat Completions(如 GLM)。 switch account.GetAPIProtocol() { case APIProtocolChatCompletions: return true diff --git a/backend/internal/service/openai_gateway_usage.go b/backend/internal/service/openai_gateway_usage.go index 824d2b94dd..c0803a4c51 100644 --- a/backend/internal/service/openai_gateway_usage.go +++ b/backend/internal/service/openai_gateway_usage.go @@ -930,7 +930,7 @@ func groupMediaPricingLooksIncomplete(group *Group) bool { // 运营者的修复手段是配置账号级 model_mapping(映射到已定价的 CN 模型)或 // 分组/渠道显式定价。 func (s *OpenAIGatewayService) filterCNProviderBillingModelCandidates(ctx context.Context, account *Account, apiKey *APIKey, candidates []string) []string { - if account == nil || (!account.IsCNProvider() && !account.IsOpenCodeGo()) { + if account == nil || !account.IsMultiProtocolAPIKey() { return candidates } out := make([]string, 0, len(candidates)) diff --git a/backend/internal/service/platform_list_test.go b/backend/internal/service/platform_list_test.go index 09cc70b090..c06f60fcf8 100644 --- a/backend/internal/service/platform_list_test.go +++ b/backend/internal/service/platform_list_test.go @@ -116,3 +116,59 @@ func TestProviderProfilesUseOpenAIGateway(t *testing.T) { require.Equal(t, domain.PlatformGatewayOpenAI, spec.Gateway, platform) } } + +// 转发、探测与计费中"多协议供应商"类判断改为查 profile:现有平台上与改动前的 +// 国产厂商 / 国产厂商 ∪ OpenCode 判断逐一相同。 +func TestProviderProfileAccountPredicatesMatchLegacy(t *testing.T) { + for _, platform := range platformProbeValues { + account := &Account{Platform: platform, Type: AccountTypeAPIKey} + require.Equal(t, legacyIsCNProvider(platform), account.RoutesProtocolByInbound(), platform) + require.Equal(t, legacyIsCNProvider(platform) || platform == PlatformOpenCodeGo, account.IsMultiProtocolAPIKey(), platform) + } + var nilAccount *Account + require.False(t, nilAccount.RoutesProtocolByInbound()) +} + +// 仅在 providerProfiles 中登记的新供应商按分流方式自动获得对应行为:按入站协议 +// 分流的与国产厂商一致,按模型分流的与 OpenCode 一致。 +func TestNewlyRegisteredProviderInheritsRoutingBehaviour(t *testing.T) { + const byInbound, byModel = "test_inbound_provider", "test_model_provider" + providerProfiles[byInbound] = &ProviderProfile{ + Platform: byInbound, DefaultMode: AccountModePayG, Routing: ProviderRoutingByInbound, + Modes: map[string]ProviderEndpoints{AccountModePayG: {BaseURLs: map[string]string{ + APIProtocolChatCompletions: "https://inbound.example.com/v1", + APIProtocolAnthropic: "https://inbound.example.com/anthropic", + }}}, + } + providerProfiles[byModel] = &ProviderProfile{ + Platform: byModel, DefaultMode: AccountModePayG, Routing: ProviderRoutingByModel, + Modes: map[string]ProviderEndpoints{AccountModePayG: {BaseURLs: map[string]string{ + APIProtocolChatCompletions: "https://model.example.com/v1", + }}}, + } + t.Cleanup(func() { + delete(providerProfiles, byInbound) + delete(providerProfiles, byModel) + }) + + inbound := &Account{Platform: byInbound, Type: AccountTypeAPIKey, Credentials: map[string]any{ + "api_key": "sk-test", "api_protocol": APIProtocolAdaptive, + "base_url": "https://inbound.example.com/v1", + }} + require.True(t, inbound.IsMultiProtocolAPIKey()) + require.True(t, inbound.RoutesProtocolByInbound()) + // 无原生 Responses 端点的 adaptive 账号回退 Chat Completions(与 GLM 相同)。 + require.True(t, shouldForwardOpenAIResponsesViaRawChatCompletions(inbound)) + require.True(t, shouldEstimateOpenAIInputTokensLocally(inbound)) + require.Equal(t, "https://inbound.example.com/v1", upstreamModelRegistryBaseURL(inbound)) + + model := &Account{Platform: byModel, Type: AccountTypeAPIKey, Credentials: map[string]any{ + "api_key": "sk-test", "api_protocol": APIProtocolAdaptive, + "base_url": "https://model.example.com/v1", + }} + require.True(t, model.IsMultiProtocolAPIKey()) + require.False(t, model.RoutesProtocolByInbound()) + // 按模型分流:protocol_rules 决定协议,不按 Responses 能力标记回退(与 OpenCode 相同)。 + require.False(t, shouldForwardOpenAIResponsesViaRawChatCompletions(model)) + require.Equal(t, "https://model.example.com/v1", upstreamModelRegistryBaseURL(model)) +} diff --git a/backend/internal/service/provider_profile.go b/backend/internal/service/provider_profile.go index 111cf968fb..c8ad645132 100644 --- a/backend/internal/service/provider_profile.go +++ b/backend/internal/service/provider_profile.go @@ -204,3 +204,12 @@ func (a *Account) routesByModel() bool { profile := a.providerProfile() return profile != nil && profile.Routing == ProviderRoutingByModel } + +// RoutesProtocolByInbound 报告账号是否为按入站协议分流的多协议 API Key 供应商 +// (单一厂商型,目前即国产厂商)。这类账号共享"显式协议优先、adaptive 选同协议 +// 原生端点"的转发、Responses 能力标记与本地 token 估算逻辑;按模型分流的聚合 +// 平台由 protocol_rules 决定协议,走 routesByModel 分支。 +func (a *Account) RoutesProtocolByInbound() bool { + profile := a.providerProfile() + return profile != nil && profile.Routing != ProviderRoutingByModel +} diff --git a/backend/internal/service/ratelimit_service.go b/backend/internal/service/ratelimit_service.go index 6438efc3e2..6846c9a5d1 100644 --- a/backend/internal/service/ratelimit_service.go +++ b/backend/internal/service/ratelimit_service.go @@ -1003,7 +1003,7 @@ func (s *RateLimitService) handle403(ctx context.Context, account *Account, upst // 国产供应商与 openai 同口径:HTML 403(CDN/代理拦截页)不构成账号失效证据, // 且 403 在 failover 状态集里会被逐账号重放——直接 SetError 会让一个坏请求/ // 一层坏代理连环永久禁用整组账号。走 HTML 豁免 + N 次累计 + 临时冷却。 - if account.Platform == PlatformOpenAI || IsCNProvider(account.Platform) || account.IsOpenCodeGo() { + if account.Platform == PlatformOpenAI || account.IsMultiProtocolAPIKey() { return s.handleOpenAI403(ctx, account, upstreamMsg, responseBody) } // 非 Antigravity 平台:保持原有行为 diff --git a/backend/internal/service/upstream_billing_probe.go b/backend/internal/service/upstream_billing_probe.go index a53fca5597..85c4122647 100644 --- a/backend/internal/service/upstream_billing_probe.go +++ b/backend/internal/service/upstream_billing_probe.go @@ -627,7 +627,7 @@ func (s *UpstreamBillingProbeService) probeLoadedAccount(ctx context.Context, ac return s.persistProbeFailure(ctx, account, intervalMinutes, now, 0, "missing_api_key", 0) } baseURL := account.GetCredential("base_url") - if account.IsCNProvider() && account.IsAdaptiveAPIProtocol() { + if account.RoutesProtocolByInbound() && account.IsAdaptiveAPIProtocol() { baseURL = account.GetCNProtocolBaseURL(APIProtocolChatCompletions) } if account.Platform == PlatformOpenAI { diff --git a/backend/internal/service/upstream_models.go b/backend/internal/service/upstream_models.go index 7596dea131..3c5eb2fcd2 100644 --- a/backend/internal/service/upstream_models.go +++ b/backend/internal/service/upstream_models.go @@ -625,7 +625,7 @@ func upstreamModelRegistryBaseURL(account *Account) string { return "" } switch { - case account.IsOpenAI() || account.IsCNProvider() || account.IsOpenCodeGo(): + case account.IsOpenAI() || account.IsMultiProtocolAPIKey(): return account.GetOpenAIFormatBaseURL() case account.IsGrok(): return account.GetGrokBaseURL() @@ -792,9 +792,8 @@ func (s *AccountTestService) buildUpstreamModelsRequest(ctx context.Context, acc return s.buildAntigravityAPIKeyModelsRequest(ctx, account) case account.IsGrok(): return s.buildGrokUpstreamModelsRequest(ctx, account) - case account.IsOpenAI() || account.IsCNProvider() || account.IsOpenCodeGo(): - // 国产 OpenAI 兼容供应商(kimi/zhipu/deepseek)与 OpenCode Go - // 复用 OpenAI /v1/models 探测。 + case account.IsOpenAI() || account.IsMultiProtocolAPIKey(): + // 多协议 API Key 供应商(国产厂商与聚合平台)复用 OpenAI /v1/models 探测。 return s.buildOpenAIUpstreamModelsRequest(ctx, account) case account.IsGemini(): return s.buildGeminiUpstreamModelsRequest(ctx, account) From 7ffa38a8ae42a4a9f1796ab0fdeecab82e1a6bcc Mon Sep 17 00:00:00 2001 From: SavitarC <71271200+SavitarC@users.noreply.github.com> Date: Sun, 27 Sep 2026 11:08:41 +0800 Subject: [PATCH 08/19] =?UTF-8?q?feat(frontend):=20=E5=B9=B3=E5=8F=B0?= =?UTF-8?q?=E5=88=97=E8=A1=A8=E4=B8=8E=E5=A4=9A=E5=8D=8F=E8=AE=AE=E8=B4=A6?= =?UTF-8?q?=E5=8F=B7=E8=A1=A8=E5=8D=95=E6=94=B9=E7=94=B1=E5=B9=B3=E5=8F=B0?= =?UTF-8?q?=E6=B8=85=E5=8D=95=E9=A9=B1=E5=8A=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 后端新增 BuildPlatformCatalog:平台清单加上多协议供应商 profile(接入模式、 各协议默认基址、内置分流规则),由测试 TestFrontendBuiltinPlatformCatalogInSync 写成前端内置清单 constants/platformCatalog.builtin.json 并校验一致。前端随后端 一同构建发布,直接使用该清单,取代 credentialsBuilder.ts 中需要手工同步的默认 端点与 OpenCode 分流规则。 改为读取平台清单: - 平台选项 CONCRETE_PLATFORM_OPTIONS / GROUP_PLATFORM_OPTIONS、平台展示名 platformLabel 以及各处 i18n 平台名的默认值; - 渠道定价平台与组合分组平台、用户平台额度、上游模型同步可用平台; - 多协议供应商判断、原生协议能力、各接入模式的默认端点与内置分流规则、 请求头覆写资格; - 系统默认额度与各登录方式默认额度:此前前端只列出 5 个平台(新增国产厂商 与 OpenCode 时漏改),后端一直支持全部平台,现在按清单列出全部平台。 没有专属界面的多协议供应商走通用表单:创建弹窗列出其按钮,接入模式、可选 协议、默认端点与分流规则都来自 profile(按模型分流的供应商显示分流规则编辑 器);编辑弹窗同样适用。未登记专属图标 / 配色的平台使用通用图标与中性配色。 平台按钮分三行:国际平台、国产厂商、多模型聚合平台(OpenCode 与平台清单中 登记的其他多协议供应商)。没有内置模型列表的供应商不预填模型白名单(此前 回落 Claude 模型列表,新账号只接受这些模型),API Key 输入框也不再显示 Claude 的占位符与说明。 AccountPlatform / GroupPlatform 类型放宽为"内置平台 | 任意字符串"。新登记 平台只需重新生成内置清单,无需修改前端代码。 另修正编辑弹窗两处遗漏 MiniMax 的默认端点回退(清空 Base URL 时曾回落到 Anthropic 默认地址)。 测试:credentialsBuilder 以改动前实现为基准,逐一比较全部平台 × 接入模式 × 协议的默认端点与各判断;替换清单后平台选项、展示名、额度列表随之更新;创建 / 编辑弹窗对走通用表单的供应商(按模型 / 按入站两种分流)提交的凭证。更新了 两个固定旧列表写法的测试。平台清单与账号表单的测试加入 CI 前端关键测试列表 (FRONTEND_CRITICAL_VITEST)。 Co-Authored-By: Claude Opus 5.5 --- Makefile | 4 + backend/internal/service/platform_catalog.go | 95 +++++++ .../internal/service/platform_catalog_test.go | 140 ++++++++++ .../settings.authSourceDefaults.spec.ts | 28 +- frontend/src/api/admin/settings.ts | 14 +- frontend/src/api/admin/users.ts | 14 +- .../components/account/CreateAccountModal.vue | 193 ++++++++++---- .../components/account/EditAccountModal.vue | 136 ++++++---- .../account/ModelWhitelistSelector.vue | 19 +- .../account/OpenCodeGoProtocolRulesEditor.vue | 38 ++- .../__tests__/CreateAccountModal.spec.ts | 150 +++++++++++ .../__tests__/EditAccountModal.spec.ts | 103 ++++++++ ...credentialsBuilder.platformCatalog.spec.ts | 242 ++++++++++++++++++ .../components/account/credentialsBuilder.ts | 191 +++++++------- .../admin/group/GroupRPMOverridesModal.vue | 3 +- .../admin/group/GroupRateMultipliersModal.vue | 3 +- .../admin/user/UserPlatformQuotaModal.vue | 6 +- .../components/user/UserPlatformQuotaCell.vue | 11 +- .../__tests__/useModelWhitelist.spec.ts | 29 +++ frontend/src/composables/useModelWhitelist.ts | 7 +- .../src/constants/__tests__/platforms.spec.ts | 73 +++++- .../constants/platformCatalog.builtin.json | 239 +++++++++++++++++ frontend/src/constants/platformCatalog.ts | 110 ++++++++ frontend/src/constants/platforms.ts | 38 ++- frontend/src/types/index.ts | 14 +- frontend/src/utils/platformColors.ts | 23 +- frontend/src/views/admin/ChannelsView.vue | 34 +-- frontend/src/views/admin/GroupsView.vue | 9 +- frontend/src/views/admin/SettingsView.vue | 13 +- .../__tests__/channelPlatformOptions.spec.ts | 13 +- 30 files changed, 1681 insertions(+), 311 deletions(-) create mode 100644 backend/internal/service/platform_catalog.go create mode 100644 backend/internal/service/platform_catalog_test.go create mode 100644 frontend/src/components/account/__tests__/credentialsBuilder.platformCatalog.spec.ts create mode 100644 frontend/src/constants/platformCatalog.builtin.json create mode 100644 frontend/src/constants/platformCatalog.ts diff --git a/Makefile b/Makefile index 319da6ca43..6895d5f85c 100644 --- a/Makefile +++ b/Makefile @@ -8,6 +8,10 @@ FRONTEND_CRITICAL_VITEST := \ src/components/account/__tests__/OpenAIReferralCell.spec.ts \ src/components/account/__tests__/OpenAIReferralCell.transport.spec.ts \ src/components/account/__tests__/OpenAIQuotaResetCell.spark_shadow.spec.ts \ + src/constants/__tests__/platforms.spec.ts \ + src/components/account/__tests__/credentialsBuilder.platformCatalog.spec.ts \ + src/components/account/__tests__/CreateAccountModal.spec.ts \ + src/components/account/__tests__/EditAccountModal.spec.ts \ src/components/keys/__tests__/BulkEditKeysModal.spec.ts \ src/components/admin/user/__tests__/UserPlatformQuotaModal.spec.ts \ src/views/user/__tests__/KeysView.spec.ts \ diff --git a/backend/internal/service/platform_catalog.go b/backend/internal/service/platform_catalog.go new file mode 100644 index 0000000000..ddd0dd7166 --- /dev/null +++ b/backend/internal/service/platform_catalog.go @@ -0,0 +1,95 @@ +package service + +import ( + "sort" + + "github.com/Wei-Shaw/sub2api/internal/domain" +) + +// PlatformCatalog 是前端使用的平台清单:domain 平台清单加上多协议供应商的 +// profile(接入模式、各协议默认基址、内置分流规则)。它被写成前端内置清单 +// frontend/src/constants/platformCatalog.builtin.json(见 +// TestFrontendBuiltinPlatformCatalogInSync),前端据此生成平台选项、展示名与 +// 多协议账号表单,新登记的平台只需重新生成该文件,无需修改前端代码。 +type PlatformCatalog struct { + Platforms []PlatformCatalogEntry `json:"platforms"` + // CompositePrecedence 是组合分组逐平台回退的顺序(先命中者生效)。 + CompositePrecedence []string `json:"composite_precedence"` +} + +// PlatformCatalogEntry 描述一个具体平台;MultiProtocol 仅多协议 API Key 供应商有值。 +type PlatformCatalogEntry struct { + domain.PlatformSpec + MultiProtocol *ProviderProfileInfo `json:"multi_protocol,omitempty"` +} + +// ProviderProfileInfo 是 ProviderProfile 的对外形状。 +type ProviderProfileInfo struct { + DefaultMode string `json:"default_mode"` + Routing ProviderRouting `json:"routing"` + ResponsesPath string `json:"responses_path,omitempty"` + // Modes 以默认模式开头,其余按模式名排序。 + Modes []ProviderModeInfo `json:"modes"` +} + +// ProviderModeInfo 是某接入模式的默认端点;BaseURLs 缺少某协议即该模式不提供该原生端点。 +type ProviderModeInfo struct { + Mode string `json:"mode"` + BaseURLs map[string]string `json:"base_urls"` + ProtocolRules []ProtocolRule `json:"protocol_rules,omitempty"` +} + +// BuildPlatformCatalog 按展示顺序返回全部具体平台(不含 composite)。 +func BuildPlatformCatalog() PlatformCatalog { + specs := domain.Platforms() + catalog := PlatformCatalog{ + Platforms: make([]PlatformCatalogEntry, 0, len(specs)), + CompositePrecedence: domain.CompositePrecedencePlatformIDs(), + } + for _, spec := range specs { + catalog.Platforms = append(catalog.Platforms, PlatformCatalogEntry{ + PlatformSpec: spec, + MultiProtocol: providerProfileInfo(LookupProviderProfile(spec.ID)), + }) + } + return catalog +} + +func providerProfileInfo(profile *ProviderProfile) *ProviderProfileInfo { + if profile == nil { + return nil + } + routing := profile.Routing + if routing == "" { + routing = ProviderRoutingByInbound + } + modes := make([]string, 0, len(profile.Modes)) + for mode := range profile.Modes { + if mode != profile.DefaultMode { + modes = append(modes, mode) + } + } + sort.Strings(modes) + if _, ok := profile.Modes[profile.DefaultMode]; ok { + modes = append([]string{profile.DefaultMode}, modes...) + } + info := &ProviderProfileInfo{ + DefaultMode: profile.DefaultMode, + Routing: routing, + ResponsesPath: profile.ResponsesPath, + Modes: make([]ProviderModeInfo, 0, len(modes)), + } + for _, mode := range modes { + endpoints := profile.Modes[mode] + baseURLs := make(map[string]string, len(endpoints.BaseURLs)) + for protocol, baseURL := range endpoints.BaseURLs { + baseURLs[protocol] = baseURL + } + info.Modes = append(info.Modes, ProviderModeInfo{ + Mode: mode, + BaseURLs: baseURLs, + ProtocolRules: append([]ProtocolRule(nil), endpoints.ProtocolRules...), + }) + } + return info +} diff --git a/backend/internal/service/platform_catalog_test.go b/backend/internal/service/platform_catalog_test.go new file mode 100644 index 0000000000..b6da5ae5d6 --- /dev/null +++ b/backend/internal/service/platform_catalog_test.go @@ -0,0 +1,140 @@ +//go:build unit + +package service + +import ( + "encoding/json" + "errors" + "os" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/domain" + "github.com/stretchr/testify/require" +) + +func TestBuildPlatformCatalogMirrorsPlatformListAndProfiles(t *testing.T) { + catalog := BuildPlatformCatalog() + require.Equal(t, domain.CompositePrecedencePlatformIDs(), catalog.CompositePrecedence) + require.Len(t, catalog.Platforms, len(domain.ConcretePlatformIDs())) + + for i, entry := range catalog.Platforms { + require.Equal(t, domain.ConcretePlatformIDs()[i], entry.ID) + profile := LookupProviderProfile(entry.ID) + if profile == nil { + require.Nil(t, entry.MultiProtocol, entry.ID) + continue + } + require.NotNil(t, entry.MultiProtocol, entry.ID) + require.Equal(t, profile.DefaultMode, entry.MultiProtocol.DefaultMode, entry.ID) + require.Equal(t, profile.DefaultMode, entry.MultiProtocol.Modes[0].Mode, entry.ID) + require.Equal(t, profile.ResponsesPath, entry.MultiProtocol.ResponsesPath, entry.ID) + require.Len(t, entry.MultiProtocol.Modes, len(profile.Modes), entry.ID) + for _, mode := range entry.MultiProtocol.Modes { + endpoints := profile.Modes[mode.Mode] + require.Equal(t, endpoints.BaseURLs, mode.BaseURLs, "%s/%s", entry.ID, mode.Mode) + require.Equal(t, len(endpoints.ProtocolRules), len(mode.ProtocolRules), "%s/%s", entry.ID, mode.Mode) + for j, rule := range endpoints.ProtocolRules { + require.Equal(t, rule, mode.ProtocolRules[j]) + } + } + } +} + +func TestBuildPlatformCatalogJSONShape(t *testing.T) { + raw, err := json.Marshal(BuildPlatformCatalog()) + require.NoError(t, err) + + type modeJSON struct { + Mode string `json:"mode"` + BaseURLs map[string]string `json:"base_urls"` + ProtocolRules []ProtocolRule `json:"protocol_rules"` + } + type platformJSON struct { + ID string `json:"id"` + DisplayName string `json:"display_name"` + Gateway string `json:"gateway"` + CNProvider *bool `json:"cn_provider"` + MultiProtocol *struct { + DefaultMode string `json:"default_mode"` + Routing string `json:"routing"` + ResponsesPath string `json:"responses_path"` + Modes []modeJSON `json:"modes"` + } `json:"multi_protocol"` + } + var decoded struct { + Platforms []platformJSON `json:"platforms"` + CompositePrecedence []string `json:"composite_precedence"` + } + require.NoError(t, json.Unmarshal(raw, &decoded)) + require.Equal(t, domain.CompositePrecedencePlatformIDs(), decoded.CompositePrecedence) + byID := map[string]platformJSON{} + for _, p := range decoded.Platforms { + byID[p.ID] = p + } + + anthropic := byID[PlatformAnthropic] + require.Equal(t, "Anthropic", anthropic.DisplayName) + require.Equal(t, "anthropic", anthropic.Gateway) + require.NotNil(t, anthropic.CNProvider) + require.False(t, *anthropic.CNProvider) + require.Nil(t, anthropic.MultiProtocol) + require.NotContains(t, string(raw), `"multi_protocol":null`) + + deepseek := byID[PlatformDeepseek].MultiProtocol + require.NotNil(t, deepseek) + require.Equal(t, "by_inbound", deepseek.Routing) + require.Equal(t, "/responses", deepseek.ResponsesPath) + + openCode := byID[PlatformOpenCodeGo].MultiProtocol + require.NotNil(t, openCode) + require.Equal(t, "by_model", openCode.Routing) + require.Equal(t, AccountModeGo, openCode.DefaultMode) + require.Len(t, openCode.Modes, 2) + require.Equal(t, AccountModeGo, openCode.Modes[0].Mode) + require.Equal(t, DefaultOpenCodeGoBaseURL, openCode.Modes[0].BaseURLs[APIProtocolChatCompletions]) + require.Equal(t, DefaultOpenCodeGoProtocolRules(), openCode.Modes[0].ProtocolRules) + require.Equal(t, AccountModeZen, openCode.Modes[1].Mode) +} + +// 下发的是副本:调用方修改结果不影响内置 profile。 +func TestBuildPlatformCatalogReturnsCopies(t *testing.T) { + catalog := BuildPlatformCatalog() + for _, entry := range catalog.Platforms { + if entry.MultiProtocol == nil { + continue + } + for _, mode := range entry.MultiProtocol.Modes { + for protocol := range mode.BaseURLs { + mode.BaseURLs[protocol] = "mutated" + } + for i := range mode.ProtocolRules { + mode.ProtocolRules[i].Protocol = "mutated" + } + } + } + require.Equal(t, DefaultOpenCodeGoBaseURL, LookupProviderProfile(PlatformOpenCodeGo).DefaultBaseURL(AccountModeGo, APIProtocolChatCompletions)) + require.NotEqual(t, "mutated", LookupProviderProfile(PlatformOpenCodeGo).Modes[AccountModeGo].ProtocolRules[0].Protocol) +} + +// 前端内置的平台清单(接口加载前与加载失败时使用)必须与后端一致。 +// 更新平台清单或 profile 后运行: +// +// UPDATE_PLATFORM_CATALOG=1 go test -tags unit ./internal/service/ -run TestFrontendBuiltinPlatformCatalogInSync +func TestFrontendBuiltinPlatformCatalogInSync(t *testing.T) { + const path = "../../../frontend/src/constants/platformCatalog.builtin.json" + want, err := json.MarshalIndent(BuildPlatformCatalog(), "", " ") + require.NoError(t, err) + want = append(want, '\n') + + if os.Getenv("UPDATE_PLATFORM_CATALOG") == "1" { + require.NoError(t, os.WriteFile(path, want, 0o644)) + return + } + got, err := os.ReadFile(path) + if errors.Is(err, os.ErrNotExist) { + t.Skip("frontend sources not available") + } + require.NoError(t, err) + require.JSONEq(t, string(want), string(got), + "frontend/src/constants/platformCatalog.builtin.json 与后端平台清单不一致,按测试注释重新生成") +} diff --git a/frontend/src/api/__tests__/settings.authSourceDefaults.spec.ts b/frontend/src/api/__tests__/settings.authSourceDefaults.spec.ts index deeb758250..7da7225e71 100644 --- a/frontend/src/api/__tests__/settings.authSourceDefaults.spec.ts +++ b/frontend/src/api/__tests__/settings.authSourceDefaults.spec.ts @@ -8,15 +8,18 @@ import { type UpdateSettingsRequest, type DefaultPlatformQuotasMap, } from "@/api/admin/settings"; +import { listPlatformIds } from "@/constants/platformCatalog"; -/** 全 null 的 5 平台 map,用于断言归一化默认值 */ -const allNullQuotas: DefaultPlatformQuotasMap = { - anthropic: { daily: null, weekly: null, monthly: null }, - openai: { daily: null, weekly: null, monthly: null }, - gemini: { daily: null, weekly: null, monthly: null }, - antigravity: { daily: null, weekly: null, monthly: null }, - grok: { daily: null, weekly: null, monthly: null }, -} +/** 与后端 AllowedQuotaPlatforms 一致的全部具体平台(平台清单)。 */ +const quotaPlatforms = [ + "anthropic", "openai", "gemini", "antigravity", "grok", + "kimi", "zhipu", "deepseek", "minimax", "opencode_go", "typesafe", +]; + +/** 全部平台全 null 的 map,用于断言归一化默认值 */ +const allNullQuotas: DefaultPlatformQuotasMap = Object.fromEntries( + quotaPlatforms.map((platform) => [platform, { daily: null, weekly: null, monthly: null }]), +) describe("admin settings auth source defaults helpers", () => { it("builds auth source defaults state from flat settings fields", () => { @@ -238,11 +241,14 @@ describe("normalizePlatformQuotasMap", () => { expect(result.gemini).toEqual({ daily: null, weekly: null, monthly: null }); expect(result.antigravity).toEqual({ daily: null, weekly: null, monthly: null }); expect(result.grok).toEqual({ daily: null, weekly: null, monthly: null }); + expect(result.kimi).toEqual({ daily: null, weekly: null, monthly: null }); + expect(result.opencode_go).toEqual({ daily: null, weekly: null, monthly: null }); }); - it("无参数时返回全 5 平台全 null", () => { + it("无参数时返回平台清单中的全部平台全 null", () => { const result = normalizePlatformQuotasMap(); - expect(Object.keys(result)).toHaveLength(5); + expect(listPlatformIds()).toEqual(quotaPlatforms); + expect(Object.keys(result)).toEqual(quotaPlatforms); for (const v of Object.values(result)) { expect(v).toEqual({ daily: null, weekly: null, monthly: null }); } @@ -290,7 +296,7 @@ describe("sanitizePlatformQuotasMap", () => { it("缺失平台填充为全 null", () => { const result = sanitizePlatformQuotasMap({}); - expect(Object.keys(result)).toHaveLength(5); + expect(Object.keys(result)).toEqual(quotaPlatforms); for (const v of Object.values(result)) { expect(v).toEqual({ daily: null, weekly: null, monthly: null }); } diff --git a/frontend/src/api/admin/settings.ts b/frontend/src/api/admin/settings.ts index 1a9c24103c..4e0fbf240b 100644 --- a/frontend/src/api/admin/settings.ts +++ b/frontend/src/api/admin/settings.ts @@ -4,7 +4,9 @@ */ import { apiClient } from "../client"; +import { listPlatformIds } from "@/constants/platformCatalog"; import type { + AccountPlatform, CustomEndpoint, CustomMenuItem, LoginAgreementDocument, @@ -18,7 +20,8 @@ export interface DefaultSubscriptionSetting { } // ── 平台限额类型 ────────────────────────────────────────────────── -export type PlatformType = "anthropic" | "openai" | "gemini" | "antigravity" | "grok" | "typesafe" +/** 可设置默认限额的平台:平台清单中的全部具体平台(与后端 AllowedQuotaPlatforms 同源)。 */ +export type PlatformType = AccountPlatform export type QuotaWindowType = "daily" | "weekly" | "monthly" /** 单平台三档限额;null = 不限制,undefined = 未填(等价 null) */ @@ -31,7 +34,6 @@ export interface PlatformQuotaLimits { /** 全平台默认限额 map(key = PlatformType) */ export type DefaultPlatformQuotasMap = Partial> -const PLATFORMS: PlatformType[] = ["anthropic", "openai", "gemini", "antigravity", "grok", "typesafe"] export type SchedulingThresholdPlatformType = | "openai" @@ -75,10 +77,10 @@ export function sanitizeAccountSchedulingThresholdsMap( return normalizeAccountSchedulingThresholdsMap(input) } -/** 归一化为全 4 平台 × 3 窗口(缺失填 null),供模板非空绑定 */ +/** 归一化为全部平台 × 3 窗口(缺失填 null),供模板非空绑定 */ export function normalizePlatformQuotasMap(input?: DefaultPlatformQuotasMap | null): DefaultPlatformQuotasMap { const result: DefaultPlatformQuotasMap = {} - for (const p of PLATFORMS) { + for (const p of listPlatformIds()) { const src = input?.[p] result[p] = { daily: typeof src?.daily === "number" ? src.daily : null, @@ -89,11 +91,11 @@ export function normalizePlatformQuotasMap(input?: DefaultPlatformQuotasMap | nu return result } -/** 提交前清洗:非有限数/负数/空字符串 → null(保留 0 = 显式禁用),返回全 4 平台嵌套 map */ +/** 提交前清洗:非有限数/负数/空字符串 → null(保留 0 = 显式禁用),返回全部平台嵌套 map */ export function sanitizePlatformQuotasMap(input?: DefaultPlatformQuotasMap | null): DefaultPlatformQuotasMap { const clean = (v: unknown): number | null => (typeof v === "number" && Number.isFinite(v) && v >= 0 ? v : null) const result: DefaultPlatformQuotasMap = {} - for (const p of PLATFORMS) { + for (const p of listPlatformIds()) { const src = input?.[p] result[p] = { daily: clean(src?.daily), weekly: clean(src?.weekly), monthly: clean(src?.monthly) } } diff --git a/frontend/src/api/admin/users.ts b/frontend/src/api/admin/users.ts index 5e2140857c..d943508e79 100644 --- a/frontend/src/api/admin/users.ts +++ b/frontend/src/api/admin/users.ts @@ -4,7 +4,8 @@ */ import { apiClient } from '../client' -import type { AdminUser, UpdateUserRequest, PaginatedResponse, ApiKey } from '@/types' +import { listPlatformIds } from '@/constants/platformCatalog' +import type { AccountPlatform, AdminUser, UpdateUserRequest, PaginatedResponse, ApiKey } from '@/types' export interface AdminBindAuthIdentityChannelRequest { channel: string @@ -330,12 +331,11 @@ export async function bindUserAuthIdentity( /** * Platform quota types */ -// Keep aligned with backend/internal/service/domain_constants.go AllowedQuotaPlatforms. -export const PLATFORM_QUOTA_PLATFORMS = [ - 'anthropic', 'openai', 'gemini', 'antigravity', 'grok', - 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', 'typesafe', -] as const -export type PlatformQuotaPlatform = typeof PLATFORM_QUOTA_PLATFORMS[number] +// 与后端 AllowedQuotaPlatforms 同源:平台清单中的全部具体平台。 +export function platformQuotaPlatforms(): PlatformQuotaPlatform[] { + return listPlatformIds() +} +export type PlatformQuotaPlatform = AccountPlatform export type PlatformQuotaWindow = 'daily' | 'weekly' | 'monthly' export interface PlatformQuotaItem { diff --git a/frontend/src/components/account/CreateAccountModal.vue b/frontend/src/components/account/CreateAccountModal.vue index 64cea06900..759571b867 100644 --- a/frontend/src/components/account/CreateAccountModal.vue +++ b/frontend/src/components/account/CreateAccountModal.vue @@ -160,9 +160,22 @@ Grok + - -
+ +
+
+ + +
+
@@ -545,6 +567,35 @@ + +
+ +
+ +
+
+
@@ -1390,7 +1441,7 @@ v-if="isCNPlatform && !isOpenCodeGoPlatform" class="mt-2" :platform="cnPresetPlatform" - :mode="accountMode" + :mode="cnPresetMode" :protocol="apiProtocol" :current-url="apiKeyBaseUrl" @select="onCnPresetSelect" @@ -1411,14 +1462,15 @@ />
-

+

{{ t('admin.accounts.cnProviders.apiProtocol.responsesFallbackDesc') }}

@@ -3966,8 +4018,14 @@ import { defaultCNAdaptiveBaseUrls, defaultCNBaseUrl, defaultOpenCodeProtocolRules, + defaultProviderProtocolRules, isCNProviderPlatform, isHeaderOverrideCapable, + isMultiProtocolApiKeyPlatform, + providerAccountModes, + providerNativeProtocols, + providerRoutesByModel, + resolveProviderAccountMode, validateHeaderOverrideRows, type CnAccountMode, type CnApiProtocol, @@ -3977,6 +4035,7 @@ import { type OpenCodeAccountMode, type OpenCodeGoProtocolRule } from '@/components/account/credentialsBuilder' +import { listPlatforms } from '@/constants/platformCatalog' import { formatDateTimeLocalInput, getBrowserTimeZone, @@ -4042,7 +4101,8 @@ const baseUrlHint = computed(() => { const apiKeyHint = computed(() => { if (form.platform === 'openai') return t('admin.accounts.openai.apiKeyHint') if (form.platform === 'gemini') return t('admin.accounts.gemini.apiKeyHint') - if (form.platform === 'grok') return '' + // Grok 与多协议供应商没有对应的说明文案;通用文案指 Claude Console Key。 + if (form.platform === 'grok' || isMultiProtocolPlatform.value) return '' return t('admin.accounts.apiKeyHint') }) @@ -4086,7 +4146,7 @@ const apiKeyValuePlaceholder = computed(() => { case 'typesafe': return 'ts-...' default: - return 'sk-ant-...' + return isMultiProtocolPlatform.value ? 'sk-...' : 'sk-ant-...' } }) @@ -4174,7 +4234,8 @@ const apiKeyValue = ref('') const upstreamBillingAutoProbeEnabled = ref(true) // ── 国产供应商(Kimi / Zhipu / DeepSeek)账号类型、API 协议与端点 ── -const accountMode = ref('payg') +// 多协议供应商(国产厂商与走通用表单的供应商)的接入模式;OpenCode 用 openCodeAccountMode。 +const accountMode = ref('payg') const openCodeAccountMode = ref('zen') // API 协议决定转发端点与格式:cc=现有转换链,anthropic=原生直通(Claude Code), // responses=deepseek / kimi 原生 Responses 端点(Codex)。与账号类型正交。 @@ -4192,8 +4253,33 @@ const adaptiveBaseUrls = ref>({ }) const isCNPlatform = computed(() => isCNProviderPlatform(form.platform)) const isOpenCodeGoPlatform = computed(() => form.platform === 'opencode_go') -const isMultiProtocolPlatform = computed(() => isCNPlatform.value || isOpenCodeGoPlatform.value) -function currentOpenCodeOrCNMode(): CnAccountMode | OpenCodeAccountMode { +const isMultiProtocolPlatform = computed(() => isMultiProtocolApiKeyPlatform(form.platform)) +// 前端没有专属界面、走通用表单的多协议供应商:模式、协议、默认端点 +// 与分流规则全部来自平台清单中的 profile。 +const isGenericMultiProtocolPlatform = computed( + () => isMultiProtocolPlatform.value && !isCNPlatform.value && !isOpenCodeGoPlatform.value +) +const extraMultiProtocolPlatforms = computed(() => + listPlatforms().filter(spec => !!spec.multi_protocol && !isCNProviderPlatform(spec.id) && spec.id !== 'opencode_go') +) +const genericAccountModes = computed(() => providerAccountModes(form.platform)) +// 按模型分流的供应商(OpenCode 等):adaptive 账号携带 protocol_rules。 +const routesByModel = computed(() => providerRoutesByModel(form.platform)) +function providerModeLabel(mode: string): string { + switch (mode) { + case 'payg': + return t('admin.accounts.cnProviders.accountMode.payg') + case 'coding': + return t('admin.accounts.cnProviders.accountMode.coding') + case 'zen': + return t('admin.accounts.opencodeGo.accountMode.zen') + case 'go': + return t('admin.accounts.opencodeGo.accountMode.go') + default: + return mode + } +} +function currentOpenCodeOrCNMode(): string { return isOpenCodeGoPlatform.value ? openCodeAccountMode.value : accountMode.value } // CnBaseUrlPresets 的 platform prop 是平台字面量联合类型,模板里不能写 @@ -4204,35 +4290,31 @@ const cnPresetPlatform = computed(() => { } return 'kimi' }) -const adaptivePresetPlatform = computed(() => { - if (form.platform === 'opencode_go') return 'opencode_go' +// 国产厂商的接入模式只有 payg / coding(selectCNPlatform 已按 profile 规范化)。 +const cnPresetMode = computed(() => (accountMode.value === 'coding' ? 'coding' : 'payg')) +const adaptivePresetPlatform = computed(() => { + if (isMultiProtocolPlatform.value) return form.platform return cnPresetPlatform.value }) -// 当前平台可选的协议档(responses 仅 deepseek / kimi)。 -const cnProtocolOptions = computed>(() => { - const opts: Array<{ value: CnApiProtocol; labelKey: string }> = [ - { value: 'adaptive', labelKey: 'adaptive' }, - { value: 'chat_completions', labelKey: 'chatCompletions' }, - { value: 'anthropic', labelKey: 'anthropic' } - ] - if (cnSupportsNativeResponses(form.platform)) { - opts.push({ value: 'responses', labelKey: 'responses' }) - } - return opts -}) -const cnAdaptiveProtocolOptions = computed>(() => { - const opts: Array<{ value: CnNativeApiProtocol; labelKey: string }> = [ - { value: 'chat_completions', labelKey: 'chatCompletions' }, - { value: 'anthropic', labelKey: 'anthropic' } - ] - if (cnSupportsNativeResponses(form.platform)) opts.push({ value: 'responses', labelKey: 'responses' }) - return opts -}) +const NATIVE_PROTOCOL_LABEL_KEYS: Record = { + chat_completions: 'chatCompletions', + anthropic: 'anthropic', + responses: 'responses' +} +// 当前平台与接入模式提供原生端点的协议(profile 中有默认基址的协议)。 +const cnAdaptiveProtocolOptions = computed>(() => + providerNativeProtocols(form.platform, currentOpenCodeOrCNMode()).map(value => ({ + value, + labelKey: NATIVE_PROTOCOL_LABEL_KEYS[value] + })) +) +// 可选的协议档:adaptive 加上各原生协议(responses 仅 deepseek / kimi 等提供原生端点的供应商)。 +const cnProtocolOptions = computed>(() => [ + { value: 'adaptive', labelKey: 'adaptive' }, + ...cnAdaptiveProtocolOptions.value +]) -function resetAdaptiveBaseUrls( - platform: CnProviderPlatform | 'opencode_go', - mode: CnAccountMode | OpenCodeAccountMode -) { +function resetAdaptiveBaseUrls(platform: string, mode: string) { adaptiveBaseUrls.value = defaultCNAdaptiveBaseUrls(platform, mode) } // 当前选中平台的品牌色(选中卡片描边 / 图标底色),与 platformColors 取色一致。 @@ -4275,9 +4357,8 @@ function selectCNPlatform(platform: CnProviderPlatform) { form.type = 'apikey' accountCategory.value = 'apikey' apiProtocol.value = 'adaptive' - if (platform === 'deepseek') { - accountMode.value = 'payg' - } + // deepseek 无 coding 套餐(profile 仅 payg);从其他供应商切换来的未知模式回落默认模式。 + accountMode.value = resolveProviderAccountMode(platform, accountMode.value) apiKeyBaseUrl.value = defaultCNBaseUrl(platform, accountMode.value, apiProtocol.value) resetAdaptiveBaseUrls(platform, accountMode.value) } @@ -4298,6 +4379,16 @@ function selectTypeSafePlatform() { apiKeyBaseUrl.value = 'https://api.typesafe.ai' allowedModels.value = ['jev-latest'] } +function selectGenericMultiProtocolPlatform(platform: string) { + form.platform = platform + form.type = 'apikey' + accountCategory.value = 'apikey' + apiProtocol.value = 'adaptive' + accountMode.value = resolveProviderAccountMode(platform, undefined) + apiKeyBaseUrl.value = defaultCNBaseUrl(platform, accountMode.value, apiProtocol.value) + resetAdaptiveBaseUrls(platform, accountMode.value) + openCodeGoProtocolRules.value = cloneOpenCodeGoProtocolRules(defaultProviderProtocolRules(platform, accountMode.value)) +} // 账号类型 / 协议变更时同步默认 base url。 watch(openCodeAccountMode, (mode, previousMode) => { if (!isOpenCodeGoPlatform.value) return @@ -4320,6 +4411,12 @@ watch(openCodeAccountMode, (mode, previousMode) => { }) watch(accountMode, (mode, previousMode) => { if (!isMultiProtocolPlatform.value || isOpenCodeGoPlatform.value) return + if (routesByModel.value) { + const previousRules = JSON.stringify(defaultProviderProtocolRules(form.platform, previousMode)) + if (JSON.stringify(openCodeGoProtocolRules.value) === previousRules) { + openCodeGoProtocolRules.value = cloneOpenCodeGoProtocolRules(defaultProviderProtocolRules(form.platform, mode)) + } + } if (apiProtocol.value === 'adaptive') { const previousDefaults = defaultCNAdaptiveBaseUrls(adaptivePresetPlatform.value, previousMode) const nextDefaults = defaultCNAdaptiveBaseUrls(adaptivePresetPlatform.value, mode) @@ -4860,7 +4957,7 @@ watch( () => form.platform, (newPlatform) => { // Reset base URL based on platform - if (isCNProviderPlatform(newPlatform) || newPlatform === 'opencode_go') { + if (isMultiProtocolApiKeyPlatform(newPlatform)) { const mode = newPlatform === 'opencode_go' ? openCodeAccountMode.value : accountMode.value apiKeyBaseUrl.value = defaultCNBaseUrl(newPlatform, mode, apiProtocol.value) } else { @@ -5823,7 +5920,7 @@ const handleSubmit = async () => { // 国产供应商:账号模式 + 协议 + 对应端点写入凭据;后端按 account_mode 路由 // 额度/余额探测,按 api_protocol 路由转发端点与格式。注意 CN apikey 走本函数 // 的通用路径(直接 doCreateAccount),不经过 createAccountAndFinish。 - if (isCNProviderPlatform(form.platform) || form.platform === 'opencode_go') { + if (isMultiProtocolApiKeyPlatform(form.platform)) { credentials.account_mode = form.platform === 'opencode_go' ? openCodeAccountMode.value : accountMode.value credentials.api_protocol = apiProtocol.value if (apiProtocol.value === 'adaptive') { @@ -5849,7 +5946,7 @@ const handleSubmit = async () => { if (zhipuOrganization.value.trim()) credentials.zhipu_organization = zhipuOrganization.value.trim() if (zhipuProject.value.trim()) credentials.zhipu_project = zhipuProject.value.trim() } - if (form.platform === 'opencode_go') { + if (providerRoutesByModel(form.platform)) { applyOpenCodeGoProtocolRules(credentials, openCodeGoProtocolRules.value, 'create') } } diff --git a/frontend/src/components/account/EditAccountModal.vue b/frontend/src/components/account/EditAccountModal.vue index f7af882c7b..55ac086b96 100644 --- a/frontend/src/components/account/EditAccountModal.vue +++ b/frontend/src/components/account/EditAccountModal.vue @@ -53,10 +53,10 @@ @select="editBaseUrl = $event" />
-

+

{{ t('admin.accounts.cnProviders.apiProtocol.responsesFallbackDesc') }}

@@ -128,8 +128,28 @@ + +
+ +
+ +
+
-
+
@@ -3151,7 +3172,13 @@ import { buildPlanTypeOptions, cloneOpenCodeGoProtocolRules, defaultOpenCodeProtocolRules, + defaultProviderProtocolRules, + isMultiProtocolApiKeyPlatform, parseOpenCodeGoProtocolRules, + providerAccountModes, + providerNativeProtocols, + providerRoutesByModel, + resolveProviderAccountMode, readPlanType, resolveOpenCodeAccountMode, isCustomGrokBaseUrl, @@ -3356,11 +3383,18 @@ const editApiKey = ref('') // ── 国产供应商(Kimi / Zhipu / DeepSeek)account_mode / api_protocol 编辑 ── // account_mode 决定额度/余额监控路径,api_protocol 决定转发端点与格式; // 二者均可修正(早期创建的账号可能存错默认值),切换时重置 base_url 预置。 +// 覆盖全部多协议 API Key 供应商(国产厂商、OpenCode 与走通用表单的供应商)。 const isCNApiKeyAccount = computed( - () => - props.account?.type === 'apikey' && - (isCNProviderPlatform(props.account.platform) || props.account.platform === 'opencode_go') + () => props.account?.type === 'apikey' && isMultiProtocolApiKeyPlatform(props.account.platform) ) +// 前端没有专属界面、走通用表单的多协议供应商:模式 / 协议 / 默认端点来自 profile。 +const isGenericMultiProtocolAccount = computed( + () => + isCNApiKeyAccount.value && + !isCNProviderPlatform(props.account?.platform ?? '') && + props.account?.platform !== 'opencode_go' +) +const genericAccountModes = computed(() => providerAccountModes(props.account?.platform ?? '')) // CnBaseUrlPresets 的 platform prop 是平台字面量联合类型,模板里不能写 // `as` 断言(其中的 `|` 会被 eslint 误判为 Vue2 filter 语法),经此 computed 传递。 const cnPresetPlatform = computed(() => { @@ -3370,15 +3404,18 @@ const cnPresetPlatform = computed(() => { } return 'kimi' }) -const adaptivePresetPlatform = computed(() => { - if (props.account?.platform === 'opencode_go') return 'opencode_go' +const adaptivePresetPlatform = computed(() => { + if (isCNApiKeyAccount.value) return props.account!.platform return cnPresetPlatform.value }) const editApiProtocol = ref('adaptive') const editOpenCodeGoProtocolRules = ref(cloneOpenCodeGoProtocolRules()) -const editAccountMode = ref('payg') +// 多协议供应商(国产厂商与走通用表单的供应商)的接入模式;OpenCode 用 editOpenCodeAccountMode。 +const editAccountMode = ref('payg') const editOpenCodeAccountMode = ref('go') -function currentOpenCodeOrCNMode(): CnAccountMode | OpenCodeAccountMode { +// 国产厂商的接入模式只有 payg / coding。 +const cnPresetMode = computed(() => (editAccountMode.value === 'coding' ? 'coding' : 'payg')) +function currentOpenCodeOrCNMode(): string { return props.account?.platform === 'opencode_go' ? editOpenCodeAccountMode.value : editAccountMode.value } // 智谱团队版 Coding Plan:组织/项目 ID,写入 credentials 供额度探测切换团队端点 @@ -3406,25 +3443,22 @@ const cnAccountModeOptions = computed>(() => { - const opts: Array<{ value: CnApiProtocol; labelKey: string }> = [ - { value: 'adaptive', labelKey: 'adaptive' }, - { value: 'chat_completions', labelKey: 'chatCompletions' }, - { value: 'anthropic', labelKey: 'anthropic' } - ] - if (cnSupportsNativeResponses(props.account?.platform ?? '')) { - opts.push({ value: 'responses', labelKey: 'responses' }) - } - return opts -}) -const editAdaptiveProtocolOptions = computed>(() => { - const opts: Array<{ value: CnNativeApiProtocol; labelKey: string }> = [ - { value: 'chat_completions', labelKey: 'chatCompletions' }, - { value: 'anthropic', labelKey: 'anthropic' } - ] - if (cnSupportsNativeResponses(props.account?.platform ?? '')) opts.push({ value: 'responses', labelKey: 'responses' }) - return opts -}) +const NATIVE_PROTOCOL_LABEL_KEYS: Record = { + chat_completions: 'chatCompletions', + anthropic: 'anthropic', + responses: 'responses' +} +// 当前供应商与接入模式提供原生端点的协议(profile 中有默认基址的协议)。 +const editAdaptiveProtocolOptions = computed>(() => + providerNativeProtocols(props.account?.platform ?? '', currentOpenCodeOrCNMode()).map(value => ({ + value, + labelKey: NATIVE_PROTOCOL_LABEL_KEYS[value] + })) +) +const cnProtocolOptions = computed>(() => [ + { value: 'adaptive', labelKey: 'adaptive' }, + ...editAdaptiveProtocolOptions.value +]) watch(editApiProtocol, (protocol, previousProtocol) => { if (!isCNApiKeyAccount.value || syncingForm.value) return if (protocol === 'adaptive') { @@ -3448,12 +3482,20 @@ watch(editApiProtocol, (protocol, previousProtocol) => { watch(editAccountMode, (mode, previousMode) => { if (!isCNApiKeyAccount.value || syncingForm.value) return if (props.account?.platform === 'opencode_go') return - // deepseek 无 coding 套餐:防御性回退(UI 已隐藏该选项)。 - const effectiveMode = props.account!.platform === 'deepseek' && mode === 'coding' ? 'payg' : mode + // 供应商没有的接入模式(如 deepseek 无 coding 套餐)防御性回退默认模式(UI 已隐藏该选项)。 + const effectiveMode = resolveProviderAccountMode(props.account!.platform, mode) if (effectiveMode !== mode) { editAccountMode.value = effectiveMode return } + if (providerRoutesByModel(props.account!.platform)) { + const previousRules = JSON.stringify(defaultProviderProtocolRules(props.account!.platform, previousMode)) + if (JSON.stringify(editOpenCodeGoProtocolRules.value) === previousRules) { + editOpenCodeGoProtocolRules.value = cloneOpenCodeGoProtocolRules( + defaultProviderProtocolRules(props.account!.platform, mode) + ) + } + } if (editApiProtocol.value === 'adaptive') { const previousDefaults = defaultCNAdaptiveBaseUrls(adaptivePresetPlatform.value, previousMode) const nextDefaults = defaultCNAdaptiveBaseUrls(adaptivePresetPlatform.value, mode) @@ -3994,12 +4036,7 @@ const defaultBaseUrl = computed(() => { if (props.account?.platform === 'typesafe') return 'https://api.typesafe.ai' // CN 供应商:按当前模式/协议回落到官方预设(清空输入框提交时使用), // 不能落到 anthropic 默认值(会被当 CC base 拼出错误端点)。 - if ( - props.account?.platform === 'kimi' || - props.account?.platform === 'zhipu' || - props.account?.platform === 'deepseek' || - props.account?.platform === 'opencode_go' - ) { + if (props.account && isMultiProtocolApiKeyPlatform(props.account.platform)) { return defaultCNBaseUrl(props.account.platform, currentOpenCodeOrCNMode(), editApiProtocol.value) } return 'https://api.anthropic.com' @@ -4375,11 +4412,13 @@ const syncFormFromAccount = (newAccount: Account | null) => { const credentials = newAccount.credentials as Record // 国产供应商:读取 account_mode 与 api_protocol 作为可编辑初始值 // (编辑弹窗允许修正两者,用于修复早期存错默认值的账号)。 - if (isCNProviderPlatform(newAccount.platform) || newAccount.platform === 'opencode_go') { + if (isMultiProtocolApiKeyPlatform(newAccount.platform)) { if (newAccount.platform === 'opencode_go') { editOpenCodeAccountMode.value = resolveOpenCodeAccountMode(credentials.account_mode) - } else { + } else if (isCNProviderPlatform(newAccount.platform)) { editAccountMode.value = credentials.account_mode === 'coding' ? 'coding' : 'payg' + } else { + editAccountMode.value = resolveProviderAccountMode(newAccount.platform, credentials.account_mode) } const storedProtocol = credentials.api_protocol editApiProtocol.value = @@ -4389,7 +4428,7 @@ const syncFormFromAccount = (newAccount: Account | null) => { storedProtocol === 'responses' ? storedProtocol : 'chat_completions' - if (!cnSupportsNativeResponses(newAccount.platform) && editApiProtocol.value === 'responses') { + if (!cnSupportsNativeResponses(newAccount.platform, currentOpenCodeOrCNMode()) && editApiProtocol.value === 'responses') { editApiProtocol.value = 'chat_completions' } const adaptiveDefaults = defaultCNAdaptiveBaseUrls(newAccount.platform, currentOpenCodeOrCNMode()) @@ -4428,10 +4467,10 @@ const syncFormFromAccount = (newAccount: Account | null) => { editZhipuOrganization.value = typeof credentials.zhipu_organization === 'string' ? credentials.zhipu_organization : '' editZhipuProject.value = typeof credentials.zhipu_project === 'string' ? credentials.zhipu_project : '' } - if (newAccount.platform === 'opencode_go') { + if (providerRoutesByModel(newAccount.platform)) { editOpenCodeGoProtocolRules.value = parseOpenCodeGoProtocolRules(credentials.protocol_rules) ?? - cloneOpenCodeGoProtocolRules(defaultOpenCodeProtocolRules(editOpenCodeAccountMode.value)) + cloneOpenCodeGoProtocolRules(defaultProviderProtocolRules(newAccount.platform, currentOpenCodeOrCNMode())) } } const platformDefaultUrl = @@ -4443,10 +4482,7 @@ const syncFormFromAccount = (newAccount: Account | null) => { ? 'https://api.x.ai/v1' : newAccount.platform === 'typesafe' ? 'https://api.typesafe.ai' - : newAccount.platform === 'kimi' || - newAccount.platform === 'zhipu' || - newAccount.platform === 'deepseek' || - newAccount.platform === 'opencode_go' + : isMultiProtocolApiKeyPlatform(newAccount.platform) ? defaultCNBaseUrl(newAccount.platform, currentOpenCodeOrCNMode(), editApiProtocol.value) : 'https://api.anthropic.com' editBaseUrl.value = isCNApiKeyAccount.value && editApiProtocol.value === 'adaptive' @@ -5193,7 +5229,7 @@ const handleSubmit = async () => { } else { delete newCredentials.api_base_urls } - if (props.account.platform === 'opencode_go') { + if (providerRoutesByModel(props.account.platform)) { applyOpenCodeGoProtocolRules(newCredentials, editOpenCodeGoProtocolRules.value, 'edit') } // 智谱团队版 Coding Plan:组织/项目 ID 写入凭据(非空才写,清空即移除回落个人版路径) diff --git a/frontend/src/components/account/ModelWhitelistSelector.vue b/frontend/src/components/account/ModelWhitelistSelector.vue index d1e7e557cb..0e9fe1d6e9 100644 --- a/frontend/src/components/account/ModelWhitelistSelector.vue +++ b/frontend/src/components/account/ModelWhitelistSelector.vue @@ -154,6 +154,7 @@ import { useClipboard } from '@/composables/useClipboard' import ModelIcon from '@/components/common/ModelIcon.vue' import Icon from '@/components/icons/Icon.vue' import { allModels, getModelsByPlatform } from '@/composables/useModelWhitelist' +import { isKnownPlatform } from '@/constants/platformCatalog' const { t } = useI18n() @@ -201,25 +202,15 @@ const normalizedPlatforms = computed(() => { ) }) -const upstreamSyncPlatforms = new Set([ - 'anthropic', - 'openai', - 'gemini', - 'antigravity', - 'grok', - 'kimi', - 'zhipu', - 'deepseek', - 'minimax', - 'opencode_go' -]) +// 上游模型同步支持全部已登记的具体平台(多协议供应商复用 OpenAI /v1/models)。 +const canSyncUpstreamPlatform = (platform: string) => isKnownPlatform(platform.toLowerCase()) const canSyncUpstream = computed(() => { if (props.accountId) { if (normalizedPlatforms.value.length === 0) return true - return normalizedPlatforms.value.some(platform => upstreamSyncPlatforms.has(platform.toLowerCase())) + return normalizedPlatforms.value.some(canSyncUpstreamPlatform) } if (props.syncCredentials) { - return upstreamSyncPlatforms.has(props.syncCredentials.platform.toLowerCase()) + return canSyncUpstreamPlatform(props.syncCredentials.platform) } return false }) diff --git a/frontend/src/components/account/OpenCodeGoProtocolRulesEditor.vue b/frontend/src/components/account/OpenCodeGoProtocolRulesEditor.vue index b35037ad66..c5127dda1d 100644 --- a/frontend/src/components/account/OpenCodeGoProtocolRulesEditor.vue +++ b/frontend/src/components/account/OpenCodeGoProtocolRulesEditor.vue @@ -29,14 +29,8 @@ class="input w-44 shrink-0" :data-testid="`opencode-go-protocol-select-${index}`" > - - -