feat(models): add configurable default fallback chain (#3200)

* feat(models): add configurable default fallback chain

* fix(lint): resolve linter issues

* fix(models): keep default fallback chain valid

* fix(models): normalize default chain on model writes

* fix(models): harden fallback chain consistency

* fix(models): preserve raw model provider injection

* fix(agent): preserve provider-prefixed model configs

* fix(agent): preserve injected provider contracts

* fix(agent): preserve fallback providers after model switch

* fix(build): update Go to 1.25.13
This commit is contained in:
LC authored and GitHub committed 2026-08-19 17:17:32 +08:00
1 parent 49183d7e8d
commit bbf6893ca7
39 files changed
+5376 -436

No files matched your search

+91 -74
View File
@@ -373,21 +373,34 @@ func (h *Handler) gatewayStartReady() (bool, string, error) {
if err != nil {
return false, "", fmt.Errorf("failed to load config: %w", err)
}
normalizeStoredModelNames(cfg)
modelName := strings.TrimSpace(cfg.Agents.Defaults.GetModelName())
if modelName == "" {
return false, "no default model configured", nil
}
if aliasModels := modelConfigsByName(cfg)[modelName]; len(aliasModels) > 1 {
if err := validateDefaultChainModelSet(
modelName,
aliasModels,
true,
defaultChainProvider(cfg),
); err != nil {
// Validation failures are readiness reasons, not handler errors.
//nolint:nilerr
return false, err.Error(), nil
}
}
modelCfg := lookupModelConfig(cfg, modelName)
if modelCfg == nil {
return false, fmt.Sprintf("default model %q is invalid", modelName), nil
}
if !defaultModelAllowedForModelConfig(modelCfg) {
if !defaultModelAllowedForModelConfig(modelCfg, defaultChainProvider(cfg)) {
return false, fmt.Sprintf("default model %q is not usable for chat", modelName), nil
}
if !hasModelConfiguration(modelCfg) {
if !rawTemplateHasConfiguration(modelCfg) {
return false, fmt.Sprintf("default model %q has no credentials configured", modelName), nil
}
if requiresRuntimeProbe(modelCfg) && !probeLocalModelAvailability(modelCfg) {
@@ -398,7 +411,7 @@ func (h *Handler) gatewayStartReady() (bool, string, error) {
}
func lookupModelConfig(cfg *config.Config, modelName string) *config.ModelConfig {
modelCfg, err := cfg.GetModelConfig(modelName)
modelCfg, err := providers.ResolveModelConfig(cfg, modelName)
if err != nil {
return nil
}
@@ -410,6 +423,7 @@ func computeConfigSignature(cfg *config.Config) string {
return ""
}
var parts []string
parts = append(parts, "default_provider:"+defaultChainProvider(cfg))
defaultModel := strings.TrimSpace(cfg.Agents.Defaults.GetModelName())
if defaultModel != "" {
parts = append(parts, "model:"+defaultModel)
@@ -504,32 +518,60 @@ func computeModelStreamingSignatures(cfg *config.Config) []string {
if defaultProvider == "" {
defaultProvider = "openai"
}
names := []string{strings.TrimSpace(cfg.Agents.Defaults.GetModelName())}
names = append(names, cfg.Agents.Defaults.ModelFallbacks...)
if cfg.Agents.Defaults.Routing != nil {
names = append(names, cfg.Agents.Defaults.Routing.LightModel)
type streamingRef struct {
scope string
name string
}
for _, agent := range cfg.Agents.List {
refs := []streamingRef{{
scope: "defaults.primary",
name: strings.TrimSpace(cfg.Agents.Defaults.GetModelName()),
}}
for i, name := range cfg.Agents.Defaults.ModelFallbacks {
refs = append(refs, streamingRef{
scope: "defaults.fallback:" + strconv.Itoa(i),
name: name,
})
}
if cfg.Agents.Defaults.Routing != nil {
refs = append(refs, streamingRef{
scope: "defaults.routing.light",
name: cfg.Agents.Defaults.Routing.LightModel,
})
}
for agentIndex, agent := range cfg.Agents.List {
if agent.Model == nil {
continue
}
names = append(names, agent.Model.Primary)
names = append(names, agent.Model.Fallbacks...)
refs = append(refs, streamingRef{
scope: "agent:" + strconv.Itoa(agentIndex) + ".primary",
name: agent.Model.Primary,
})
for i, name := range agent.Model.Fallbacks {
refs = append(refs, streamingRef{
scope: "agent:" + strconv.Itoa(agentIndex) + ".fallback:" + strconv.Itoa(i),
name: name,
})
}
}
seenNames := make(map[string]bool)
seenEntries := make(map[string]bool)
signatures := make([]string, 0, len(names))
for _, name := range names {
name = strings.TrimSpace(name)
if name == "" || seenNames[name] {
signatures := make([]string, 0, len(refs))
for _, ref := range refs {
ref.name = strings.TrimSpace(ref.name)
if ref.name == "" {
continue
}
seenNames[name] = true
for _, match := range modelConfigsMatchingSignatureRef(cfg.ModelList, name, defaultProvider) {
referenceEntry := strings.Join([]string{ref.scope, ref.name}, ":")
if !seenEntries[referenceEntry] {
seenEntries[referenceEntry] = true
signatures = append(signatures, referenceEntry)
}
for _, match := range modelConfigsMatchingSignatureRef(cfg.ModelList, ref.name, defaultProvider) {
mc := match.model
entry := strings.Join([]string{
name,
ref.scope,
ref.name,
strconv.Itoa(match.index),
strings.TrimSpace(mc.Provider),
strings.TrimSpace(mc.Model),
@@ -570,76 +612,51 @@ func modelConfigsMatchingSignatureRef(
if len(matches) > 0 {
return matches
}
for i, mc := range modelList {
if mc == nil || strings.TrimSpace(mc.Model) != raw {
continue
}
return []signatureModelConfigMatch{{index: i, model: mc}}
cfg := &config.Config{
Agents: config.AgentsConfig{
Defaults: config.AgentDefaults{Provider: defaultProvider},
},
ModelList: modelList,
}
for i, mc := range modelList {
if modelConfigMatchesBareRef(mc, raw, defaultProvider) {
return []signatureModelConfigMatch{{index: i, model: mc}}
}
resolved, err := providers.ResolveModelConfig(cfg, raw)
if err != nil {
return nil
}
rawRef := providers.ParseModelRef(raw, "")
rawHasProvider := rawRef != nil && hasUnambiguousProviderPrefix(raw) &&
strings.TrimSpace(rawRef.Provider) != "" && strings.TrimSpace(rawRef.Model) != ""
if rawHasProvider {
for i, mc := range modelList {
if modelConfigMatchesProviderRef(mc, raw) {
return []signatureModelConfigMatch{{index: i, model: mc}}
}
for i, modelCfg := range modelList {
if modelConfigsMatchResolvedEntry(modelCfg, resolved, defaultProvider) {
return []signatureModelConfigMatch{{index: i, model: modelCfg}}
}
}
return nil
}
func hasUnambiguousProviderPrefix(raw string) bool {
provider, _, found := strings.Cut(strings.TrimSpace(raw), "/")
if !found {
func modelConfigsMatchResolvedEntry(
left,
right *config.ModelConfig,
defaultProvider string,
) bool {
if left == nil || right == nil || left.IsVirtual() {
return false
}
provider = strings.ToLower(strings.TrimSpace(provider))
if provider == "" {
return false
}
normalizedProvider := providers.NormalizeProvider(provider)
if !providers.IsSupportedModelProvider(normalizedProvider) {
return false
}
return true
leftProvider, leftModel := modelConfigProviderAndID(left, defaultProvider)
rightProvider, rightModel := providers.ExtractProtocol(right)
return left.ModelName == right.ModelName &&
providers.ModelKey(leftProvider, leftModel) == providers.ModelKey(rightProvider, rightModel) &&
left.APIBase == right.APIBase &&
left.APIKey() == right.APIKey() &&
left.Enabled == right.Enabled &&
left.AuthMethod == right.AuthMethod &&
left.ConnectMode == right.ConnectMode
}
func modelConfigMatchesProviderRef(mc *config.ModelConfig, raw string) bool {
func modelConfigProviderAndID(mc *config.ModelConfig, defaultProvider string) (string, string) {
if mc == nil {
return false
return "", ""
}
raw = strings.TrimSpace(raw)
if raw == "" {
return false
if strings.TrimSpace(mc.Provider) != "" {
return providers.ExtractProtocol(mc)
}
rawRef := providers.ParseModelRef(raw, "")
if rawRef == nil || strings.TrimSpace(rawRef.Provider) == "" || strings.TrimSpace(rawRef.Model) == "" {
return false
}
protocol, modelID := providers.ExtractProtocol(mc)
return providers.ModelKey(protocol, modelID) == providers.ModelKey(rawRef.Provider, rawRef.Model)
}
func modelConfigMatchesBareRef(mc *config.ModelConfig, raw string, defaultProvider string) bool {
if mc == nil {
return false
}
raw = strings.TrimSpace(raw)
if raw == "" {
return false
}
protocol, modelID := providers.ExtractProtocol(mc)
if strings.TrimSpace(modelID) != raw {
return false
}
return providers.NormalizeProvider(protocol) == providers.NormalizeProvider(defaultProvider)
return providers.SplitModelProviderAndID(mc.Model, defaultProvider)
}
func computeChannelSignatures(channels config.ChannelsConfig) []string {
+214 -5
View File
@@ -536,6 +536,65 @@ func TestGatewayStartReady_ValidDefaultModel(t *testing.T) {
}
}
func TestGatewayStartReady_RejectsInvalidDuplicateAliasEntry(t *testing.T) {
configPath := filepath.Join(t.TempDir(), "config.json")
cfg := config.DefaultConfig()
cfg.Agents.Defaults.ModelName = "shared"
cfg.ModelList = []*config.ModelConfig{
{
ModelName: "shared",
Provider: "openai",
Model: "gpt-4o",
APIKeys: config.SimpleSecureStrings("test-key"),
},
{
ModelName: "shared",
Provider: "elevenlabs",
Model: "scribe_v1",
APIKeys: config.SimpleSecureStrings("audio-key"),
},
}
if err := config.SaveConfig(configPath, cfg); err != nil {
t.Fatalf("SaveConfig() error = %v", err)
}
h := NewHandler(configPath)
ready, reason, err := h.gatewayStartReady()
if err != nil {
t.Fatalf("gatewayStartReady() error = %v", err)
}
if ready {
t.Fatal("gatewayStartReady() ready = true, want false")
}
if !strings.Contains(reason, "cannot be used as the default chat model") {
t.Fatalf("gatewayStartReady() reason = %q, want duplicate alias rejection", reason)
}
}
func TestGatewayStartReady_RawDefaultModelUsesProviderTemplate(t *testing.T) {
configPath := filepath.Join(t.TempDir(), "config.json")
cfg := config.DefaultConfig()
cfg.Agents.Defaults.ModelName = "openrouter/deepseek/deepseek-v3.2"
cfg.ModelList = []*config.ModelConfig{{
ModelName: "openrouter-template",
Model: "openrouter/auto",
APIBase: "https://openrouter.ai/api/v1",
}}
cfg.ModelList[0].SetAPIKey("test-key")
if err := config.SaveConfig(configPath, cfg); err != nil {
t.Fatalf("SaveConfig() error = %v", err)
}
h := NewHandler(configPath)
ready, reason, err := h.gatewayStartReady()
if err != nil {
t.Fatalf("gatewayStartReady() error = %v", err)
}
if !ready {
t.Fatalf("gatewayStartReady() ready = false, want true (reason=%q)", reason)
}
}
func TestGatewayStartReady_DefaultModelWithoutCredential(t *testing.T) {
configPath := filepath.Join(t.TempDir(), "config.json")
cfg := config.DefaultConfig()
@@ -1138,6 +1197,109 @@ func TestGatewayStatusRequiresRestartAfterDefaultModelChange(t *testing.T) {
}
}
func TestGatewayStatusRequiresRestartAfterFallbackOrderChange(t *testing.T) {
resetGatewayTestState(t)
configPath := filepath.Join(t.TempDir(), "config.json")
cfg := config.DefaultConfig()
cfg.ModelList = []*config.ModelConfig{
{
ModelName: "primary",
Provider: "openai",
Model: "gpt-4o",
APIKeys: config.SimpleSecureStrings("sk-primary"),
},
{
ModelName: "backup-a",
Provider: "anthropic",
Model: "claude-sonnet-4.6",
APIKeys: config.SimpleSecureStrings("sk-backup-a"),
},
{
ModelName: "backup-b",
Provider: "gemini",
Model: "gemini-2.5-pro",
APIKeys: config.SimpleSecureStrings("sk-backup-b"),
},
}
cfg.Agents.Defaults.ModelName = "primary"
cfg.Agents.Defaults.ModelFallbacks = []string{"backup-a", "backup-b"}
if err := config.SaveConfig(configPath, cfg); err != nil {
t.Fatalf("SaveConfig() error = %v", err)
}
h := NewHandler(configPath)
mux := http.NewServeMux()
h.RegisterRoutes(mux)
process, err := os.FindProcess(os.Getpid())
if err != nil {
t.Fatalf("FindProcess() error = %v", err)
}
bootSignature := computeConfigSignature(cfg)
gateway.mu.Lock()
gateway.cmd = &exec.Cmd{Process: process}
gateway.bootDefaultModel = cfg.ModelList[0].ModelName
gateway.bootConfigSignature = bootSignature
setGatewayRuntimeStatusLocked("running")
gateway.mu.Unlock()
updatedCfg, err := config.LoadConfig(configPath)
if err != nil {
t.Fatalf("LoadConfig() error = %v", err)
}
updatedCfg.Agents.Defaults.ModelFallbacks = []string{"backup-b", "backup-a"}
if err := config.SaveConfig(configPath, updatedCfg); err != nil {
t.Fatalf("SaveConfig() error = %v", err)
}
gatewayHealthGet = func(string, time.Duration) (*http.Response, error) {
return mockGatewayHealthResponse(http.StatusOK, os.Getpid()), nil
}
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/gateway/status", nil)
mux.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK)
}
var body map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatalf("unmarshal response: %v", err)
}
if got := body["gateway_status"]; got != "running" {
t.Fatalf("gateway_status = %#v, want %q", got, "running")
}
if got := body["gateway_restart_required"]; got != true {
t.Fatalf("gateway_restart_required = %#v, want true", got)
}
}
func TestModelStreamingSignaturesIncludeRawFallbackOrder(t *testing.T) {
cfg := config.DefaultConfig()
cfg.ModelList = []*config.ModelConfig{openAIModelConfig("primary")}
cfg.Agents.Defaults.ModelName = "primary"
cfg.Agents.Defaults.ModelFallbacks = []string{
"openrouter/fallback-a",
"anthropic/fallback-b",
}
before := strings.Join(computeModelStreamingSignatures(cfg), "\n")
cfg.Agents.Defaults.ModelFallbacks = []string{
"anthropic/fallback-b",
"openrouter/fallback-a",
}
after := strings.Join(computeModelStreamingSignatures(cfg), "\n")
if before == after {
t.Fatalf("raw fallback reorder did not change signatures:\n%s", before)
}
}
func TestGatewayStatusRequiresRestartAfterToolChange(t *testing.T) {
resetGatewayTestState(t)
@@ -1754,7 +1916,7 @@ func TestConfigSignatureIncludesDefaultProviderPrefixedRefWithSplitConfig(t *tes
}
}
func TestConfigSignatureBareModelRefUsesExactModelBeforeDefaultProviderModelID(t *testing.T) {
func TestConfigSignatureBareModelRefUsesDefaultProviderModelID(t *testing.T) {
cfg := config.DefaultConfig()
cfg.ModelList = []*config.ModelConfig{
{
@@ -1777,15 +1939,29 @@ func TestConfigSignatureBareModelRefUsesExactModelBeforeDefaultProviderModelID(t
cfg.ModelList[0].Streaming = config.ModelStreamingConfig{Enabled: true}
afterExactModelChange := computeConfigSignature(cfg)
if before == afterExactModelChange {
t.Fatal("config signature should change when the exact bare model entry changes streaming")
if before != afterExactModelChange {
t.Fatal("config signature should not change for a bare model entry on another provider")
}
cfg.ModelList[1].Streaming = config.ModelStreamingConfig{Enabled: true}
afterDefaultProviderModelChange := computeConfigSignature(cfg)
if afterExactModelChange != afterDefaultProviderModelChange {
t.Fatal("config signature should not change when a shadowed default-provider model id changes streaming")
if afterExactModelChange == afterDefaultProviderModelChange {
t.Fatal("config signature should change when the default-provider model id changes streaming")
}
}
func TestConfigSignatureChangesWithDefaultProvider(t *testing.T) {
cfg := config.DefaultConfig()
cfg.Agents.Defaults.Provider = "openai"
cfg.Agents.Defaults.ModelName = "gpt-4o"
cfg.ModelList = []*config.ModelConfig{{ModelName: "legacy", Model: "gpt-4o"}}
before := computeConfigSignature(cfg)
cfg.Agents.Defaults.Provider = "openrouter"
after := computeConfigSignature(cfg)
if before == after {
t.Fatal("config signature should change when the effective default provider changes")
}
}
@@ -2383,3 +2559,36 @@ func TestFindPicoclawBinary_EnvOverride_InvalidPath(t *testing.T) {
t.Errorf("FindPicoclawBinary() returned invalid env path %q, expected fallback", got)
}
}
func TestModelConfigsMatchingSignatureRef_BareUsesDefaultProvider(t *testing.T) {
models := []*config.ModelConfig{
{ModelName: "openrouter-model", Provider: "openrouter", Model: "gpt-4o"},
{ModelName: "openai-model", Provider: "openai", Model: "gpt-4o"},
}
matches := modelConfigsMatchingSignatureRef(models, "gpt-4o", "openai")
if len(matches) != 1 || matches[0].model.ModelName != "openai-model" {
t.Fatalf("matches = %#v, want openai-model", matches)
}
}
func TestModelConfigsMatchingSignatureRefUsesResolverScore(t *testing.T) {
models := []*config.ModelConfig{
{
ModelName: "disabled",
Provider: "openrouter",
Model: "target",
},
{
ModelName: "enabled",
Provider: "openrouter",
Model: "target",
Enabled: true,
},
}
matches := modelConfigsMatchingSignatureRef(models, "openrouter/target", "openai")
if len(matches) != 1 || matches[0].index != 1 {
t.Fatalf("matches = %#v, want resolver-selected index 1", matches)
}
}
+19 -2
View File
@@ -89,7 +89,8 @@ func hasModelConfiguration(m *config.ModelConfig) bool {
authMethod := strings.ToLower(strings.TrimSpace(m.AuthMethod))
apiKey := strings.TrimSpace(m.APIKey())
if authMethod == "oauth" || authMethod == "token" {
usesStoredAuth := authMethod == "oauth" || authMethod == "token"
if usesStoredAuth {
if configured, checked := hasStoredOAuthCredential(m); checked {
return configured
}
@@ -109,7 +110,23 @@ func hasModelConfiguration(m *config.ModelConfig) bool {
return true
}
return apiKey != ""
if apiKey != "" {
return true
}
if usesStoredAuth {
return false
}
apiBase := strings.TrimSpace(m.APIBase)
if apiBase == "" {
return false
}
switch providers.NormalizeProvider(protocol) {
case "anthropic", "anthropic-messages", "alibaba-coding-anthropic":
return false
}
defaultBase := providers.DefaultAPIBaseForProtocol(protocol)
return defaultBase == "" ||
normalizeAPIBaseForCompare(apiBase) != normalizeAPIBaseForCompare(defaultBase)
}
func hasStoredOAuthCredential(m *config.ModelConfig) (bool, bool) {
+570 -58
View File
@@ -21,11 +21,13 @@ import (
// registerModelRoutes binds model list management endpoints to the ServeMux.
func (h *Handler) registerModelRoutes(mux *http.ServeMux) {
mux.HandleFunc("GET /api/models", h.handleListModels)
mux.HandleFunc("GET /api/models/default-chain", h.handleGetDefaultChain)
mux.HandleFunc("POST /api/models/fetch", h.handleFetchModels)
mux.HandleFunc("GET /api/models/catalog", h.handleListCatalogs)
mux.HandleFunc("DELETE /api/models/catalog/{id}", h.handleDeleteCatalog)
mux.HandleFunc("POST /api/models", h.handleAddModel)
mux.HandleFunc("POST /api/models/default", h.handleSetDefaultModel)
mux.HandleFunc("PUT /api/models/default-chain", h.handleUpdateDefaultChain)
mux.HandleFunc("PUT /api/models/{index}", h.handleUpdateModel)
mux.HandleFunc("DELETE /api/models/{index}", h.handleDeleteModel)
mux.HandleFunc("POST /api/models/{index}/test", h.handleTestModel)
@@ -63,12 +65,27 @@ type modelResponse struct {
DefaultModelAllowed bool `json:"default_model_allowed"`
}
func normalizeStoredModelConfig(mc *config.ModelConfig) bool {
type defaultChainResponse struct {
DefaultModel string `json:"default_model"`
FallbackChain []string `json:"fallback_chain"`
}
type defaultChainRequest struct {
DefaultModel string `json:"default_model"`
FallbackChain []string `json:"fallback_chain"`
}
func normalizeStoredModelConfig(mc *config.ModelConfig, defaultProvider string) bool {
if mc == nil {
return false
}
changed := false
modelName := strings.TrimSpace(mc.ModelName)
if modelName != mc.ModelName {
mc.ModelName = modelName
changed = true
}
model := strings.TrimSpace(mc.Model)
if model != mc.Model {
mc.Model = model
@@ -111,7 +128,7 @@ func normalizeStoredModelConfig(mc *config.ModelConfig) bool {
return changed
}
effectiveProvider, modelID := providers.SplitModelProviderAndID(model, "openai")
effectiveProvider, modelID := providers.SplitModelProviderAndID(model, defaultProvider)
if effectiveProvider == "" {
return changed
}
@@ -126,16 +143,17 @@ func normalizeStoredModelConfig(mc *config.ModelConfig) bool {
return changed
}
func normalizeIncomingModelConfig(mc *config.ModelConfig) {
func normalizeIncomingModelConfig(mc *config.ModelConfig, defaultProvider string) {
if mc == nil {
return
}
mc.ModelName = strings.TrimSpace(mc.ModelName)
mc.Model = strings.TrimSpace(mc.Model)
mc.Provider = strings.TrimSpace(mc.Provider)
mc.AuthMethod = strings.ToLower(strings.TrimSpace(mc.AuthMethod))
if mc.Provider == "" {
mc.Provider, mc.Model = providers.SplitModelProviderAndID(mc.Model, "openai")
mc.Provider, mc.Model = providers.SplitModelProviderAndID(mc.Model, defaultProvider)
} else {
mc.Provider = providers.NormalizeProvider(mc.Provider)
if mc.Provider == "elevenlabs" {
@@ -188,8 +206,8 @@ func modelProviderOptionsForResponse() []providers.ModelProviderOption {
return options
}
func defaultModelAllowedForModelConfig(mc *config.ModelConfig) bool {
provider, _ := providers.ExtractProtocol(mc)
func defaultModelAllowedForModelConfig(mc *config.ModelConfig, defaultProvider string) bool {
provider, _ := modelConfigProviderAndID(mc, defaultProvider)
return providers.IsDefaultModelProvider(provider)
}
@@ -227,14 +245,346 @@ func normalizeStoredModelProviders(cfg *config.Config) bool {
}
changed := false
defaultProvider := defaultChainProvider(cfg)
for _, model := range cfg.ModelList {
if normalizeStoredModelConfig(model) {
if normalizeStoredModelConfig(model, defaultProvider) {
changed = true
}
}
return changed
}
func normalizeStoredModelNames(cfg *config.Config) bool {
if cfg == nil {
return false
}
changed := false
for _, model := range cfg.ModelList {
if model == nil {
continue
}
modelName := strings.TrimSpace(model.ModelName)
if modelName != model.ModelName {
model.ModelName = modelName
changed = true
}
}
return changed
}
func trimModelNameList(names []string) []string {
trimmed := make([]string, 0, len(names))
for _, name := range names {
name = strings.TrimSpace(name)
if name == "" {
continue
}
trimmed = append(trimmed, name)
}
return trimmed
}
func dedupeModelNameList(names []string) []string {
if len(names) == 0 {
return nil
}
seen := make(map[string]struct{}, len(names))
deduped := make([]string, 0, len(names))
for _, name := range names {
if _, ok := seen[name]; ok {
continue
}
seen[name] = struct{}{}
deduped = append(deduped, name)
}
return deduped
}
func modelConfigsByName(cfg *config.Config) map[string][]*config.ModelConfig {
models := make(map[string][]*config.ModelConfig, len(cfg.ModelList))
for _, model := range cfg.ModelList {
if model == nil {
continue
}
name := strings.TrimSpace(model.ModelName)
if name == "" {
continue
}
models[name] = append(models[name], model)
}
return models
}
func modelConfigsByNameExceptIndex(
cfg *config.Config,
modelName string,
exceptIndex int,
) []*config.ModelConfig {
modelName = strings.TrimSpace(modelName)
if cfg == nil || modelName == "" {
return nil
}
models := make([]*config.ModelConfig, 0, 1)
for i, model := range cfg.ModelList {
if i == exceptIndex || model == nil {
continue
}
if strings.TrimSpace(model.ModelName) == modelName {
models = append(models, model)
}
}
return models
}
func validateDefaultChainModelSet(
modelName string,
models []*config.ModelConfig,
defaultContext bool,
defaultProvider string,
) error {
if len(models) == 0 {
if defaultContext {
return fmt.Errorf("default model %q not found in model_list", modelName)
}
return fmt.Errorf("fallback model %q not found in model_list", modelName)
}
for _, modelCfg := range models {
if modelCfg.IsVirtual() {
if defaultContext {
return fmt.Errorf("cannot set virtual model %q as default", modelName)
}
return fmt.Errorf("cannot add virtual model %q to fallback_chain", modelName)
}
if !defaultModelAllowedForModelConfig(modelCfg, defaultProvider) {
if defaultContext {
return fmt.Errorf("model %q cannot be used as the default chat model", modelName)
}
return fmt.Errorf("model %q cannot be used in the fallback chain", modelName)
}
effectiveModelCfg := modelCfg
if strings.TrimSpace(modelCfg.Provider) == "" {
clone := *modelCfg
normalizeStoredModelConfig(&clone, defaultProvider)
effectiveModelCfg = &clone
}
if !hasModelConfiguration(effectiveModelCfg) {
return rawModelConfigurationError(modelName, defaultContext)
}
}
return nil
}
func validateDefaultChainReference(
cfg *config.Config,
modelName string,
models []*config.ModelConfig,
defaultContext bool,
) error {
if len(models) > 0 {
return validateDefaultChainModelSet(
modelName,
models,
defaultContext,
defaultChainProvider(cfg),
)
}
resolved, err := providers.ResolveModelConfig(cfg, modelName)
if err != nil || resolved == nil {
ref := providers.ParseModelRef(modelName, defaultChainProvider(cfg))
if ref != nil &&
strings.TrimSpace(ref.Provider) != "" &&
strings.TrimSpace(ref.Model) != "" &&
!providers.IsDefaultModelProvider(ref.Provider) {
if defaultContext {
return fmt.Errorf("model %q cannot be used as the default chat model", modelName)
}
return fmt.Errorf("model %q cannot be used in the fallback chain", modelName)
}
if ref != nil &&
strings.TrimSpace(ref.Provider) != "" &&
strings.TrimSpace(ref.Model) != "" &&
providers.IsDefaultModelProvider(ref.Provider) {
return rawModelConfigurationError(modelName, defaultContext)
}
return validateDefaultChainModelSet(
modelName,
nil,
defaultContext,
defaultChainProvider(cfg),
)
}
if err := validateDefaultChainModelSet(
modelName,
[]*config.ModelConfig{resolved},
defaultContext,
defaultChainProvider(cfg),
); err != nil {
return err
}
if !rawTemplateHasConfiguration(resolved) {
return rawModelConfigurationError(modelName, defaultContext)
}
return nil
}
func rawTemplateHasConfiguration(modelCfg *config.ModelConfig) bool {
return hasModelConfiguration(modelCfg)
}
func rawModelConfigurationError(modelName string, defaultContext bool) error {
if defaultContext {
return fmt.Errorf("default model %q has no configured provider", modelName)
}
return fmt.Errorf("fallback model %q has no configured provider", modelName)
}
func defaultChainProvider(cfg *config.Config) string {
if cfg != nil && strings.TrimSpace(cfg.Agents.Defaults.Provider) != "" {
return providers.NormalizeProvider(cfg.Agents.Defaults.Provider)
}
return "openai"
}
func defaultChainReferenceIdentity(cfg *config.Config, modelName string) string {
modelName = strings.TrimSpace(modelName)
if modelName == "" {
return ""
}
defaultProvider := defaultChainProvider(cfg)
var modelList []*config.ModelConfig
if cfg != nil {
modelList = cfg.ModelList
}
matches := modelConfigsMatchingSignatureRef(modelList, modelName, defaultProvider)
if len(matches) > 0 {
modelCfg := matches[0].model
if alias := strings.TrimSpace(modelCfg.ModelName); alias != "" {
return "model_name:" + alias
}
provider, modelID := providers.ExtractProtocol(modelCfg)
return providers.ModelKey(provider, modelID)
}
ref := providers.ParseModelRef(modelName, defaultProvider)
if ref == nil {
return ""
}
return providers.ModelKey(ref.Provider, ref.Model)
}
func validateDefaultModelChain(
cfg *config.Config,
defaultModel string,
fallbacks []string,
) ([]string, error) {
defaultModel = strings.TrimSpace(defaultModel)
fallbacks = dedupeModelNameList(trimModelNameList(fallbacks))
if cfg == nil {
return nil, fmt.Errorf("config is required")
}
if defaultModel == "" && len(fallbacks) > 0 {
return nil, fmt.Errorf("default_model is required when fallback_chain is not empty")
}
modelsByName := modelConfigsByName(cfg)
defaultIdentity := ""
if defaultModel != "" {
if err := validateDefaultChainReference(
cfg,
defaultModel,
modelsByName[defaultModel],
true,
); err != nil {
return nil, err
}
defaultIdentity = defaultChainReferenceIdentity(cfg, defaultModel)
}
seenIdentities := make(map[string]struct{}, len(fallbacks))
validated := make([]string, 0, len(fallbacks))
for _, fallback := range fallbacks {
if fallback == defaultModel {
return nil, fmt.Errorf("default model %q cannot also appear in fallback_chain", defaultModel)
}
if err := validateDefaultChainReference(cfg, fallback, modelsByName[fallback], false); err != nil {
return nil, err
}
identity := defaultChainReferenceIdentity(cfg, fallback)
if identity != "" && identity == defaultIdentity {
return nil, fmt.Errorf(
"fallback model %q resolves to the same runtime model as default model %q",
fallback,
defaultModel,
)
}
if _, exists := seenIdentities[identity]; identity != "" && exists {
continue
}
if identity != "" {
seenIdentities[identity] = struct{}{}
}
validated = append(validated, fallback)
}
return validated, nil
}
func normalizeDefaultChainReferences(cfg *config.Config) {
if cfg == nil {
return
}
defaultModel := strings.TrimSpace(cfg.Agents.Defaults.ModelName)
fallbacks := dedupeModelNameList(trimModelNameList(cfg.Agents.Defaults.ModelFallbacks))
modelsByName := modelConfigsByName(cfg)
defaultIdentity := ""
if defaultModel != "" {
if err := validateDefaultChainReference(
cfg,
defaultModel,
modelsByName[defaultModel],
true,
); err != nil {
defaultModel = ""
}
defaultIdentity = defaultChainReferenceIdentity(cfg, defaultModel)
}
if defaultModel == "" {
cfg.Agents.Defaults.ModelName = ""
cfg.Agents.Defaults.ModelFallbacks = nil
return
}
seenIdentities := make(map[string]struct{}, len(fallbacks))
validated := make([]string, 0, len(fallbacks))
for _, fallback := range fallbacks {
if fallback == defaultModel {
continue
}
if err := validateDefaultChainReference(cfg, fallback, modelsByName[fallback], false); err != nil {
continue
}
identity := defaultChainReferenceIdentity(cfg, fallback)
if identity != "" && identity == defaultIdentity {
continue
}
if _, exists := seenIdentities[identity]; identity != "" && exists {
continue
}
if identity != "" {
seenIdentities[identity] = struct{}{}
}
validated = append(validated, fallback)
}
cfg.Agents.Defaults.ModelName = defaultModel
cfg.Agents.Defaults.ModelFallbacks = validated
}
// handleListModels returns all model_list entries with masked API keys.
//
// GET /api/models
@@ -248,8 +598,10 @@ func (h *Handler) handleListModels(w http.ResponseWriter, r *http.Request) {
// Normalize legacy provider/model storage in memory so GET can round-trip
// through the current API shape without mutating the on-disk config.
normalizeStoredModelProviders(cfg)
normalizeDefaultChainReferences(cfg)
defaultModel := cfg.Agents.Defaults.GetModelName()
fallbackChain := cfg.Agents.Defaults.ModelFallbacks
modelStatuses := make([]modelConfigurationSummary, len(cfg.ModelList))
var wg sync.WaitGroup
@@ -289,7 +641,7 @@ func (h *Handler) handleListModels(w http.ResponseWriter, r *http.Request) {
Status: modelStatuses[i].Status,
IsDefault: m.ModelName == defaultModel,
IsVirtual: m.IsVirtual(),
DefaultModelAllowed: defaultModelAllowedForModelConfig(m),
DefaultModelAllowed: defaultModelAllowedForModelConfig(m, defaultChainProvider(cfg)),
})
}
@@ -298,10 +650,33 @@ func (h *Handler) handleListModels(w http.ResponseWriter, r *http.Request) {
"models": models,
"total": len(models),
"default_model": defaultModel,
"default_provider": defaultChainProvider(cfg),
"fallback_chain": fallbackChain,
"provider_options": modelProviderOptionsForResponse(),
})
}
// handleGetDefaultChain returns the persisted default model and fallback chain.
//
// GET /api/models/default-chain
func (h *Handler) handleGetDefaultChain(w http.ResponseWriter, r *http.Request) {
cfg, err := config.LoadConfig(h.configPath)
if err != nil {
http.Error(w, fmt.Sprintf("Failed to load config: %v", err), http.StatusInternalServerError)
return
}
normalizeStoredModelProviders(cfg)
normalizeDefaultChainReferences(cfg)
resp := defaultChainResponse{
DefaultModel: strings.TrimSpace(cfg.Agents.Defaults.GetModelName()),
FallbackChain: trimModelNameList(cfg.Agents.Defaults.ModelFallbacks),
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(resp)
}
// handleAddModel appends a new model configuration entry.
//
// POST /api/models
@@ -324,25 +699,27 @@ func (h *Handler) handleAddModel(w http.ResponseWriter, r *http.Request) {
return
}
normalizeIncomingModelConfig(&mc.ModelConfig)
if err = validateIncomingModelConfig(&mc.ModelConfig, nil); err != nil {
http.Error(w, fmt.Sprintf("Validation error: %v", err), http.StatusBadRequest)
return
}
if mc.APIKey != "" {
mc.ModelConfig.SetAPIKey(mc.APIKey)
}
h.configMu.Lock()
defer h.configMu.Unlock()
cfg, err := config.LoadConfig(h.configPath)
if err != nil {
http.Error(w, fmt.Sprintf("Failed to load config: %v", err), http.StatusInternalServerError)
return
}
normalizeIncomingModelConfig(&mc.ModelConfig, defaultChainProvider(cfg))
if err = validateIncomingModelConfig(&mc.ModelConfig, nil); err != nil {
http.Error(w, fmt.Sprintf("Validation error: %v", err), http.StatusBadRequest)
return
}
cfg.ModelList = append(cfg.ModelList, &mc.ModelConfig)
normalizeStoredModelProviders(cfg)
normalizeDefaultChainReferences(cfg)
if err := config.SaveConfig(h.configPath, cfg); err != nil {
http.Error(w, fmt.Sprintf("Failed to save config: %v", err), http.StatusInternalServerError)
@@ -393,16 +770,21 @@ func (h *Handler) handleUpdateModel(w http.ResponseWriter, r *http.Request) {
return
}
h.configMu.Lock()
defer h.configMu.Unlock()
cfg, err := config.LoadConfig(h.configPath)
if err != nil {
http.Error(w, fmt.Sprintf("Failed to load config: %v", err), http.StatusInternalServerError)
return
}
normalizeStoredModelProviders(cfg)
if idx < 0 || idx >= len(cfg.ModelList) {
http.Error(w, fmt.Sprintf("Index %d out of range (0-%d)", idx, len(cfg.ModelList)-1), http.StatusNotFound)
return
}
oldModelName := strings.TrimSpace(cfg.ModelList[idx].ModelName)
// Preserve the existing API key when the caller omits it (empty string).
// This lets the UI update api_base / proxy without clearing the stored secret.
@@ -463,20 +845,44 @@ func (h *Handler) handleUpdateModel(w http.ResponseWriter, r *http.Request) {
}
}
normalizeIncomingModelConfig(&mc.ModelConfig)
normalizeIncomingModelConfig(&mc.ModelConfig, defaultChainProvider(cfg))
if err = validateIncomingModelConfig(&mc.ModelConfig, cfg.ModelList[idx]); err != nil {
http.Error(w, fmt.Sprintf("Validation error: %v", err), http.StatusBadRequest)
return
}
if cfg.Agents.Defaults.ModelName == cfg.ModelList[idx].ModelName &&
!defaultModelAllowedForModelConfig(&mc.ModelConfig) {
// Allow users to recover from legacy/invalid defaults by saving the model
// and clearing the default chat model reference in the same write.
cfg.Agents.Defaults.ModelName = ""
newModelName := strings.TrimSpace(mc.ModelConfig.ModelName)
defaultReferenceRenamed := false
fallbackReferenceRenamed := false
if oldModelName != "" && newModelName != "" && oldModelName != newModelName {
remainingOldNameModels := modelConfigsByNameExceptIndex(cfg, oldModelName, idx)
if err := validateDefaultChainModelSet(
oldModelName,
remainingOldNameModels,
true,
defaultChainProvider(cfg),
); err != nil {
defaultReferenceRenamed = true
if strings.TrimSpace(cfg.Agents.Defaults.ModelName) == oldModelName {
cfg.Agents.Defaults.ModelName = newModelName
}
}
if err := validateDefaultChainModelSet(
oldModelName,
remainingOldNameModels,
false,
defaultChainProvider(cfg),
); err != nil {
fallbackReferenceRenamed = true
cfg.Agents.Defaults.ModelFallbacks = replaceModelName(
cfg.Agents.Defaults.ModelFallbacks,
oldModelName,
newModelName,
)
}
}
cfg.ModelList[idx] = &mc.ModelConfig
normalizeStoredModelProviders(cfg)
normalizeDefaultChainReferences(cfg)
logger.Debugf("update model config: %#v", mc.ModelConfig)
@@ -486,7 +892,16 @@ func (h *Handler) handleUpdateModel(w http.ResponseWriter, r *http.Request) {
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{"status": "ok"})
response := map[string]any{"status": "ok"}
if oldModelName != "" && newModelName != "" && oldModelName != newModelName {
response["reference_rename"] = map[string]any{
"from": oldModelName,
"to": newModelName,
"default": defaultReferenceRenamed,
"fallback": fallbackReferenceRenamed,
}
}
json.NewEncoder(w).Encode(response)
}
// handleDeleteModel removes a model configuration entry at the given index.
@@ -499,25 +914,50 @@ func (h *Handler) handleDeleteModel(w http.ResponseWriter, r *http.Request) {
return
}
h.configMu.Lock()
defer h.configMu.Unlock()
cfg, err := config.LoadConfig(h.configPath)
if err != nil {
http.Error(w, fmt.Sprintf("Failed to load config: %v", err), http.StatusInternalServerError)
return
}
normalizeStoredModelNames(cfg)
if idx < 0 || idx >= len(cfg.ModelList) {
http.Error(w, fmt.Sprintf("Index %d out of range (0-%d)", idx, len(cfg.ModelList)-1), http.StatusNotFound)
return
}
deletedModelName := cfg.ModelList[idx].ModelName
deletedModelName := strings.TrimSpace(cfg.ModelList[idx].ModelName)
cfg.ModelList = append(cfg.ModelList[:idx], cfg.ModelList[idx+1:]...)
// If the deleted model was the default, clear it.
if cfg.Agents.Defaults.ModelName == deletedModelName {
cfg.Agents.Defaults.ModelName = ""
if deletedModelName != "" {
remainingModels := modelConfigsByName(cfg)[deletedModelName]
if strings.TrimSpace(cfg.Agents.Defaults.ModelName) == deletedModelName {
if err := validateDefaultChainModelSet(
deletedModelName,
remainingModels,
true,
defaultChainProvider(cfg),
); err != nil {
cfg.Agents.Defaults.ModelName = ""
}
}
if err := validateDefaultChainModelSet(
deletedModelName,
remainingModels,
false,
defaultChainProvider(cfg),
); err != nil {
cfg.Agents.Defaults.ModelFallbacks = removeModelName(
cfg.Agents.Defaults.ModelFallbacks,
deletedModelName,
)
}
}
normalizeDefaultChainReferences(cfg)
if err := config.SaveConfig(h.configPath, cfg); err != nil {
http.Error(w, fmt.Sprintf("Failed to save config: %v", err), http.StatusInternalServerError)
@@ -528,6 +968,38 @@ func (h *Handler) handleDeleteModel(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(map[string]string{"status": "ok"})
}
func removeModelName(names []string, target string) []string {
target = strings.TrimSpace(target)
if target == "" || len(names) == 0 {
return names
}
filtered := make([]string, 0, len(names))
for _, name := range names {
if strings.TrimSpace(name) == target {
continue
}
filtered = append(filtered, name)
}
return filtered
}
func replaceModelName(names []string, oldName string, newName string) []string {
oldName = strings.TrimSpace(oldName)
newName = strings.TrimSpace(newName)
if oldName == "" || oldName == newName || len(names) == 0 {
return names
}
replaced := make([]string, 0, len(names))
for _, name := range names {
if strings.TrimSpace(name) == oldName {
replaced = append(replaced, newName)
continue
}
replaced = append(replaced, name)
}
return replaced
}
// handleSetDefaultModel sets the default model for all agents.
//
// POST /api/models/default
@@ -547,50 +1019,41 @@ func (h *Handler) handleSetDefaultModel(w http.ResponseWriter, r *http.Request)
return
}
if req.ModelName == "" {
modelName := strings.TrimSpace(req.ModelName)
if modelName == "" {
http.Error(w, "model_name is required", http.StatusBadRequest)
return
}
h.configMu.Lock()
defer h.configMu.Unlock()
cfg, err := config.LoadConfig(h.configPath)
if err != nil {
http.Error(w, fmt.Sprintf("Failed to load config: %v", err), http.StatusInternalServerError)
return
}
normalizeStoredModelNames(cfg)
// Verify the model_name exists in model_list and is not a virtual model
found := false
isVirtual := false
for _, m := range cfg.ModelList {
if m.ModelName == req.ModelName {
found = true
isVirtual = m.IsVirtual()
break
// Keep this legacy endpoint alias-only. Raw references are managed by the
// default-chain endpoint and may already exist in persisted configuration.
if err := validateDefaultChainModelSet(
modelName,
modelConfigsByName(cfg)[modelName],
true,
defaultChainProvider(cfg),
); err != nil {
status := http.StatusBadRequest
if strings.Contains(err.Error(), "not found in model_list") {
status = http.StatusNotFound
}
}
if !found {
http.Error(w, fmt.Sprintf("Model %q not found in model_list", req.ModelName), http.StatusNotFound)
http.Error(w, err.Error(), status)
return
}
if isVirtual {
http.Error(w, fmt.Sprintf("Cannot set virtual model %q as default", req.ModelName), http.StatusBadRequest)
return
}
for _, m := range cfg.ModelList {
if m.ModelName == req.ModelName {
if !defaultModelAllowedForModelConfig(m) {
http.Error(
w,
fmt.Sprintf("Model %q cannot be used as the default chat model", req.ModelName),
http.StatusBadRequest,
)
return
}
break
}
}
cfg.Agents.Defaults.ModelName = req.ModelName
cfg.Agents.Defaults.ModelName = modelName
cfg.Agents.Defaults.ModelFallbacks = removeModelName(cfg.Agents.Defaults.ModelFallbacks, modelName)
normalizeDefaultChainReferences(cfg)
if err := config.SaveConfig(h.configPath, cfg); err != nil {
http.Error(w, fmt.Sprintf("Failed to save config: %v", err), http.StatusInternalServerError)
@@ -600,7 +1063,56 @@ func (h *Handler) handleSetDefaultModel(w http.ResponseWriter, r *http.Request)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{
"status": "ok",
"default_model": req.ModelName,
"default_model": modelName,
})
}
// handleUpdateDefaultChain updates the persisted default model and fallback chain.
//
// PUT /api/models/default-chain
func (h *Handler) handleUpdateDefaultChain(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))
if err != nil {
http.Error(w, "Failed to read request body", http.StatusBadRequest)
return
}
defer r.Body.Close()
var req defaultChainRequest
if err = json.Unmarshal(body, &req); err != nil {
http.Error(w, fmt.Sprintf("Invalid JSON: %v", err), http.StatusBadRequest)
return
}
h.configMu.Lock()
defer h.configMu.Unlock()
cfg, err := config.LoadConfig(h.configPath)
if err != nil {
http.Error(w, fmt.Sprintf("Failed to load config: %v", err), http.StatusInternalServerError)
return
}
normalizeStoredModelNames(cfg)
defaultModel := strings.TrimSpace(req.DefaultModel)
fallbacks, err := validateDefaultModelChain(cfg, defaultModel, req.FallbackChain)
if err != nil {
http.Error(w, fmt.Sprintf("Validation error: %v", err), http.StatusBadRequest)
return
}
cfg.Agents.Defaults.ModelName = defaultModel
cfg.Agents.Defaults.ModelFallbacks = fallbacks
if err := config.SaveConfig(h.configPath, cfg); err != nil {
http.Error(w, fmt.Sprintf("Failed to save config: %v", err), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(defaultChainResponse{
DefaultModel: defaultModel,
FallbackChain: fallbacks,
})
}
File diff suppressed because it is too large. Load diff
+10 -7
View File
@@ -20,13 +20,16 @@ type Handler struct {
serverAllowLocalhostBypass bool
serverTrustedProxyCIDRs []string
debug bool
oauthMu sync.Mutex
oauthFlows map[string]*oauthFlow
oauthState map[string]string
weixinMu sync.Mutex
weixinFlows map[string]*weixinFlow
wecomMu sync.Mutex
wecomFlows map[string]*wecomFlow
// Serializes model-related config writes. Other config endpoints still
// coordinate their own load-modify-save cycles.
configMu sync.Mutex
oauthMu sync.Mutex
oauthFlows map[string]*oauthFlow
oauthState map[string]string
weixinMu sync.Mutex
weixinFlows map[string]*weixinFlow
wecomMu sync.Mutex
wecomFlows map[string]*wecomFlow
}
// NewHandler creates an instance of the API handler.