Open source AI coding agent. Designed for large projects and real world tasks.
Go aiai-agentsai-developer-toolsai-toolsclicommand-linedeveloper-toolsgitgolanggpt-4llmopenaipolyglot-programmingterminalterminal-basedterminal-ui
fixes for 'models import' command. working on testing provider fallback
Dane Schneider804d4e6961f0
diff --git a/app/cli/cmd/model_packs.go b/app/cli/cmd/model_packs.goindex 324a5aef..0a542951 100644--- a/app/cli/cmd/model_packs.go+++ b/app/cli/cmd/model_packs.go@@ -26,7 +26,7 @@ var modelPacksCmd = &cobra.Command{var createModelPackCmd = &cobra.Command{Use: "create",Short: "Create a model pack",- Run: customModelsNotImplemented,+ Run: customModelsCreateNotImplemented,}var deleteModelPackCmd = &cobra.Command{@@ -40,7 +40,7 @@ var deleteModelPackCmd = &cobra.Command{var updateModelPackCmd = &cobra.Command{Use: "update",Short: "Update a model pack by name",- Run: customModelsNotImplemented,+ Run: customModelsCreateNotImplemented,}var showModelPackCmd = &cobra.Command{diff --git a/app/cli/cmd/model_providers.go b/app/cli/cmd/model_providers.goindex c89b4c5e..af0ef46a 100644--- a/app/cli/cmd/model_providers.go+++ b/app/cli/cmd/model_providers.go@@ -36,14 +36,14 @@ var addProviderCmd = &cobra.Command{Use: "add",Aliases: []string{"create"},Short: "Add a custom model provider",- Run: customModelsNotImplemented,+ Run: customModelsCreateNotImplemented,}var updateProviderCmd = &cobra.Command{Use: "update",Aliases: []string{"edit"},Short: "Update a custom model provider",- Run: customModelsNotImplemented,+ Run: customModelsCreateNotImplemented,}func init() {diff --git a/app/cli/cmd/models.go b/app/cli/cmd/models.goindex 050eb3ee..e45344e9 100644--- a/app/cli/cmd/models.go+++ b/app/cli/cmd/models.go@@ -77,14 +77,14 @@ var addCustomModelCmd = &cobra.Command{Use: "add",Aliases: []string{"create"},Short: "Add a custom model",- Run: customModelsNotImplemented,+ Run: customModelsCreateNotImplemented,}var updateCustomModelCmd = &cobra.Command{Use: "update",Aliases: []string{"edit"},Short: "Update a custom model",- Run: customModelsNotImplemented,+ Run: customModelsUpdateNotImplemented,}var deleteCustomModelCmd = &cobra.Command{@@ -100,57 +100,86 @@ func importCustomModels(cmd *cobra.Command, args []string) {var jsonFile string- if len(args) == 1 {- jsonFile = args[0]- } else if updateModels {- term.StartSpinner("")+ term.StartSpinner("")- errCh := make(chan *shared.ApiError, 3)- var modelsInput *shared.ModelsInput+ errCh := make(chan *shared.ApiError, 3)+ var (+ customModels []*shared.CustomModel+ customProviders []*shared.CustomProvider+ customModelPacks []*shared.ModelPackSchema+ )++ go func() {+ models, apiErr := api.Client.ListCustomModels()+ if apiErr != nil {+ errCh <- apiErr+ return+ }+ customModels = models+ errCh <- nil+ }()- go func() {- models, apiErr := api.Client.ListCustomModels()- if apiErr != nil {- errCh <- apiErr- }- modelsInput.CustomModels = models+ go func() {+ // custom providers are not supported on cloud+ if auth.Current.IsCloud {errCh <- nil- }()+ return+ }+ providers, apiErr := api.Client.ListCustomProviders()+ if apiErr != nil {+ errCh <- apiErr+ return+ }+ customProviders = providers+ errCh <- nil+ }()- go func() {- providers, apiErr := api.Client.ListCustomProviders()- if apiErr != nil {- errCh <- apiErr- }- modelsInput.CustomProviders = providers- errCh <- nil- }()+ go func() {+ modelPacks, apiErr := api.Client.ListModelPacks()+ if apiErr != nil {+ errCh <- apiErr+ return+ }- go func() {- modelPacks, apiErr := api.Client.ListModelPacks()- if apiErr != nil {- errCh <- apiErr- }+ schemas := make([]*shared.ModelPackSchema, len(modelPacks))+ for i, modelPack := range modelPacks {+ schemas[i] = modelPack.ToModelPackSchema()+ }- schemas := make([]*shared.ModelPackSchema, len(modelPacks))- for i, modelPack := range modelPacks {- schemas[i] = modelPack.ToModelPackSchema()- }+ customModelPacks = schemas+ errCh <- nil+ }()- modelsInput.CustomModelPacks = schemas- errCh <- nil- }()+ for i := 0; i < 3; i++ {+ err := <-errCh+ if err != nil {+ term.OutputErrorAndExit("Error fetching custom models: %v", err.Msg)+ return+ }+ }- term.StopSpinner()+ existsById := map[string]bool{}+ for _, model := range customModels {+ existsById[string(model.ModelId)] = true+ }+ for _, provider := range customProviders {+ existsById[provider.Name] = true+ }+ for _, modelPack := range customModelPacks {+ existsById[modelPack.Name] = true+ }- for i := 0; i < 3; i++ {- err := <-errCh- if err != nil {- term.OutputErrorAndExit("Error fetching custom models: %v", err.Msg)- return- }+ if len(args) == 1 {+ jsonFile = args[0]+ } else if updateModels {+ modelsInput := &shared.ModelsInput{+ CustomModels: customModels,+ CustomProviders: customProviders,+ CustomModelPacks: customModelPacks,}+ modelsInput.PrepareUpdate()+// Generate temp file with current statetmpFile, err := os.CreateTemp("", "plandex-models-update-*.json")if err != nil {@@ -173,15 +202,12 @@ func importCustomModels(cmd *cobra.Command, args []string) {return}- fmt.Printf("✅ Created file with current configuration: %s\n",- color.New(color.Bold, term.ColorHiGreen).Sprint(jsonFile))- fmt.Println()+ term.StopSpinner()- } else {- // Case 3: Create new models (default flow)- fmt.Println(color.New(color.Bold, color.FgHiCyan).Sprint("Creating template for custom models..."))+ fmt.Printf("✅ Exported models file: %s\n", jsonFile)+ fmt.Println("👨💻 Edit the file, then come back here to finish importing")fmt.Println()-+ } else {// Generate temp file with examplestmpFile, err := os.CreateTemp("", "plandex-models-*.json")if err != nil {@@ -192,7 +218,7 @@ func importCustomModels(cmd *cobra.Command, args []string) {jsonFile = tmpFile.Name()tmpFile.Close()- jsonData, err := json.MarshalIndent(getExampleTemplate(), "", " ")+ jsonData, err := json.MarshalIndent(getExampleTemplate(auth.Current.IsCloud), "", " ")if err != nil {term.OutputErrorAndExit("Error marshalling template: %v", err)return@@ -204,21 +230,22 @@ func importCustomModels(cmd *cobra.Command, args []string) {return}- fmt.Printf("✅ Created template: %s\n",- color.New(color.Bold, term.ColorHiGreen).Sprint(jsonFile))+ term.StopSpinner()++ fmt.Printf("✅ Created example template: %s\n", jsonFile)+ fmt.Println("👨💻 Edit the file, then come back here to finish importing")fmt.Println()}// For both add and update flows, open the editor- if len(args) == 0 {+ if len(args) == 0 || (len(args) == 1 && updateModels) {selectedEditor := maybePromptAndOpen(jsonFile)if selectedEditor {fmt.Println("📝 Opened in editor")- fmt.Println("👨💻 Edit the file, then come back here to finish importing")fmt.Println()- confirmed, err := term.ConfirmYesNo("Done editing and ready to import?")+ confirmed, err := term.ConfirmYesNo("Ready to import?")if err != nil {term.OutputErrorAndExit("Error confirming: %v", err)return@@ -243,7 +270,6 @@ func importCustomModels(cmd *cobra.Command, args []string) {Sprintf(" %smodels import %s ", pf, jsonFile))return}- fmt.Println()} else {// No editor available or user chose manualfmt.Println("👨💻 Edit the file in your JSON editor of choice")@@ -261,6 +287,7 @@ func importCustomModels(cmd *cobra.Command, args []string) {}}+ term.StartSpinner("")// Import the JSON filejsonData, err := os.ReadFile(jsonFile)if err != nil {@@ -270,12 +297,35 @@ func importCustomModels(cmd *cobra.Command, args []string) {modelsInput, err := schema.ValidateModelsInputJSON(jsonData)if err != nil {+ term.StopSpinner()color.New(color.Bold, term.ColorHiRed).Println("🚨 Error validating JSON file")fmt.Println(err.Error())return}- term.StartSpinner("")+ noDuplicates, errMsg := modelsInput.CheckNoDuplicates()+ if !noDuplicates {+ term.StopSpinner()+ color.New(color.Bold, term.ColorHiRed).Println("🚨 Some items are duplicated:")+ fmt.Println()+ fmt.Println(errMsg)+ return+ }++ modelsInput = modelsInput.FilterUnchanged(&shared.ModelsInput{+ CustomModels: customModels,+ CustomProviders: customProviders,+ CustomModelPacks: customModelPacks,+ })++ if modelsInput.IsEmpty() {+ term.StopSpinner()+ fmt.Println("🤷♂️ Nothing to import")+ fmt.Println()+ term.PrintCmds("", "models available", "models import", "models import --update")+ return+ }+apiErr := api.Client.CreateCustomModels(&modelsInput)term.StopSpinner()@@ -284,31 +334,53 @@ func importCustomModels(cmd *cobra.Command, args []string) {return}- action := "Imported"+ added := strings.Builder{}+ updated := strings.Builder{}for _, provider := range modelsInput.CustomProviders {- fmt.Printf("✅ %s custom %s → %s\n",+ action := "✅ Added"+ builder := &added+ if existsById[provider.Name] {+ action = "🔄 Updated"+ builder = &updated+ }+ builder.WriteString(fmt.Sprintf("%s custom %s → %s\n",action,color.New(term.ColorHiCyan).Sprint("provider"),- color.New(color.Bold, term.ColorHiGreen).Sprint(provider.Name))+ color.New(color.Bold, term.ColorHiGreen).Sprint(provider.Name)))}for _, model := range modelsInput.CustomModels {- fmt.Printf("✅ %s custom %s → %s\n",+ action := "✅ Added"+ builder := &added+ if existsById[string(model.ModelId)] {+ action = "🔄 Updated"+ builder = &updated+ }+ builder.WriteString(fmt.Sprintf("%s custom %s → %s\n",action,color.New(term.ColorHiCyan).Sprint("model"),- color.New(color.Bold, term.ColorHiGreen).Sprint(string(model.ModelId)))+ color.New(color.Bold, term.ColorHiGreen).Sprint(string(model.ModelId))))}for _, modelPack := range modelsInput.CustomModelPacks {- fmt.Printf("✅ %s custom %s → %s\n",+ action := "✅ Added"+ builder := &added+ if existsById[modelPack.Name] {+ action = "🔄 Updated"+ builder = &updated+ }+ builder.WriteString(fmt.Sprintf("%s custom %s → %s\n",action,color.New(term.ColorHiCyan).Sprint("model pack"),- color.New(color.Bold, term.ColorHiGreen).Sprint(modelPack.Name))+ color.New(color.Bold, term.ColorHiGreen).Sprint(modelPack.Name)))}+ fmt.Print(added.String())+ fmt.Print(updated.String())+// Clean up temp file if it was generated- if len(args) == 0 && looksLikeEphemeralTemplate(jsonFile) {+ if (len(args) == 0 || (len(args) == 1 && updateModels)) && looksLikeEphemeralTemplate(jsonFile) {err = os.Remove(jsonFile)if err != nil {term.OutputErrorAndExit("Error cleaning up temp file: %v", err)@@ -667,10 +739,17 @@ func renderModelPack(modelPack *shared.ModelPack, allProperties bool) {}-func customModelsNotImplemented(cmd *cobra.Command, args []string) {+func customModelsCreateNotImplemented(cmd *cobra.Command, args []string) {+ color.New(color.Bold, color.FgHiRed).Println("⛔️ Not implemented")+ fmt.Println()+ fmt.Println("Use " + color.New(color.BgCyan, color.FgHiWhite).Sprint(" plandex models import ") + " to add custom models, providers, and model packs with a JSON file")+ os.Exit(1)+}++func customModelsUpdateNotImplemented(cmd *cobra.Command, args []string) {color.New(color.Bold, color.FgHiRed).Println("⛔️ Not implemented")fmt.Println()- fmt.Println("Use " + color.New(color.BgCyan, color.FgHiWhite).Sprint(" plandex models import ") + " to add or update custom models, providers, and model packs with a JSON file")+ fmt.Println("Use " + color.New(color.BgCyan, color.FgHiWhite).Sprint(" plandex models import --update ") + " to update existing custom models, providers, and model packs with a JSON file")os.Exit(1)}@@ -784,7 +863,7 @@ func maybePromptAndOpen(path string) bool {const openManually = "Open manually"opts = append(opts, openManually)- choice, err := term.SelectFromList("Edit the template now?", opts)+ choice, err := term.SelectFromList("Open the file now?", opts)if err != nil {term.OutputErrorAndExit("Error selecting editor: %v", err)}@@ -821,18 +900,32 @@ func looksLikeEphemeralTemplate(p string) bool {strings.HasSuffix(p, ".json")}-func getExampleTemplate() shared.ModelsInput {+func getExampleTemplate(isCloud bool) shared.ModelsInput {exampleProviderName := "togetherai"+ var customProviders []*shared.CustomProvider+ usesProviders := []shared.BaseModelUsesProvider{}+ if !isCloud {+ customProviders = append(customProviders, &shared.CustomProvider{+ Name: exampleProviderName,+ BaseUrl: "https://api.together.xyz/v1",+ ApiKeyEnvVar: "TOGETHER_API_KEY",+ })++ usesProviders = append(usesProviders, shared.BaseModelUsesProvider{+ Provider: shared.ModelProviderCustom,+ CustomProvider: &exampleProviderName,+ ModelName: "meta-llama/Llama-4-Maverick-17B-128E-Instruct-FP8",+ })+ }+ usesProviders = append(usesProviders, shared.BaseModelUsesProvider{+ Provider: shared.ModelProviderOpenRouter,+ ModelName: "meta-llama/llama-4-maverick",+ })+return shared.ModelsInput{- SchemaUrl: shared.SchemaUrlInputConfig,- CustomProviders: []*shared.CustomProvider{- {- Name: exampleProviderName,- BaseUrl: "https://api.together.xyz/v1",- ApiKeyEnvVar: "TOGETHER_API_KEY",- },- },+ SchemaUrl: shared.SchemaUrlInputConfig,+ CustomProviders: customProviders,CustomModels: []*shared.CustomModel{{ModelId: shared.ModelId("meta-llama/llama-4-maverick"),@@ -848,17 +941,7 @@ func getExampleTemplate() shared.ModelsInput {PreferredOutputFormat: shared.ModelOutputFormatXml,},- Providers: []shared.BaseModelUsesProvider{- {- Provider: shared.ModelProviderCustom,- CustomProvider: &exampleProviderName,- ModelName: "meta-llama/Llama-4-Maverick-17B-128E-Instruct-FP8",- },- {- Provider: shared.ModelProviderOpenRouter,- ModelName: "meta-llama/llama-4-maverick",- },- },+ Providers: usesProviders,},},CustomModelPacks: []*shared.ModelPackSchema{@@ -866,10 +949,10 @@ func getExampleTemplate() shared.ModelsInput {Name: "example-model-pack",Description: "Example model pack",Planner: shared.ModelRoleConfigSchema{- ModelId: shared.ModelId("deepseek/r1-reasoning-visible"),+ ModelId: shared.ModelId("deepseek/r1"),},Architect: &shared.ModelRoleConfigSchema{- ModelId: shared.ModelId("deepseek/r1-reasoning-visible"),+ ModelId: shared.ModelId("deepseek/r1"),},Coder: &shared.ModelRoleConfigSchema{ModelId: shared.ModelId("deepseek/v3-0324"),@@ -878,13 +961,13 @@ func getExampleTemplate() shared.ModelsInput {ModelId: shared.ModelId("meta-llama/llama-4-maverick"),},Builder: shared.ModelRoleConfigSchema{- ModelId: shared.ModelId("deepseek/r1-reasoning-hidden"),+ ModelId: shared.ModelId("deepseek/r1-hidden"),},WholeFileBuilder: &shared.ModelRoleConfigSchema{- ModelId: shared.ModelId("deepseek/r1-reasoning-hidden"),+ ModelId: shared.ModelId("deepseek/r1-hidden"),},ExecStatus: shared.ModelRoleConfigSchema{- ModelId: shared.ModelId("deepseek/r1-reasoning-hidden"),+ ModelId: shared.ModelId("deepseek/r1-hidden"),},Namer: shared.ModelRoleConfigSchema{ModelId: shared.ModelId("meta-llama/llama-4-maverick"),diff --git a/app/cli/go.mod b/app/cli/go.modindex 1a92e8e1..b424d265 100644--- a/app/cli/go.mod+++ b/app/cli/go.mod@@ -21,6 +21,8 @@ require (github.com/sashabaranov/go-openai v1.38.1github.com/shopspring/decimal v1.4.0github.com/spf13/cobra v1.8.0+ github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415+ github.com/xeipuuv/gojsonschema v1.2.0golang.org/x/term v0.19.0gopkg.in/natefinch/lumberjack.v2 v2.2.1)@@ -53,6 +55,7 @@ require (github.com/gobwas/httphead v0.1.0 // indirectgithub.com/gobwas/pool v0.2.1 // indirectgithub.com/gobwas/ws v1.4.0 // indirect+ github.com/google/go-cmp v0.7.0 // indirectgithub.com/gorilla/css v1.0.1 // indirectgithub.com/jinzhu/copier v0.4.0 // indirectgithub.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 // indirect@@ -69,8 +72,6 @@ require (github.com/pkg/term v1.2.0-beta.2 // indirectgithub.com/rivo/uniseg v0.4.7 // indirectgithub.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f // indirect- github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect- github.com/xeipuuv/gojsonschema v1.2.0 // indirectgithub.com/yuin/goldmark v1.6.0 // indirectgithub.com/yuin/goldmark-emoji v1.0.2 // indirectgolang.org/x/exp v0.0.0-20241108190413-2d47ceb2692f // indirectdiff --git a/app/cli/go.sum b/app/cli/go.sumindex aaf493a3..a6d20c25 100644--- a/app/cli/go.sum+++ b/app/cli/go.sum@@ -428,8 +428,8 @@ github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/github.com/google/go-cmp v0.5.7/go.mod h1:n+brtR0CgQNWTVd5ZUFpTBC8YFBDLK/h/bpaJ8/DtOE=github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=-github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=-github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=+github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=+github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=github.com/google/goterm v0.0.0-20190703233501-fc88cf888a3f/go.mod h1:nOFQdrUlIlx6M6ODdSpBj1NVA+VgLC6kmw60mkw34H4=github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs=diff --git a/app/cli/schema/json-schemas/models-input.schema.json b/app/cli/schema/json-schemas/models-input.schema.jsonindex 06d01009..852c2bfd 100644--- a/app/cli/schema/json-schemas/models-input.schema.json+++ b/app/cli/schema/json-schemas/models-input.schema.json@@ -5,19 +5,19 @@"description": "Input schema for custom models, providers, and model packs","type": "object","properties": {- "customModels": {+ "models": {"type": "array","items": {"$ref": "./model-config.schema.json"}},- "customProviders": {+ "providers": {"type": "array","items": {"$ref": "./model-provider-config.schema.json"}},- "customModelPacks": {+ "modelPacks": {"type": "array","items": {"$ref": "./model-pack-config.schema.json"diff --git a/app/server/go.mod b/app/server/go.modindex 0a8830c6..9eb18710 100644--- a/app/server/go.mod+++ b/app/server/go.mod@@ -15,6 +15,7 @@ require (github.com/dlclark/regexp2 v1.11.5 // indirectgithub.com/go-toast/toast v0.0.0-20190211030409-01e6764cf0a4 // indirectgithub.com/godbus/dbus/v5 v5.1.0 // indirect+ github.com/google/go-cmp v0.7.0 // indirectgithub.com/hashicorp/errwrap v1.1.0 // indirectgithub.com/hashicorp/go-multierror v1.1.1 // indirectgithub.com/jinzhu/copier v0.4.0 // indirectdiff --git a/app/server/go.sum b/app/server/go.sumindex 8e10a00a..a55f5e68 100644--- a/app/server/go.sum+++ b/app/server/go.sum@@ -43,6 +43,8 @@ github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=github.com/golang-migrate/migrate/v4 v4.18.3 h1:EYGkoOsvgHHfm5U/naS1RP/6PL/Xv3S4B/swMiAmDLs=github.com/golang-migrate/migrate/v4 v4.18.3/go.mod h1:99BKpIi6ruaaXRM1A77eqZ+FWPQ3cfRa+ZVy5bmWMaY=+github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=+github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY=diff --git a/app/server/handlers/models.go b/app/server/handlers/models.goindex 9a234393..316575b0 100644--- a/app/server/handlers/models.go+++ b/app/server/handlers/models.go@@ -10,6 +10,7 @@ import (shared "plandex-shared"+ "github.com/davecgh/go-spew/spew""github.com/gorilla/mux""github.com/jmoiron/sqlx")@@ -35,11 +36,33 @@ func CreateCustomModelHandler(w http.ResponseWriter, r *http.Request) {return}- if len(modelsInput.CustomModels)+len(modelsInput.CustomProviders)+len(modelsInput.CustomModelPacks) == 0 {+ if modelsInput.IsEmpty() {http.Error(w, "No custom models, providers, or model packs provided", http.StatusBadRequest)return}+ if len(modelsInput.CustomProviders) > 0 {+ if os.Getenv("IS_CLOUD") != "" {+ http.Error(w, "Custom model providers are not supported on Plandex Cloud", http.StatusBadRequest)+ return+ }+ }++ hasDuplicates, errMsg := modelsInput.CheckNoDuplicates()+ if !hasDuplicates {+ http.Error(w, "Has duplicates: "+errMsg, http.StatusBadRequest)+ return+ }++ for _, provider := range modelsInput.CustomProviders {+ if provider.Name == "" {+ msg := "Provider name is required"+ log.Println(msg)+ http.Error(w, msg, http.StatusBadRequest)+ return+ }+ }+for _, model := range modelsInput.CustomModels {if model.ModelId == "" {msg := "Model id is required"@@ -56,15 +79,6 @@ func CreateCustomModelHandler(w http.ResponseWriter, r *http.Request) {}}- for _, provider := range modelsInput.CustomProviders {- if provider.Name == "" {- msg := "Provider name is required"- log.Println(msg)- http.Error(w, msg, http.StatusBadRequest)- return- }- }-for _, modelPack := range modelsInput.CustomModelPacks {if modelPack.Name == "" {msg := "Model pack name is required"@@ -74,36 +88,22 @@ func CreateCustomModelHandler(w http.ResponseWriter, r *http.Request) {}}- var customModelIds = make(map[string]bool)+ var customModelIds = make(map[shared.ModelId]bool)var customProviderNames = make(map[string]bool)- if len(modelsInput.CustomModels) > 0 {-- var modelIds []string- for _, model := range modelsInput.CustomModels {- modelIds = append(modelIds, string(model.ModelId))- }-- customModels, err := db.ListCustomModelsForModelIds(auth.OrgId, modelIds)- if err != nil {- log.Printf("Error fetching custom models: %v\n", err)- http.Error(w, "Failed to create custom model: "+err.Error(), http.StatusInternalServerError)- return- }-- for _, model := range customModels {- customModelIds[model.Id] = true- }-+ customModels, err := db.ListCustomModels(auth.OrgId)+ if err != nil {+ log.Printf("Error fetching custom models: %v\n", err)+ http.Error(w, "Failed to create custom model: "+err.Error(), http.StatusInternalServerError)+ return}- if len(modelsInput.CustomProviders) > 0 {- var names []string- for _, provider := range modelsInput.CustomProviders {- names = append(names, provider.Name)- }+ for _, model := range customModels {+ customModelIds[model.ModelId] = true+ }- customProviders, err := db.ListCustomProvidersForNames(auth.OrgId, names)+ if os.Getenv("IS_CLOUD") == "" {+ customProviders, err := db.ListCustomProviders(auth.OrgId)if err != nil {log.Printf("Error fetching custom providers: %v\n", err)http.Error(w, "Failed to create custom model: "+err.Error(), http.StatusInternalServerError)@@ -162,13 +162,20 @@ func CreateCustomModelHandler(w http.ResponseWriter, r *http.Request) {willCreateModelIds[string(model.ModelId)] = true}+ log.Println(spew.Sdump(map[string]interface{}{+ "customModelIds": customModelIds,+ "willCreateModelIds": willCreateModelIds,+ }))+for _, modelPack := range modelsInput.CustomModelPacks {// ensure that all models are either built-in, being created, or already existallModelIds := modelPack.AllModelIds()+for _, modelId := range allModelIds {- _, exists := customModelIds[string(modelId)]+ _, exists := customModelIds[modelId]_, creating := willCreateModelIds[string(modelId)]_, builtIn := shared.BuiltInBaseModelsById[modelId]+if !exists && !creating && !builtIn {msg := fmt.Sprintf("'%s' is not built-in, not being created, and not an existing custom model", modelId)log.Println(msg)@@ -185,7 +192,7 @@ func CreateCustomModelHandler(w http.ResponseWriter, r *http.Request) {toUpsertModelPacks = append(toUpsertModelPacks, dbMp)}- err := db.WithTx(r.Context(), "create custom models/providers/model packs", func(tx *sqlx.Tx) error {+ err = db.WithTx(r.Context(), "create custom models/providers/model packs", func(tx *sqlx.Tx) error {for _, model := range toUpsertCustomModels {if err := db.UpsertCustomModel(tx, model); err != nil {return fmt.Errorf("error creating custom model: %w", err)@@ -209,13 +216,13 @@ func CreateCustomModelHandler(w http.ResponseWriter, r *http.Request) {if err != nil {log.Printf("Error: %v\n", err)- http.Error(w, "Failed to create custom model: "+err.Error(), http.StatusInternalServerError)+ http.Error(w, "Failed to import custom models/providers/model packs: "+err.Error(), http.StatusInternalServerError)return}w.WriteHeader(http.StatusOK)- log.Println("Successfully created custom model")+ log.Println("Successfully imported custom models/providers/model packs")}func GetCustomModelHandler(w http.ResponseWriter, r *http.Request) {diff --git a/app/server/model/client_stream.go b/app/server/model/client_stream.goindex 36e361f8..bde4a387 100644--- a/app/server/model/client_stream.go+++ b/app/server/model/client_stream.go@@ -247,6 +247,12 @@ func withStreamingRetries[T any](log.Printf("withStreamingRetries - will run operation")+ log.Println(spew.Sdump(map[string]interface{}{+ "numTotalRetry": numTotalRetry,+ "didProviderFallback": didProviderFallback,+ "modelErr": modelErr,+ }))+resp, fallbackRes, err = operation(numTotalRetry, didProviderFallback, modelErr)if err == nil {return resp, nildiff --git a/app/shared/ai_models_available.go b/app/shared/ai_models_available.goindex 62d8d0cd..04df701f 100644--- a/app/shared/ai_models_available.go+++ b/app/shared/ai_models_available.go@@ -137,29 +137,6 @@ var BuiltInModels = []*BaseModelConfigSchema{{Provider: ModelProviderOpenRouter, ModelName: "openai/gpt-4.1-nano"},},},- {- ModelTag: "openai/o3-mini",- Publisher: ModelPublisherOpenAI,- Description: "OpenAI o3-mini",- BaseModelShared: BaseModelShared{- DefaultMaxConvoTokens: 10000, MaxTokens: 200000, MaxOutputTokens: 100000,- ReservedOutputTokens: 40000, ModelCompatibility: FullCompatibility,- PreferredOutputFormat: ModelOutputFormatToolCallJson, SystemPromptDisabled: true,- RoleParamsDisabled: true, ReasoningEffortEnabled: true, ReasoningEffort: ReasoningEffortHigh,- StopDisabled: true,- },- RequiresVariantOverrides: []string{"ReasoningEffort"},- Variants: []BaseModelConfigVariant{- {VariantTag: "high", Description: "high", Overrides: BaseModelShared{ReasoningEffort: ReasoningEffortHigh}},- {VariantTag: "medium", Description: "medium", Overrides: BaseModelShared{ReasoningEffort: ReasoningEffortMedium, ReservedOutputTokens: 30000}},- {VariantTag: "low", Description: "low", Overrides: BaseModelShared{ReasoningEffort: ReasoningEffortLow, ReservedOutputTokens: 20000}},- },- Providers: []BaseModelUsesProvider{- {Provider: ModelProviderOpenAI, ModelName: "o3-mini"},- {Provider: ModelProviderAzureOpenAI, ModelName: "azure/o3-mini"},- {Provider: ModelProviderOpenRouter, ModelName: "openai/o3-mini"},- },- },{ModelTag: "anthropic/claude-opus-4",Publisher: ModelPublisherAnthropic,@@ -172,14 +149,15 @@ var BuiltInModels = []*BaseModelConfigSchema{},Variants: []BaseModelConfigVariant{{IsBaseVariant: true},- {- VariantTag: "thinking", Description: "thinking",- Overrides: BaseModelShared{ReasoningBudget: AnthropicMaxReasoningBudget},- Variants: []BaseModelConfigVariant{- {VariantTag: "visible", Description: "visible", Overrides: BaseModelShared{IncludeReasoning: true}},- {VariantTag: "hidden", Description: "hidden", Overrides: BaseModelShared{IncludeReasoning: false}},- },- },+ // Opus thinking variant not working yet—might need a specific cap set+ // {+ // VariantTag: "thinking", Description: "thinking",+ // Overrides: BaseModelShared{ReasoningBudget: AnthropicMaxReasoningBudget},+ // Variants: []BaseModelConfigVariant{+ // {VariantTag: "visible", IsDefaultVariant: true, Description: "visible", Overrides: BaseModelShared{IncludeReasoning: true}},+ // {VariantTag: "hidden", Description: "hidden", Overrides: BaseModelShared{IncludeReasoning: false}},+ // },+ // },},Providers: []BaseModelUsesProvider{{Provider: ModelProviderAnthropic, ModelName: "anthropic/claude-opus-4-0"},@@ -204,7 +182,7 @@ var BuiltInModels = []*BaseModelConfigSchema{VariantTag: "thinking", Description: "thinking",Overrides: BaseModelShared{ReasoningBudget: AnthropicMaxReasoningBudget},Variants: []BaseModelConfigVariant{- {VariantTag: "visible", Description: "visible", Overrides: BaseModelShared{IncludeReasoning: true}},+ {VariantTag: "visible", IsDefaultVariant: true, Description: "visible", Overrides: BaseModelShared{IncludeReasoning: true}},{VariantTag: "hidden", Description: "hidden", Overrides: BaseModelShared{IncludeReasoning: false}},},},@@ -232,7 +210,7 @@ var BuiltInModels = []*BaseModelConfigSchema{VariantTag: "thinking", Description: "thinking",Overrides: BaseModelShared{ReasoningBudget: AnthropicMaxReasoningBudget},Variants: []BaseModelConfigVariant{- {VariantTag: "visible", Description: "visible", Overrides: BaseModelShared{IncludeReasoning: true}},+ {VariantTag: "visible", IsDefaultVariant: true, Description: "visible", Overrides: BaseModelShared{IncludeReasoning: true}},{VariantTag: "hidden", Description: "hidden", Overrides: BaseModelShared{IncludeReasoning: false}},},},@@ -366,8 +344,8 @@ var BuiltInModels = []*BaseModelConfigSchema{PreferredOutputFormat: ModelOutputFormatXml,},Variants: []BaseModelConfigVariant{- {VariantTag: "reasoning-visible", Description: "(reasoning visible)", Overrides: BaseModelShared{IncludeReasoning: true}},- {VariantTag: "reasoning-hidden", Description: "(reasoning hidden)", Overrides: BaseModelShared{IncludeReasoning: false}},+ {VariantTag: "visible", IsDefaultVariant: true, Description: "(reasoning visible)", Overrides: BaseModelShared{IncludeReasoning: true}},+ {VariantTag: "hidden", Description: "(reasoning hidden)", Overrides: BaseModelShared{IncludeReasoning: false}},},Providers: []BaseModelUsesProvider{{Provider: ModelProviderDeepSeek, ModelName: "deepseek/deepseek-reasoner"},@@ -384,8 +362,8 @@ var BuiltInModels = []*BaseModelConfigSchema{PreferredOutputFormat: ModelOutputFormatXml,},Variants: []BaseModelConfigVariant{- {VariantTag: "reasoning-visible", Description: "(reasoning visible)", Overrides: BaseModelShared{IncludeReasoning: true}},- {VariantTag: "reasoning-hidden", Description: "(reasoning hidden)", Overrides: BaseModelShared{IncludeReasoning: false}},+ {VariantTag: "visible", IsDefaultVariant: true, Description: "(reasoning visible)", Overrides: BaseModelShared{IncludeReasoning: true}},+ {VariantTag: "hidden", Description: "(reasoning hidden)", Overrides: BaseModelShared{IncludeReasoning: false}},},Providers: []BaseModelUsesProvider{{Provider: ModelProviderPerplexity, ModelName: "r1-1776-online"},@@ -402,7 +380,7 @@ var BuiltInModels = []*BaseModelConfigSchema{PreferredOutputFormat: ModelOutputFormatXml,},Variants: []BaseModelConfigVariant{- {VariantTag: "visible", Description: "(reasoning visible)", Overrides: BaseModelShared{IncludeReasoning: true}},+ {VariantTag: "visible", IsDefaultVariant: true, Description: "(reasoning visible)", Overrides: BaseModelShared{IncludeReasoning: true}},{VariantTag: "hidden", Description: "(reasoning hidden)", Overrides: BaseModelShared{IncludeReasoning: false}},},Providers: []BaseModelUsesProvider{@@ -468,7 +446,7 @@ func init() {addVariants = func(variants []BaseModelConfigVariant, baseId ModelId) {for _, variant := range variants {var modelId ModelId- if variant.IsBaseVariant {+ if variant.IsBaseVariant || variant.IsDefaultVariant {modelId = baseId} else {modelId = ModelId(strings.Join([]string{string(baseId), string(variant.VariantTag)}, "-"))@@ -479,10 +457,12 @@ func init() {continue}- model.ModelId = modelId- BuiltInModelProvidersByModelId[modelId] = model.Providers- BuiltInBaseModelsById[modelId] = model- BuiltInBaseModels = append(BuiltInBaseModels, model)+ cloned := *model+ cloned.ModelId = modelId++ BuiltInModelProvidersByModelId[modelId] = cloned.Providers+ BuiltInBaseModelsById[modelId] = &cloned+ BuiltInBaseModels = append(BuiltInBaseModels, &cloned)}}diff --git a/app/shared/ai_models_custom.go b/app/shared/ai_models_custom.goindex f6dd6fd1..2aea8f9b 100644--- a/app/shared/ai_models_custom.go+++ b/app/shared/ai_models_custom.go@@ -1,6 +1,13 @@package shared-import "time"+import (+ "fmt"+ "strings"+ "time"++ "github.com/google/go-cmp/cmp"+ "github.com/google/go-cmp/cmp/cmpopts"+)type SchemaUrl string@@ -40,7 +47,119 @@ type CustomProvider struct {type ModelsInput struct {SchemaUrl SchemaUrl `json:"schemaUrl"`- CustomModels []*CustomModel `json:"customModels"`- CustomProviders []*CustomProvider `json:"customProviders"`- CustomModelPacks []*ModelPackSchema `json:"customModelPacks"`+ CustomModels []*CustomModel `json:"models"`+ CustomProviders []*CustomProvider `json:"providers,omitempty"`+ CustomModelPacks []*ModelPackSchema `json:"modelPacks"`+}++func (input ModelsInput) FilterUnchanged(existing *ModelsInput) ModelsInput {+ filtered := ModelsInput{+ SchemaUrl: input.SchemaUrl,+ }++ existingProvidersById := map[string]*CustomProvider{}+ for _, provider := range existing.CustomProviders {+ existingProvidersById[provider.Name] = provider+ }+ existingModelsById := map[string]*CustomModel{}+ for _, model := range existing.CustomModels {+ existingModelsById[string(model.ModelId)] = model+ }+ existingPacksById := map[string]*ModelPackSchema{}+ for _, pack := range existing.CustomModelPacks {+ existingPacksById[pack.Name] = pack+ }++ for _, model := range input.CustomModels {+ if existingModel, ok := existingModelsById[string(model.ModelId)]; !ok || !modelsEqual(model, existingModel) {+ filtered.CustomModels = append(filtered.CustomModels, model)+ }+ }++ for _, provider := range input.CustomProviders {+ if existingProvider, ok := existingProvidersById[provider.Name]; !ok || !providersEqual(provider, existingProvider) {+ filtered.CustomProviders = append(filtered.CustomProviders, provider)+ }+ }++ for _, pack := range input.CustomModelPacks {+ if existingPack, ok := existingPacksById[pack.Name]; !ok || !packsEqual(pack, existingPack) {+ filtered.CustomModelPacks = append(filtered.CustomModelPacks, pack)+ }+ }++ return filtered+}++func (input ModelsInput) CheckNoDuplicates() (bool, string) {+ sawModelIds := map[ModelId]bool{}+ sawProviderNames := map[string]bool{}+ sawPackNames := map[string]bool{}++ builder := strings.Builder{}++ for _, provider := range input.CustomProviders {+ if _, ok := sawProviderNames[provider.Name]; ok {+ builder.WriteString(fmt.Sprintf("• Provider %s is duplicated\n", provider.Name))+ }+ sawProviderNames[provider.Name] = true+ }++ for _, model := range input.CustomModels {+ if _, ok := sawModelIds[model.ModelId]; ok {+ builder.WriteString(fmt.Sprintf("• Model %s is duplicated\n", model.ModelId))+ }+ sawModelIds[model.ModelId] = true+ }++ for _, pack := range input.CustomModelPacks {+ if _, ok := sawPackNames[pack.Name]; ok {+ builder.WriteString(fmt.Sprintf("• Model pack %s is duplicated\n", pack.Name))+ }+ sawPackNames[pack.Name] = true+ }++ res := builder.String()++ return len(res) == 0, res+}++func (input ModelsInput) IsEmpty() bool {+ return len(input.CustomModels) == 0 && len(input.CustomProviders) == 0 && len(input.CustomModelPacks) == 0+}++func (input *ModelsInput) PrepareUpdate() {+ input.SchemaUrl = SchemaUrlInputConfig++ for _, model := range input.CustomModels {+ model.Id = ""+ model.CreatedAt = nil+ model.UpdatedAt = nil+ }++ for _, provider := range input.CustomProviders {+ provider.Id = ""+ provider.CreatedAt = nil+ provider.UpdatedAt = nil+ }+}++func modelsEqual(a, b *CustomModel) bool {+ return cmp.Equal(+ a, b,+ cmpopts.EquateEmpty(), // treat nil == empty slice/map+ cmpopts.IgnoreFields(CustomModel{}, "CreatedAt", "UpdatedAt", "Id"),+ )+}++func providersEqual(a, b *CustomProvider) bool {+ return cmp.Equal(+ a, b,+ cmpopts.EquateEmpty(),+ cmpopts.IgnoreFields(CustomProvider{}, "CreatedAt", "UpdatedAt", "Id"),+ )+}++func packsEqual(a, b *ModelPackSchema) bool {+ return cmp.Equal(a, b, cmpopts.EquateEmpty())}diff --git a/app/shared/ai_models_data_models.go b/app/shared/ai_models_data_models.goindex 17af1ff8..cc31e30d 100644--- a/app/shared/ai_models_data_models.go+++ b/app/shared/ai_models_data_models.go@@ -98,6 +98,7 @@ type BaseModelConfigVariant struct {Overrides BaseModelShared `json:"overrides"`Variants []BaseModelConfigVariant `json:"variants"`RequiresVariantOverrides []string `json:"requiresVariantOverrides"`+ IsDefaultVariant bool `json:"isDefaultVariant"`}func (b *BaseModelConfigSchema) ToAvailableModels() []*AvailableModel {@@ -509,14 +510,14 @@ type ModelPackSchema struct {Name string `json:"name"`Description string `json:"description"`Planner ModelRoleConfigSchema `json:"planner"`- Coder *ModelRoleConfigSchema `json:"coder"`+ Coder *ModelRoleConfigSchema `json:"coder,omitempty"`PlanSummary ModelRoleConfigSchema `json:"planSummary"`Builder ModelRoleConfigSchema `json:"builder"`- WholeFileBuilder *ModelRoleConfigSchema `json:"wholeFileBuilder"` // optional, defaults to builder model — access via GetWholeFileBuilder()+ WholeFileBuilder *ModelRoleConfigSchema `json:"wholeFileBuilder,omitempty"` // optional, defaults to builder model — access via GetWholeFileBuilder()Namer ModelRoleConfigSchema `json:"namer"`CommitMsg ModelRoleConfigSchema `json:"commitMsg"`ExecStatus ModelRoleConfigSchema `json:"execStatus"`- Architect *ModelRoleConfigSchema `json:"contextLoader"`+ Architect *ModelRoleConfigSchema `json:"contextLoader,omitempty"`}func (m *ModelPackSchema) AllModelIds() []ModelId {diff --git a/app/shared/ai_models_errors.go b/app/shared/ai_models_errors.goindex 0e039887..208b25f0 100644--- a/app/shared/ai_models_errors.go+++ b/app/shared/ai_models_errors.go@@ -3,6 +3,7 @@ package sharedimport ("log"+ "github.com/davecgh/go-spew/spew""github.com/jinzhu/copier")@@ -68,7 +69,14 @@ func (m *ModelRoleConfig) GetFallbackForModelError(IsFallback: true,}} else if !didProviderFallback {+ log.Println("no error fallback, trying provider fallback")+providerFallback := m.GetProviderFallback(authVars)++ log.Println(spew.Sdump(map[string]interface{}{+ "providerFallback": providerFallback,+ }))+if providerFallback != nil {return FallbackResult{ModelRoleConfig: providerFallback,diff --git a/app/shared/go.mod b/app/shared/go.modindex c76577cb..0a9705d4 100644--- a/app/shared/go.mod+++ b/app/shared/go.mod@@ -4,6 +4,7 @@ go 1.23.3require (github.com/davecgh/go-spew v1.1.1+ github.com/google/go-cmp v0.7.0github.com/jinzhu/copier v0.4.0github.com/pkoukk/tiktoken-go v0.1.7)diff --git a/app/shared/go.sum b/app/shared/go.sumindex a5df4991..f58dcd6a 100644--- a/app/shared/go.sum+++ b/app/shared/go.sum@@ -2,6 +2,8 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97cgithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=github.com/dlclark/regexp2 v1.11.5 h1:Q/sSnsKerHeCkc/jSTNq1oCm7KiVgUMZRDUoRu0JQZQ=github.com/dlclark/regexp2 v1.11.5/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=+github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=+github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=github.com/jinzhu/copier v0.4.0 h1:w3ciUoD19shMCRargcpm0cm91ytaBhDvuRpz1ODO/U8=