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
'models custom' command for management of custom models/providers/model packs via json file
Dane Schneider63083a6d5011
diff --git a/app/cli/cmd/models.go b/app/cli/cmd/models.goindex cf45c628..27527a0d 100644--- a/app/cli/cmd/models.go+++ b/app/cli/cmd/models.go@@ -37,12 +37,12 @@ func init() {modelsCmd.AddCommand(listAvailableModelsCmd)modelsCmd.AddCommand(addCustomModelCmd)modelsCmd.AddCommand(updateCustomModelCmd)- modelsCmd.AddCommand(importCustomModelCmd)+ modelsCmd.AddCommand(manageCustomModelsCmd)modelsCmd.AddCommand(deleteCustomModelCmd)modelsCmd.AddCommand(defaultModelsCmd)- importCustomModelCmd.Flags().BoolVar(&saveCustomModels, "save", false, "Save custom models")- importCustomModelCmd.Flags().StringVar(&customModelsPath, "path", "", "Path to custom models file")+ manageCustomModelsCmd.Flags().BoolVar(&saveCustomModels, "save", false, "Save custom models")+ manageCustomModelsCmd.Flags().StringVarP(&customModelsPath, "file", "f", "", "Path to custom models file")listAvailableModelsCmd.Flags().BoolVarP(&customModelsOnly, "custom", "c", false, "List custom models only")}@@ -66,10 +66,10 @@ var listAvailableModelsCmd = &cobra.Command{Run: listAvailableModels,}-var importCustomModelCmd = &cobra.Command{+var manageCustomModelsCmd = &cobra.Command{Use: "custom",Short: "Manage custom models, providers, and model packs",- Run: importCustomModels,+ Run: manageCustomModels,}var addCustomModelCmd = &cobra.Command{@@ -94,7 +94,7 @@ var deleteCustomModelCmd = &cobra.Command{Run: customModelsNotImplemented,}-func importCustomModels(cmd *cobra.Command, args []string) {+func manageCustomModels(cmd *cobra.Command, args []string) {auth.MustResolveAuthWithOrg()term.StartSpinner("")@@ -166,11 +166,23 @@ func importCustomModels(cmd *cobra.Command, args []string) {existsById[modelPack.Name] = true}+ serverModelsInput := &shared.ModelsInput{+ CustomModels: customModels,+ CustomProviders: customProviders,+ CustomModelPacks: customModelPacks,+ }+usingDefaultPath := falseif customModelsPath == "" {usingDefaultPath = truecustomModelsPath = filepath.Join(fs.HomePlandexDir, "custom-models.json")}+ hashPath := customModelsPath + ".hash"++ cmdPrefix := "\\"+ if !term.IsRepl {+ cmdPrefix = "plandex "+ }exists := false_, err := os.Stat(customModelsPath)@@ -183,105 +195,167 @@ func importCustomModels(cmd *cobra.Command, args []string) {return}- if len(args) == 1 {- jsonFile = args[0]- } else if updateModels {- modelsInput := &shared.ModelsInput{- CustomModels: customModels,- CustomProviders: customProviders,- CustomModelPacks: customModelPacks,- }-- modelsInput.PrepareUpdate()+ var jsonData []byte- // Generate temp file with current state- tmpFile, err := os.CreateTemp("", "plandex-models-update-*.json")- if err != nil {- term.OutputErrorAndExit("Error creating temp file: %v", err)+ if saveCustomModels {+ if !exists {+ term.OutputErrorAndExit("File not found: %s", customModelsPath)return}-- jsonFile = tmpFile.Name()- tmpFile.Close()-- jsonData, err := json.MarshalIndent(modelsInput, "", " ")+ jsonData, err = os.ReadFile(customModelsPath)if err != nil {- term.OutputErrorAndExit("Error marshalling models: %v", err)+ term.OutputErrorAndExit("Error reading JSON file: %v", err)return}+ } else {+ if serverModelsInput.IsEmpty() {+ jsonData, err = json.MarshalIndent(getExampleTemplate(auth.Current.IsCloud), "", " ")+ if err != nil {+ term.OutputErrorAndExit("Error marshalling template: %v", err)+ return+ }- err = os.WriteFile(jsonFile, jsonData, 0644)- if err != nil {- term.OutputErrorAndExit("Error writing file: %v", err)- return- }+ err = os.MkdirAll(filepath.Dir(customModelsPath), 0755)+ if err != nil {+ term.OutputErrorAndExit("Error creating directory: %v", err)+ return+ }- term.StopSpinner()+ err = os.WriteFile(customModelsPath, jsonData, 0644)+ if err != nil {+ term.OutputErrorAndExit("Error writing template file: %v", err)+ return+ }- 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 examples- tmpFile, err := os.CreateTemp("", "plandex-models-*.json")- if err != nil {- term.OutputErrorAndExit("Error creating template file: %v", err)- return- }+ term.StopSpinner()- jsonFile = tmpFile.Name()- tmpFile.Close()+ fmt.Printf("π§ Example models file β %s\n", customModelsPath)+ fmt.Println("π¨βπ» Edit it, then come back here to save")+ fmt.Println()+ } else {+ localJsonData, err := os.ReadFile(customModelsPath)+ if err != nil {+ term.OutputErrorAndExit("Error reading JSON file: %v", err)+ return+ }- jsonData, err := json.MarshalIndent(getExampleTemplate(auth.Current.IsCloud), "", " ")- if err != nil {- term.OutputErrorAndExit("Error marshalling template: %v", err)- return- }+ var localModelsInput shared.ModelsInput+ err = json.Unmarshal(localJsonData, &localModelsInput)+ if err != nil {+ term.OutputErrorAndExit("Error unmarshalling JSON file: %v", err)+ return+ }- err = os.WriteFile(jsonFile, jsonData, 0644)- if err != nil {- term.OutputErrorAndExit("Error writing template file: %v", err)- return- }+ // we only do a conflict check on the default path in the home dir+ // if user specifies the path and the file exists, just open the file without checking for conflicts+ var currentHash string+ if usingDefaultPath {+ lastSavedHash, err := os.ReadFile(hashPath)+ if err != nil && !os.IsNotExist(err) {+ term.OutputErrorAndExit("Error reading hash file: %v", err)+ return+ }- term.StopSpinner()+ currentHash, err = localModelsInput.Hash()+ if err != nil {+ term.OutputErrorAndExit("Error hashing models: %v", err)+ return+ }- fmt.Printf("β Created example template: %s\n", jsonFile)- fmt.Println("π¨βπ» Edit the file, then come back here to finish importing")- fmt.Println()- }+ if currentHash != string(lastSavedHash) {+ term.StopSpinner()+ color.New(color.Bold, term.ColorHiYellow).Println("β οΈ The models file has local changes")++ fmt.Println()+ fmt.Println("Path β " + customModelsPath)+ fmt.Println()++ fmt.Println("If you continue, local changes will be dropped in favor of the latest server state")++ fmt.Println()+ fmt.Printf("To keep the local version instead, quit and run %s\n", color.New(color.Bold, color.BgCyan, color.FgHiWhite).+ Sprintf(" %smodels custom --save ", cmdPrefix))+ fmt.Println()+ res, err := term.ConfirmYesNo("Drop local changes and continue?")+ if err != nil {+ term.OutputErrorAndExit("Error confirming: %v", err)+ return+ }+ if !res {+ return+ }+ fmt.Println()+ term.StartSpinner("")+ }+ }++ serverModelsInput.PrepareUpdate()++ if serverModelsInput.Equals(localModelsInput) {+ jsonData = localJsonData+ } else {+ jsonData, err = json.MarshalIndent(serverModelsInput, "", " ")+ if err != nil {+ term.OutputErrorAndExit("Error marshalling models: %v", err)+ return+ }++ err = os.WriteFile(customModelsPath, jsonData, 0644)+ if err != nil {+ term.OutputErrorAndExit("Error writing file: %v", err)+ return+ }+ }++ if currentHash != "" {+ err = os.WriteFile(hashPath, []byte(currentHash), 0644)+ if err != nil {+ term.OutputErrorAndExit("Error writing hash file: %v", err)+ return+ }+ }++ term.StopSpinner()++ fmt.Printf("π§ %s β %s\n", color.New(color.Bold, term.ColorHiCyan).Sprint("Models file"), customModelsPath)+ fmt.Println("π¨βπ» Edit it, then come back here to save")+ fmt.Println()+ }++ pathArg := ""+ if !usingDefaultPath {+ pathArg = fmt.Sprintf(" --file %s", customModelsPath)+ }+ printManual := func() {+ fmt.Println("To save changes, run " ++ fmt.Sprintf(" %s ", color.New(color.Bold, color.BgCyan, color.FgHiWhite).+ Sprintf(" %smodels custom --save%s ", cmdPrefix, pathArg)))+ }- // For both add and update flows, open the editor- if len(args) == 0 || (len(args) == 1 && updateModels) {- selectedEditor := maybePromptAndOpen(jsonFile)+ selectedEditor := maybePromptAndOpen(customModelsPath)if selectedEditor {fmt.Println("π Opened in editor")fmt.Println()- confirmed, err := term.ConfirmYesNo("Ready to import?")+ confirmed, err := term.ConfirmYesNo("Ready to save?")if err != nil {term.OutputErrorAndExit("Error confirming: %v", err)return}if !confirmed {- fmt.Println("π€·ββοΈ Import cancelled")+ fmt.Println("π ββοΈ Update canceled")fmt.Println()- // Clean up temp file- if looksLikeEphemeralTemplate(jsonFile) {- os.Remove(jsonFile)- }-- pf := "\\"- if !term.IsRepl {- pf = "plandex "- }+ printManual()+ return+ }- fmt.Println("When you're ready, run:")- fmt.Printf("β’ %s\n", color.New(color.Bold, color.BgCyan, color.FgHiWhite).- Sprintf(" %smodels import %s ", pf, jsonFile))+ // get updated file state+ jsonData, err = os.ReadFile(customModelsPath)+ if err != nil {+ term.OutputErrorAndExit("Error reading JSON file: %v", err)return}} else {@@ -289,32 +363,12 @@ func importCustomModels(cmd *cobra.Command, args []string) {fmt.Println("π¨βπ» Edit the file in your JSON editor of choice")fmt.Println()- pf := "\\"- if !term.IsRepl {- pf = "plandex "- }-- fmt.Println("When you're ready, run:")- fmt.Printf("β’ %s\n", color.New(color.Bold, color.BgCyan, color.FgHiWhite).- Sprintf(" %smodels import %s ", pf, jsonFile))- return- }- }-- if saveCustomModels {- if !exists {- term.OutputErrorAndExit("File not found: %s", customModelsPath)+ printManual()return}}term.StartSpinner("")- // Import the JSON file- jsonData, err := os.ReadFile(jsonFile)- if err != nil {- term.OutputErrorAndExit("Error reading JSON file: %v", err)- return- }modelsInput, err := schema.ValidateModelsInputJSON(jsonData)if err != nil {@@ -333,32 +387,65 @@ func importCustomModels(cmd *cobra.Command, args []string) {return}- modelsInput = modelsInput.FilterUnchanged(&shared.ModelsInput{- CustomModels: customModels,- CustomProviders: customProviders,- CustomModelPacks: customModelPacks,- })+ printNoChanges := func() {+ term.StopSpinner()+ fmt.Println("π€·ββοΈ No changes to custom models/providers/model packs")+ }if modelsInput.IsEmpty() {- term.StopSpinner()- fmt.Println("π€·ββοΈ Nothing to import")- fmt.Println()- term.PrintCmds("", "models available", "models import", "models import --update")+ printNoChanges()return}apiErr := api.Client.CreateCustomModels(&modelsInput)- term.StopSpinner()if apiErr != nil {term.OutputErrorAndExit("Error importing models: %v", apiErr.Msg)return}+ // only write the hash if we're using the default path in the home dir+ // otherwise we don't do conflict checking, so we don't need the hash file+ if usingDefaultPath {+ hash, err := modelsInput.Hash()+ if err != nil {+ term.OutputErrorAndExit("Error hashing models: %v", err)+ return+ }++ err = os.WriteFile(hashPath, []byte(hash), 0644)+ if err != nil {+ term.OutputErrorAndExit("Error writing hash file: %v", err)+ return+ }+ }++ inputModelIds := map[string]bool{}+ inputProviderNames := map[string]bool{}+ inputModelPackNames := map[string]bool{}+ for _, model := range modelsInput.CustomModels {+ inputModelIds[string(model.ModelId)] = true+ }+ for _, provider := range modelsInput.CustomProviders {+ inputProviderNames[provider.Name] = true+ }+ for _, modelPack := range modelsInput.CustomModelPacks {+ inputModelPackNames[modelPack.Name] = true+ }++ updatedModelsInput := modelsInput.FilterUnchanged(&shared.ModelsInput{+ CustomModels: customModels,+ CustomProviders: customProviders,+ CustomModelPacks: customModelPacks,+ })++ term.StopSpinner()+added := strings.Builder{}updated := strings.Builder{}+ deleted := strings.Builder{}- for _, provider := range modelsInput.CustomProviders {+ for _, provider := range updatedModelsInput.CustomProviders {action := "β Added"builder := &addedif existsById[provider.Name] {@@ -370,8 +457,15 @@ func importCustomModels(cmd *cobra.Command, args []string) {color.New(term.ColorHiCyan).Sprint("provider"),color.New(color.Bold, term.ColorHiGreen).Sprint(provider.Name)))}+ for _, provider := range customProviders {+ if !inputProviderNames[provider.Name] {+ deleted.WriteString(fmt.Sprintf("β Removed custom %s β %s\n",+ color.New(term.ColorHiCyan).Sprint("provider"),+ color.New(color.Bold, term.ColorHiRed).Sprint(provider.Name)))+ }+ }- for _, model := range modelsInput.CustomModels {+ for _, model := range updatedModelsInput.CustomModels {action := "β Added"builder := &addedif existsById[string(model.ModelId)] {@@ -383,8 +477,15 @@ func importCustomModels(cmd *cobra.Command, args []string) {color.New(term.ColorHiCyan).Sprint("model"),color.New(color.Bold, term.ColorHiGreen).Sprint(string(model.ModelId))))}+ for _, model := range customModels {+ if !inputModelIds[string(model.ModelId)] {+ deleted.WriteString(fmt.Sprintf("β Removed custom %s β %s\n",+ color.New(term.ColorHiCyan).Sprint("model"),+ color.New(color.Bold, term.ColorHiRed).Sprint(string(model.ModelId))))+ }+ }- for _, modelPack := range modelsInput.CustomModelPacks {+ for _, modelPack := range updatedModelsInput.CustomModelPacks {action := "β Added"builder := &addedif existsById[modelPack.Name] {@@ -396,17 +497,22 @@ func importCustomModels(cmd *cobra.Command, args []string) {color.New(term.ColorHiCyan).Sprint("model pack"),color.New(color.Bold, term.ColorHiGreen).Sprint(modelPack.Name)))}+ for _, modelPack := range customModelPacks {+ if !inputModelPackNames[modelPack.Name] {+ deleted.WriteString(fmt.Sprintf("β Removed custom %s β %s\n",+ color.New(term.ColorHiCyan).Sprint("model pack"),+ color.New(color.Bold, term.ColorHiRed).Sprint(modelPack.Name)))+ }+ }++ if updated.Len()+added.Len()+deleted.Len() == 0 {+ printNoChanges()+ return+ }fmt.Print(added.String())fmt.Print(updated.String())-- // Clean up temp file if it was generated- 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)- }- }+ fmt.Print(deleted.String())}func models(cmd *cobra.Command, args []string) {@@ -829,14 +935,6 @@ func maybePromptAndOpen(path string) bool {return false}-func looksLikeEphemeralTemplate(p string) bool {- // covers cases where the user pasted the temp name manually- tmp := os.TempDir()- return strings.HasPrefix(p, tmp+string(os.PathSeparator)) &&- strings.HasPrefix(filepath.Base(p), "plandex-models-") &&- strings.HasSuffix(p, ".json")-}-func getExampleTemplate(isCloud bool) shared.ModelsInput {exampleProviderName := "togetherai"diff --git a/app/cli/cmd/set_model.go b/app/cli/cmd/set_model.goindex 7219a60d..6020740f 100644--- a/app/cli/cmd/set_model.go+++ b/app/cli/cmd/set_model.go@@ -24,10 +24,11 @@ func init() {}var modelsSetCmd = &cobra.Command{- Use: "set-model [model-set-or-role-or-setting] [property-or-value] [value]",- Short: "Update current plan model settings",- Run: modelsSet,- Args: cobra.MaximumNArgs(3),+ Use: "set-model [model-set-or-role-or-setting] [property-or-value] [value]",+ Aliases: []string{"set-models"},+ Short: "Update current plan model settings",+ Run: modelsSet,+ Args: cobra.MaximumNArgs(3),}var defaultModelSetCmd = &cobra.Command{diff --git a/app/server/db/data_models.go b/app/server/db/data_models.goindex c2bec0ff..dedc4931 100644--- a/app/server/db/data_models.go+++ b/app/server/db/data_models.go@@ -318,32 +318,34 @@ type ModelPack struct {func ModelPackFromApi(apiModelPack *shared.ModelPack) *ModelPack {return &ModelPack{- Name: apiModelPack.Name,- Description: apiModelPack.Description,- Planner: apiModelPack.Planner,- Architect: apiModelPack.Architect,- Coder: apiModelPack.Coder,- PlanSummary: apiModelPack.PlanSummary,- Builder: apiModelPack.Builder,- Namer: apiModelPack.Namer,- CommitMsg: apiModelPack.CommitMsg,- ExecStatus: apiModelPack.ExecStatus,+ Name: apiModelPack.Name,+ Description: apiModelPack.Description,+ Planner: apiModelPack.Planner,+ Architect: apiModelPack.Architect,+ Coder: apiModelPack.Coder,+ PlanSummary: apiModelPack.PlanSummary,+ Builder: apiModelPack.Builder,+ WholeFileBuilder: apiModelPack.WholeFileBuilder,+ Namer: apiModelPack.Namer,+ CommitMsg: apiModelPack.CommitMsg,+ ExecStatus: apiModelPack.ExecStatus,}}func (modelPack *ModelPack) ToApi() *shared.ModelPack {return &shared.ModelPack{- Id: modelPack.Id,- Name: modelPack.Name,- Description: modelPack.Description,- Planner: modelPack.Planner,- Architect: modelPack.Architect,- Coder: modelPack.Coder,- PlanSummary: modelPack.PlanSummary,- Builder: modelPack.Builder,- Namer: modelPack.Namer,- CommitMsg: modelPack.CommitMsg,- ExecStatus: modelPack.ExecStatus,+ Id: modelPack.Id,+ Name: modelPack.Name,+ Description: modelPack.Description,+ Planner: modelPack.Planner,+ Architect: modelPack.Architect,+ Coder: modelPack.Coder,+ PlanSummary: modelPack.PlanSummary,+ Builder: modelPack.Builder,+ WholeFileBuilder: modelPack.WholeFileBuilder,+ Namer: modelPack.Namer,+ CommitMsg: modelPack.CommitMsg,+ ExecStatus: modelPack.ExecStatus,}}diff --git a/app/server/handlers/models.go b/app/server/handlers/models.goindex 8b2e6eac..b3d941d8 100644--- a/app/server/handlers/models.go+++ b/app/server/handlers/models.go@@ -16,7 +16,7 @@ import (const CustomModelsMinClientVersion = "2.2.0"-func CreateCustomModelHandler(w http.ResponseWriter, r *http.Request) {+func UpsertCustomModelsHandler(w http.ResponseWriter, r *http.Request) {log.Println("Received request for CreateCustomModelHandler")auth := Authenticate(w, r, true)@@ -115,6 +115,27 @@ func CreateCustomModelHandler(w http.ResponseWriter, r *http.Request) {}}+ apiCustomModels := make([]*shared.CustomModel, len(customModels))+ for i, model := range customModels {+ apiCustomModels[i] = model.ToApi()+ }++ apiCustomProviders := make([]*shared.CustomProvider, len(customProviders))+ for i, provider := range customProviders {+ apiCustomProviders[i] = provider.ToApi()+ }++ apiCustomModelPacks := make([]*shared.ModelPackSchema, len(customModelPacks))+ for i, modelPack := range customModelPacks {+ apiCustomModelPacks[i] = modelPack.ToApi().ToModelPackSchema()+ }++ updatedModelsInput := modelsInput.FilterUnchanged(&shared.ModelsInput{+ CustomModels: apiCustomModels,+ CustomProviders: apiCustomProviders,+ CustomModelPacks: apiCustomModelPacks,+ })+for _, model := range customModels {existingCustomModelIds[model.ModelId] = true}@@ -123,27 +144,27 @@ func CreateCustomModelHandler(w http.ResponseWriter, r *http.Request) {existingCustomProviderNames[provider.Name] = true}- willUpsertModelIds := make(map[string]bool)- willUpsertProviderNames := make(map[string]bool)- willUpsertModelPackNames := make(map[string]bool)+ inputModelIds := make(map[string]bool)+ inputProviderNames := make(map[string]bool)+ inputModelPackNames := make(map[string]bool)for _, model := range modelsInput.CustomModels {- willUpsertModelIds[string(model.ModelId)] = true+ inputModelIds[string(model.ModelId)] = true}for _, provider := range modelsInput.CustomProviders {- willUpsertProviderNames[provider.Name] = true+ inputProviderNames[provider.Name] = true}for _, modelPack := range modelsInput.CustomModelPacks {- willUpsertModelPackNames[modelPack.Name] = true+ inputModelPackNames[modelPack.Name] = true}var toUpsertCustomModels []*db.CustomModelvar toUpsertCustomProviders []*db.CustomProvidervar toUpsertModelPacks []*db.ModelPack- for _, provider := range modelsInput.CustomProviders {+ for _, provider := range updatedModelsInput.CustomProviders {dbProvider := db.CustomProviderFromApi(provider)dbProvider.Id = provider.IddbProvider.OrgId = auth.OrgId@@ -151,12 +172,12 @@ func CreateCustomModelHandler(w http.ResponseWriter, r *http.Request) {toUpsertCustomProviders = append(toUpsertCustomProviders, dbProvider)}- for _, model := range modelsInput.CustomModels {- // ensure that providers are either built-in, being created, or already exist+ for _, model := range updatedModelsInput.CustomModels {+ // ensure that providers to upsert are either built-in, being created, or already existfor _, provider := range model.Providers {if provider.Provider == shared.ModelProviderCustom {_, exists := existingCustomProviderNames[*provider.CustomProvider]- _, creating := willUpsertProviderNames[*provider.CustomProvider]+ _, creating := inputProviderNames[*provider.CustomProvider]if !exists && !creating {msg := fmt.Sprintf("'%s' is not a custom model provider that exists or is being created", *provider.CustomProvider)log.Println(msg)@@ -181,13 +202,13 @@ func CreateCustomModelHandler(w http.ResponseWriter, r *http.Request) {toUpsertCustomModels = append(toUpsertCustomModels, dbModel)}- for _, modelPack := range modelsInput.CustomModelPacks {+ for _, modelPack := range updatedModelsInput.CustomModelPacks {// ensure that all models are either built-in, being created, or already existallModelIds := modelPack.AllModelIds()for _, modelId := range allModelIds {_, exists := existingCustomModelIds[modelId]- _, creating := willUpsertModelIds[string(modelId)]+ _, creating := inputModelIds[string(modelId)]_, builtIn := shared.BuiltInBaseModelsById[modelId]if !exists && !creating && !builtIn {@@ -211,19 +232,19 @@ func CreateCustomModelHandler(w http.ResponseWriter, r *http.Request) {toDeleteModelPackIds := []string{}for _, model := range customModels {- if _, exists := willUpsertModelIds[string(model.ModelId)]; !exists {+ if _, exists := inputModelIds[string(model.ModelId)]; !exists {toDeleteCustomModelIds = append(toDeleteCustomModelIds, model.Id)}}for _, provider := range customProviders {- if _, exists := willUpsertProviderNames[provider.Name]; !exists {+ if _, exists := inputProviderNames[provider.Name]; !exists {toDeleteCustomProviderIds = append(toDeleteCustomProviderIds, provider.Id)}}for _, modelPack := range customModelPacks {- if _, exists := willUpsertModelPackNames[modelPack.Name]; !exists {+ if _, exists := inputModelPackNames[modelPack.Name]; !exists {toDeleteModelPackIds = append(toDeleteModelPackIds, modelPack.Id)}}diff --git a/app/server/routes/routes.go b/app/server/routes/routes.goindex f63fbc0c..a4f36d61 100644--- a/app/server/routes/routes.go+++ b/app/server/routes/routes.go@@ -163,7 +163,7 @@ func addApiRoutes(r *mux.Router, prefix string) {HandlePlandexFn(r, prefix+"/plans/{planId}/{branch}/build", true, handlers.BuildPlanHandler).Methods("PATCH")HandlePlandexFn(r, prefix+"/custom_models", false, handlers.ListCustomModelsHandler).Methods("GET")- HandlePlandexFn(r, prefix+"/custom_models", false, handlers.CreateCustomModelHandler).Methods("POST")+ HandlePlandexFn(r, prefix+"/custom_models", false, handlers.UpsertCustomModelsHandler).Methods("POST")HandlePlandexFn(r, prefix+"/custom_models/{modelId}", false, handlers.GetCustomModelHandler).Methods("GET")diff --git a/app/shared/ai_models_custom.go b/app/shared/ai_models_custom.goindex 2aea8f9b..fe293bb8 100644--- a/app/shared/ai_models_custom.go+++ b/app/shared/ai_models_custom.go@@ -1,6 +1,9 @@package sharedimport (+ "crypto/sha256"+ "encoding/hex"+ "encoding/json""fmt""strings""time"@@ -13,6 +16,8 @@ type SchemaUrl stringconst SchemaUrlInputConfig SchemaUrl = "https://plandex.ai/schemas/models-input.schema.json"+// Note that none of the custom model structs should have maps anywhere in the hierarchy, since it will break deterministic hashing. Use structs or slices instead.+type CustomModel struct {Id string `json:"id,omitempty"`ModelId ModelId `json:"modelId"`@@ -91,6 +96,13 @@ func (input ModelsInput) FilterUnchanged(existing *ModelsInput) ModelsInput {return filtered}+func (input ModelsInput) Equals(other ModelsInput) bool {+ left := input.FilterUnchanged(&other)+ right := other.FilterUnchanged(&input)++ return left.IsEmpty() && right.IsEmpty()+}+func (input ModelsInput) CheckNoDuplicates() (bool, string) {sawModelIds := map[ModelId]bool{}sawProviderNames := map[string]bool{}@@ -154,12 +166,31 @@ func modelsEqual(a, b *CustomModel) bool {func providersEqual(a, b *CustomProvider) bool {return cmp.Equal(- a, b,+ a,+ b,cmpopts.EquateEmpty(),cmpopts.IgnoreFields(CustomProvider{}, "CreatedAt", "UpdatedAt", "Id"),)}func packsEqual(a, b *ModelPackSchema) bool {- return cmp.Equal(a, b, cmpopts.EquateEmpty())+ res := cmp.Equal(+ a,+ b,+ cmpopts.EquateEmpty(),+ )+ return res+}++// Hash returns a deterministic hash of the ModelsInput.+// WARNING: This relies on json.Marshal being deterministic for our struct types.+// Do not add map fields to these structs or the hash will become non-deterministic.+func (input ModelsInput) Hash() (string, error) {+ data, err := json.Marshal(input)+ if err != nil {+ return "", err+ }++ hash := sha256.Sum256(data)+ return hex.EncodeToString(hash[:]), nil}