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
refactor model settings logic, check for models file updates prior to prompts, and sync server state after rewind or checkout
Dane Schneider101567b7bf35
diff --git a/app/cli/cmd/checkout.go b/app/cli/cmd/checkout.goindex 2d49c828..acb0f556 100644--- a/app/cli/cmd/checkout.go+++ b/app/cli/cmd/checkout.go@@ -122,10 +122,9 @@ func checkout(cmd *cobra.Command, args []string) {term.OutputErrorAndExit("Branch not found")}+ term.StartSpinner("")if willCreate {- term.StartSpinner("")err := api.Client.CreateBranch(lib.CurrentPlanId, lib.CurrentBranch, shared.CreateBranchRequest{Name: branchName})- term.StopSpinner()if err != nil {term.OutputErrorAndExit("Error creating branch: %v", err)@@ -142,8 +141,21 @@ func checkout(cmd *cobra.Command, args []string) {return}+ updatedModelSettings, err := lib.SaveLatestPlanModelSettingsIfNeeded()+ term.StopSpinner()+ if err != nil {+ term.OutputErrorAndExit("Error saving model settings: %v", err)+ }++ term.StopSpinner()+fmt.Printf("β Checked out branch %s\n", color.New(color.Bold, term.ColorHiGreen).Sprint(branchName))+ if updatedModelSettings {+ fmt.Println()+ fmt.Println("π§ Model settings file updated β ", lib.GetPlanModelSettingsPath(lib.CurrentPlanId))+ }+fmt.Println()term.PrintCmds("", "load", "tell", "branches", "delete-branch")diff --git a/app/cli/cmd/models.go b/app/cli/cmd/models.goindex 2e7192d8..783a7b41 100644--- a/app/cli/cmd/models.go+++ b/app/cli/cmd/models.go@@ -5,13 +5,11 @@ import ("fmt""os""path/filepath"- "strings""plandex-cli/api""plandex-cli/auth""plandex-cli/fs""plandex-cli/lib"- "plandex-cli/schema""plandex-cli/term""strconv"@@ -97,112 +95,32 @@ func manageCustomModels(cmd *cobra.Command, args []string) {term.StartSpinner("")- 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() {- // 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() {- modelPacks, apiErr := api.Client.ListModelPacks()- if apiErr != nil {- errCh <- apiErr- return- }-- schemas := make([]*shared.ModelPackSchema, len(modelPacks))- for i, modelPack := range modelPacks {- schemas[i] = modelPack.ToModelPackSchema()- }-- 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- }- }-- 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- }-- serverModelsInput := &shared.ModelsInput{- CustomModels: customModels,- CustomProviders: customProviders,- CustomModelPacks: customModelPacks,+ serverModelsInput, err := lib.GetServerModelsInput()+ if err != nil {+ term.OutputErrorAndExit("Error getting server models input: %v", err)+ return}usingDefaultPath := falseif customModelsPath == "" {usingDefaultPath = true- customModelsPath = filepath.Join(fs.HomePlandexDir, "custom-models.json")+ customModelsPath = lib.CustomModelsDefaultPath}- hashPath := customModelsPath + ".hash"-- exists := false- _, err := os.Stat(customModelsPath)- if err == nil {- exists = true- } else if os.IsNotExist(err) {- exists = false- } else {++ exists, err := fs.FileExists(customModelsPath)+ if err != nil {term.OutputErrorAndExit("Error checking custom models file: %v", err)return}- var jsonData []byte-if saveCustomModels {if !exists {term.OutputErrorAndExit("File not found: %s", customModelsPath)return}- jsonData, err = os.ReadFile(customModelsPath)- if err != nil {- term.OutputErrorAndExit("Error reading JSON file: %v", err)- return- }} else {if serverModelsInput.IsEmpty() {- jsonData, err = json.MarshalIndent(getExampleTemplate(auth.Current.IsCloud), "", " ")+ jsonData, err := json.MarshalIndent(getExampleTemplate(auth.Current.IsCloud), "", " ")if err != nil {term.OutputErrorAndExit("Error marshalling template: %v", err)return@@ -228,42 +146,21 @@ func manageCustomModels(cmd *cobra.Command, args []string) {} else {serverClientModelsInput := serverModelsInput.ToClientModelsInput()serverClientModelsInput.PrepareUpdate()- var localClientModelsInput shared.ClientModelsInput+var localModelsInput shared.ModelsInput- var localJsonData []byteif exists {- localJsonData, err = os.ReadFile(customModelsPath)- if err != nil {- term.OutputErrorAndExit("Error reading JSON file: %v", err)- return- }-- err = json.Unmarshal(localJsonData, &localClientModelsInput)- if err != nil {- term.OutputErrorAndExit("Error unmarshalling JSON file: %v", err)- return- }-- localModelsInput = localClientModelsInput.ToModelsInput()-// 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 stringif usingDefaultPath {- lastSavedHash, err := os.ReadFile(hashPath)- if err != nil && !os.IsNotExist(err) {- term.OutputErrorAndExit("Error reading hash file: %v", err)- return- }-- currentHash, err = localModelsInput.Hash()+ res, err := lib.CustomModelsCheckLocalChanges(customModelsPath)if err != nil {- term.OutputErrorAndExit("Error hashing models: %v", err)+ term.OutputErrorAndExit("Error checking local changes: %v", err)return}- if currentHash != string(lastSavedHash) {+ localModelsInput = res.LocalModelsInput+ if res.HasLocalChanges {term.StopSpinner()res, err := warnModelsFileLocalChanges(customModelsPath, "models custom")@@ -280,33 +177,12 @@ func manageCustomModels(cmd *cobra.Command, args []string) {}}- if serverModelsInput.Equals(localModelsInput) {- jsonData = localJsonData- } else {- jsonData, err = json.MarshalIndent(serverClientModelsInput, "", " ")+ if !serverModelsInput.Equals(localModelsInput) {+ err := lib.WriteCustomModelsFile(customModelsPath, serverModelsInput, true)if err != nil {- term.OutputErrorAndExit("Error marshalling models: %v", err)+ term.OutputErrorAndExit("Error saving custom models file: %v", err)return}-- err = os.WriteFile(customModelsPath, jsonData, 0644)- if err != nil {- term.OutputErrorAndExit("Error writing file: %v", err)- return- }-- hash, err := serverModelsInput.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- }-}term.StopSpinner()@@ -325,156 +201,13 @@ func manageCustomModels(cmd *cobra.Command, args []string) {if res.shouldReturn {return}- jsonData = res.jsonData}- term.StartSpinner("")+ didUpdate := lib.MustSyncCustomModels(customModelsPath, serverModelsInput, saveCustomModels)- clientModelsInput, 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- }-- modelsInput := clientModelsInput.ToModelsInput()-- 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- }-- printNoChanges := func() {- term.StopSpinner()+ if !didUpdate {fmt.Println("π€·ββοΈ No changes to custom models/providers/model packs")}-- if modelsInput.Equals(*serverModelsInput) {- printNoChanges()- return- }-- apiErr := api.Client.CreateCustomModels(&modelsInput)-- 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 clientModelsInput.CustomModels {- inputModelIds[string(model.ModelId)] = true- }- for _, provider := range clientModelsInput.CustomProviders {- inputProviderNames[provider.Name] = true- }- for _, modelPack := range clientModelsInput.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 updatedModelsInput.CustomProviders {- 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)))- }- 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 updatedModelsInput.CustomModels {- 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))))- }- 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 updatedModelsInput.CustomModelPacks {- 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)))- }- 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())- fmt.Print(deleted.String())}func models(cmd *cobra.Command, args []string) {diff --git a/app/cli/cmd/rewind.go b/app/cli/cmd/rewind.goindex 2f0bab95..c246f49b 100644--- a/app/cli/cmd/rewind.go+++ b/app/cli/cmd/rewind.go@@ -149,16 +149,25 @@ func rewind(cmd *cobra.Command, args []string) {}doRewind := func() {+ var updatedModelSettings bool+term.StartSpinner("")_, apiErr := api.Client.RewindPlan(lib.CurrentPlanId, lib.CurrentBranch, shared.RewindPlanRequest{Sha: targetSha,})- term.StopSpinner()if apiErr != nil {+ term.StopSpinner()term.OutputErrorAndExit("Error rewinding plan: %v", apiErr)}+ var err error+ updatedModelSettings, err = lib.SaveLatestPlanModelSettingsIfNeeded()+ term.StopSpinner()+ if err != nil {+ term.OutputErrorAndExit("Error saving model settings: %v", err)+ }+var msg stringif isSha {msg = "β Rewound to " + targetSha@@ -171,6 +180,11 @@ func rewind(cmd *cobra.Command, args []string) {}fmt.Println(msg)++ if updatedModelSettings {+ fmt.Println()+ fmt.Println("π§ Model settings file updated β ", lib.GetPlanModelSettingsPath(lib.CurrentPlanId))+ }fmt.Println()}diff --git a/app/cli/cmd/set_model.go b/app/cli/cmd/set_model.goindex e1d59dbd..99663dbb 100644--- a/app/cli/cmd/set_model.go+++ b/app/cli/cmd/set_model.go@@ -1,15 +1,12 @@package cmdimport (- "encoding/json""fmt""os"- "path/filepath""plandex-cli/api""plandex-cli/auth""plandex-cli/fs""plandex-cli/lib"- "plandex-cli/schema""plandex-cli/term""strings"@@ -64,7 +61,7 @@ func modelsSet(cmd *cobra.Command, args []string) {return}- defaultPath := filepath.Join(fs.HomePlandexDir, lib.CurrentPlanId, "model-settings.json")+ defaultPath := lib.GetPlanModelSettingsPath(lib.CurrentPlanId)settings := updateModelSettings(args, originalSettings, defaultPath)@@ -107,7 +104,7 @@ func defaultModelsSet(cmd *cobra.Command, args []string) {return}- defaultPath := filepath.Join(fs.HomePlandexDir, "default-model-settings.json")+ defaultPath := lib.DefaultModelSettingsPathsettings := updateModelSettings(args, originalSettings, defaultPath)@@ -196,56 +193,26 @@ func updateModelSettings(args []string, originalSettings *shared.PlanSettings, dusingDefaultPath = truesetModelJsonFilePath = defaultPath}- hashPath := setModelJsonFilePath + ".hash"-- exists := false- _, err := os.Stat(setModelJsonFilePath)- if err == nil {- exists = true- } else if os.IsNotExist(err) {- exists = false- } else {- term.OutputErrorAndExit("Error checking custom models file: %v", err)++ exists, err := fs.FileExists(setModelJsonFilePath)+ if err != nil {+ term.OutputErrorAndExit("Error checking model settings file: %v", err)return nil}- var jsonData []byte-if saveCustomModels {if !exists {term.OutputErrorAndExit("File not found: %s", customModelsPath)}- jsonData, err = os.ReadFile(setModelJsonFilePath)- if err != nil {- term.OutputErrorAndExit("Error reading JSON file: %v", err)- return nil- }} else {if usingDefaultPath && exists {- lastSavedHash, err := os.ReadFile(hashPath)- if err != nil && !os.IsNotExist(err) {- term.OutputErrorAndExit("Error reading hash file: %v", err)- return nil- }-- localJsonData, err := os.ReadFile(setModelJsonFilePath)- if err != nil {- term.OutputErrorAndExit("Error reading JSON file: %v", err)- }-- var localModelPackSchemaRoles *shared.ClientModelPackSchemaRoles- err = json.Unmarshal(localJsonData, &localModelPackSchemaRoles)- if err != nil {- term.OutputErrorAndExit("Error unmarshalling JSON file: %v", err)- }-- currentHash, err := localModelPackSchemaRoles.ToModelPackSchemaRoles().Hash()+ modelSettingsCheckLocalChangesResult, err := lib.ModelSettingsCheckLocalChanges(setModelJsonFilePath)if err != nil {- term.OutputErrorAndExit("Error hashing model pack: %v", err)+ term.OutputErrorAndExit("Error checking model settings file: %v", err)return nil}- if currentHash != string(lastSavedHash) {+ if modelSettingsCheckLocalChangesResult.HasLocalChanges {term.StopSpinner()res, err := warnModelsFileLocalChanges(setModelJsonFilePath, "set-model")@@ -262,22 +229,9 @@ func updateModelSettings(args []string, originalSettings *shared.PlanSettings, d}}- err = os.MkdirAll(filepath.Dir(setModelJsonFilePath), 0755)+ err = lib.WriteModelSettingsFile(setModelJsonFilePath, originalSettings)if err != nil {- term.OutputErrorAndExit("Error creating directory: %v", err)- return nil- }-- clientModelPackRoles := originalSettings.GetModelPack().ToModelPackSchema().ToClientModelPackSchemaRoles()- bytes, err := json.MarshalIndent(clientModelPackRoles, "", " ")- if err != nil {- term.OutputErrorAndExit("Error marshalling model pack: %v", err)- return nil- }-- err = os.WriteFile(setModelJsonFilePath, bytes, 0644)- if err != nil {- term.OutputErrorAndExit("Error writing JSON file: %v", err)+ term.OutputErrorAndExit("Error writing model settings file: %v", err)return nil}@@ -295,36 +249,14 @@ func updateModelSettings(args []string, originalSettings *shared.PlanSettings, dif res.shouldReturn {return nil}- jsonData = res.jsonData}term.StartSpinner("")- clientModelPackRoles, err := schema.ValidateModelPackInlineJSON(jsonData)- if err != nil {- term.StopSpinner()- color.New(color.Bold, term.ColorHiRed).Println("π¨ Error validating JSON file")- fmt.Println(err.Error())- os.Exit(1)- }- modelPackRoles := clientModelPackRoles.ToModelPackSchemaRoles()-- modelPackSchema := shared.ModelPackSchema{- Name: "custom",- Description: "Model pack with custom settings",- ModelPackSchemaRoles: modelPackRoles,- }- modelPack := modelPackSchema.ToModelPack()- settings.SetCustomModelPack(&modelPack)+ settings, err = lib.ApplyModelSettings(setModelJsonFilePath, originalSettings)- hash, err := modelPackRoles.Hash()- if err != nil {- term.OutputErrorAndExit("Error hashing model pack: %v", err)- return nil- }- err = os.WriteFile(hashPath, []byte(hash), 0644)if err != nil {- term.OutputErrorAndExit("Error writing hash file: %v", err)+ term.OutputErrorAndExit("Error applying model settings: %v", err)return nil}diff --git a/app/cli/fs/utils.go b/app/cli/fs/utils.gonew file mode 100644index 00000000..4aa52d0b--- /dev/null+++ b/app/cli/fs/utils.go@@ -0,0 +1,17 @@+package fs++import (+ "fmt"+ "os"+)++func FileExists(path string) (bool, error) {+ _, err := os.Stat(path)+ if err == nil {+ return true, nil+ } else if os.IsNotExist(err) {+ return false, nil+ } else {+ return false, fmt.Errorf("error checking if file exists: %v", err)+ }+}diff --git a/app/cli/lib/apply.go b/app/cli/lib/apply.goindex 9d626207..9c441af1 100644--- a/app/cli/lib/apply.go+++ b/app/cli/lib/apply.go@@ -58,6 +58,13 @@ func MustApplyPlanAttempt(term.StartSpinner("")+ err := PromptSyncModelsIfNeeded()+ if err != nil {+ term.OutputErrorAndExit("Error syncing models: %v", err)+ }++ term.StartSpinner("")+currentPlanState, apiErr := api.Client.GetCurrentPlanState(planId, branch)if apiErr != nil {diff --git a/app/cli/lib/custom_models.go b/app/cli/lib/custom_models.gonew file mode 100644index 00000000..ccd890ed--- /dev/null+++ b/app/cli/lib/custom_models.go@@ -0,0 +1,344 @@+package lib++import (+ "encoding/json"+ "fmt"+ "os"+ "path/filepath"+ "plandex-cli/api"+ "plandex-cli/auth"+ "plandex-cli/fs"+ "plandex-cli/schema"+ "plandex-cli/term"+ shared "plandex-shared"+ "strings"++ "github.com/fatih/color"+)++var CustomModelsDefaultPath string++type CustomModelsCheckLocalChangesResult struct {+ HasLocalChanges bool+ LocalModelsInput shared.ModelsInput+}++func init() {+ CustomModelsDefaultPath = filepath.Join(fs.HomePlandexDir, "custom-models.json")+}++func GetServerModelsInput() (*shared.ModelsInput, error) {+ 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() {+ // 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() {+ modelPacks, apiErr := api.Client.ListModelPacks()+ if apiErr != nil {+ errCh <- apiErr+ return+ }++ schemas := make([]*shared.ModelPackSchema, len(modelPacks))+ for i, modelPack := range modelPacks {+ schemas[i] = modelPack.ToModelPackSchema()+ }++ customModelPacks = schemas+ errCh <- nil+ }()++ for i := 0; i < 3; i++ {+ err := <-errCh+ if err != nil {+ return nil, fmt.Errorf("error fetching custom models: %v", err.Msg)+ }+ }++ serverModelsInput := &shared.ModelsInput{+ CustomModels: customModels,+ CustomProviders: customProviders,+ CustomModelPacks: customModelPacks,+ }++ return serverModelsInput, nil+}++func CustomModelsCheckLocalChanges(path string) (CustomModelsCheckLocalChangesResult, error) {+ hashPath := path + ".hash"++ exists, err := fs.FileExists(path)+ if err != nil {+ return CustomModelsCheckLocalChangesResult{}, err+ }++ if !exists {+ return CustomModelsCheckLocalChangesResult{}, nil+ }++ localJsonData, err := os.ReadFile(path)+ if err != nil {+ return CustomModelsCheckLocalChangesResult{}, fmt.Errorf("error reading JSON file: %v", err)+ }++ var localClientModelsInput shared.ClientModelsInput+ err = json.Unmarshal(localJsonData, &localClientModelsInput)+ if err != nil {+ return CustomModelsCheckLocalChangesResult{}, fmt.Errorf("error unmarshalling JSON file: %v", err)+ }++ localModelsInput := localClientModelsInput.ToModelsInput()++ lastSavedHash, err := os.ReadFile(hashPath)+ if err != nil && !os.IsNotExist(err) {+ return CustomModelsCheckLocalChangesResult{}, fmt.Errorf("error reading hash file: %v", err)+ }++ currentHash, err := localModelsInput.Hash()+ if err != nil {+ return CustomModelsCheckLocalChangesResult{}, fmt.Errorf("error hashing models: %v", err)+ }++ return CustomModelsCheckLocalChangesResult{+ HasLocalChanges: currentHash != string(lastSavedHash),+ LocalModelsInput: localModelsInput,+ }, nil+}++func WriteCustomModelsFile(path string, modelsInput *shared.ModelsInput, saveHash bool) error {+ err := os.MkdirAll(filepath.Dir(path), 0755)+ if err != nil {+ return fmt.Errorf("error creating directory: %v", err)+ }++ clientModelsInput := modelsInput.ToClientModelsInput()+ clientModelsInput.PrepareUpdate()++ jsonData, err := json.MarshalIndent(clientModelsInput, "", " ")+ if err != nil {+ return fmt.Errorf("error marshalling models: %v", err)+ }++ err = os.WriteFile(path, jsonData, 0644)+ if err != nil {+ return fmt.Errorf("error writing file: %v", err)+ }++ if saveHash {+ err = SaveCustomModelsHash(path, modelsInput)+ if err != nil {+ return fmt.Errorf("error saving hash file: %v", err)+ }+ }++ return nil+}++func SaveCustomModelsHash(basePath string, modelsInput *shared.ModelsInput) error {+ hashPath := basePath + ".hash"++ hash, err := modelsInput.Hash()+ if err != nil {+ return fmt.Errorf("error hashing models: %v", err)+ }++ err = os.WriteFile(hashPath, []byte(hash), 0644)+ if err != nil {+ return fmt.Errorf("error writing hash file: %v", err)+ }++ return nil+}++func MustSyncCustomModels(path string, serverModelsInput *shared.ModelsInput, saveHash bool) bool {+ term.StartSpinner("")++ jsonData, err := os.ReadFile(path)+ if err != nil {+ term.OutputErrorAndExit("Error reading custom models file: %v", err)+ return false+ }++ clientModelsInput, err := schema.ValidateModelsInputJSON(jsonData)+ if err != nil {+ term.StopSpinner()+ color.New(color.Bold, term.ColorHiRed).Println("π¨ Error validating custom models file")+ fmt.Println(err.Error())+ return false+ }++ modelsInput := clientModelsInput.ToModelsInput()++ noDuplicates, errMsg := modelsInput.CheckNoDuplicates()+ if !noDuplicates {+ term.StopSpinner()+ color.New(color.Bold, term.ColorHiRed).Println("π¨ Some items in custom models file are duplicated:")+ fmt.Println()+ fmt.Println(errMsg)+ return false+ }++ if modelsInput.Equals(*serverModelsInput) {+ term.StopSpinner()+ return false+ }++ apiErr := api.Client.CreateCustomModels(&modelsInput)+ if apiErr != nil {+ term.OutputErrorAndExit("Error importing models: %v", apiErr.Msg)+ return false+ }++ if saveHash {+ err := SaveCustomModelsHash(path, &modelsInput)+ if err != nil {+ term.OutputErrorAndExit("Error saving hash file: %v", err)+ return false+ }+ }++ inputModelIds := map[string]bool{}+ inputProviderNames := map[string]bool{}+ inputModelPackNames := map[string]bool{}+ for _, model := range clientModelsInput.CustomModels {+ inputModelIds[string(model.ModelId)] = true+ }+ for _, provider := range clientModelsInput.CustomProviders {+ inputProviderNames[provider.Name] = true+ }+ for _, modelPack := range clientModelsInput.CustomModelPacks {+ inputModelPackNames[modelPack.Name] = true+ }++ updatedModelsInput := modelsInput.FilterUnchanged(serverModelsInput)++ customModels := serverModelsInput.CustomModels+ customProviders := serverModelsInput.CustomProviders+ customModelPacks := serverModelsInput.CustomModelPacks++ term.StopSpinner()++ added := strings.Builder{}+ updated := strings.Builder{}+ deleted := strings.Builder{}++ 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 _, provider := range updatedModelsInput.CustomProviders {+ 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)))+ }+ 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 updatedModelsInput.CustomModels {+ 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))))+ }+ 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 updatedModelsInput.CustomModelPacks {+ 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)))+ }+ 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 {+ return false+ }++ fmt.Print(added.String())+ fmt.Print(updated.String())+ fmt.Print(deleted.String())++ return true+}++func SyncCustomModels() error {+ serverModelsInput, err := GetServerModelsInput()+ if err != nil {+ return fmt.Errorf("error getting server models input: %v", err)+ }++ MustSyncCustomModels(CustomModelsDefaultPath, serverModelsInput, true)++ return nil+}diff --git a/app/cli/lib/editor.go b/app/cli/lib/editor.goindex 36305c85..71984990 100644--- a/app/cli/lib/editor.go+++ b/app/cli/lib/editor.go@@ -4,10 +4,54 @@ import ("os""os/exec""path/filepath"+ "plandex-cli/term""sort""strings")+func MaybePromptAndOpen(path string) bool {+ editors := detectEditors()+ if len(editors) == 0 {+ // just exit if there are no editors available+ return false+ }+ opts := []string{}+ for _, c := range editors {+ opts = append(opts, "Open with "+c.name)+ }++ const openManually = "Open manually"+ opts = append(opts, openManually)++ choice, err := term.SelectFromList("Open the file now?", opts)+ if err != nil {+ term.OutputErrorAndExit("Error selecting editor: %v", err)+ }++ if choice == openManually {+ return false+ }++ var idx int+ for i, c := range opts {+ if c == choice {+ idx = i+ break+ }+ }++ if idx < len(editors) {+ sel := editors[idx]+ err = exec.Command(sel.cmd, append(sel.args, path)...).Start()+ if err != nil {+ term.OutputErrorAndExit("Error opening template: %v", err)+ }+ return true+ }++ return false+}+type editorCandidate struct {name stringcmd stringdiff --git a/app/cli/lib/model_settings.go b/app/cli/lib/model_settings.goindex a322b92e..ec19eef4 100644--- a/app/cli/lib/model_settings.go+++ b/app/cli/lib/model_settings.go@@ -1,105 +1,248 @@package libimport (+ "encoding/json""fmt"- "os/exec"+ "os"+ "path/filepath"+ "plandex-cli/api"+ "plandex-cli/fs"+ "plandex-cli/schema""plandex-cli/term"-shared "plandex-shared"++ "github.com/fatih/color")-const GoBack = "β Go back"+var DefaultModelSettingsPath string-func SelectModelIdForRole(customModels []*shared.CustomModel, role shared.ModelRole) shared.ModelId {- builtInModels := shared.FilterBuiltInCompatibleModels(shared.BuiltInBaseModels, role)- customModels = shared.FilterCustomCompatibleModels(customModels, role)+func init() {+ DefaultModelSettingsPath = filepath.Join(fs.HomePlandexDir, "default-model-settings.json")+}- for {- var selectableModelIds []shared.ModelId- opts := []string{}+func GetPlanModelSettingsPath(planId string) string {+ return filepath.Join(fs.HomePlandexDir, planId, "model-settings.json")+}- for _, m := range builtInModels {- label := fmt.Sprintf("%s | max %d πͺ", m.ModelId, m.MaxTokens)- opts = append(opts, label)- selectableModelIds = append(selectableModelIds, m.ModelId)- }+type ModelSettingsCheckLocalChangesResult struct {+ HasLocalChanges bool+ LocalModelPackSchemaRoles *shared.ModelPackSchemaRoles+}- for _, m := range customModels {- label := fmt.Sprintf("%s | max %d πͺ", m.ModelId, m.MaxTokens)- opts = append(opts, label)- selectableModelIds = append(selectableModelIds, m.ModelId)- }+func ModelSettingsCheckLocalChanges(path string) (ModelSettingsCheckLocalChangesResult, error) {+ hashPath := path + ".hash"- opts = append(opts, GoBack)+ exists, err := fs.FileExists(path)+ if err != nil {+ return ModelSettingsCheckLocalChangesResult{}, fmt.Errorf("error checking model settings file: %v", err)+ }- selection, err := term.SelectFromList("Select a model:", opts)+ if !exists {+ return ModelSettingsCheckLocalChangesResult{}, nil+ }- if err != nil {- if err.Error() == "interrupt" {- return ""- }+ lastSavedHash, err := os.ReadFile(hashPath)+ if err != nil && !os.IsNotExist(err) {+ return ModelSettingsCheckLocalChangesResult{}, fmt.Errorf("error reading hash file: %v", err)+ }- term.OutputErrorAndExit("Error selecting model: %v", err)- return ""- }+ localJsonData, err := os.ReadFile(path)+ if err != nil {+ return ModelSettingsCheckLocalChangesResult{}, fmt.Errorf("error reading JSON file: %v", err)+ }- if selection == GoBack {- continue- }+ var clientModelPackSchemaRoles *shared.ClientModelPackSchemaRoles+ err = json.Unmarshal(localJsonData, &clientModelPackSchemaRoles)+ if err != nil {+ return ModelSettingsCheckLocalChangesResult{}, fmt.Errorf("error unmarshalling JSON file: %v", err)+ }- var idx int- for i := range opts {- if opts[i] == selection {- idx = i- break- }- }+ currentHash, err := clientModelPackSchemaRoles.ToModelPackSchemaRoles().Hash()+ if err != nil {+ return ModelSettingsCheckLocalChangesResult{}, fmt.Errorf("error hashing model pack: %v", err)+ }- id := selectableModelIds[idx]+ modelPackSchemaRoles := clientModelPackSchemaRoles.ToModelPackSchemaRoles()- return id+ return ModelSettingsCheckLocalChangesResult{+ HasLocalChanges: currentHash != string(lastSavedHash),+ LocalModelPackSchemaRoles: &modelPackSchemaRoles,+ }, nil+}++func WriteModelSettingsFile(path string, originalSettings *shared.PlanSettings) error {+ err := os.MkdirAll(filepath.Dir(path), 0755)+ if err != nil {+ return fmt.Errorf("error creating directory: %v", err)}++ clientModelPackRoles := originalSettings.GetModelPack().ToModelPackSchema().ToClientModelPackSchemaRoles()++ bytes, err := json.MarshalIndent(clientModelPackRoles, "", " ")+ if err != nil {+ return fmt.Errorf("error marshalling model pack: %v", err)+ }++ err = os.WriteFile(path, bytes, 0644)+ if err != nil {+ return fmt.Errorf("error writing JSON file: %v", err)+ }++ return nil}-func MaybePromptAndOpen(path string) bool {- editors := detectEditors()- if len(editors) == 0 {- // just exit if there are no editors available- return false+func SaveModelPackRolesHash(basePath string, serverModelPack *shared.ModelPackSchemaRoles) error {+ hashPath := basePath + ".hash"++ hash, err := serverModelPack.Hash()+ if err != nil {+ return fmt.Errorf("error hashing model pack: %v", err)+ }++ err = os.WriteFile(hashPath, []byte(hash), 0644)+ if err != nil {+ return fmt.Errorf("error writing hash file: %v", err)}- opts := []string{}- for _, c := range editors {- opts = append(opts, "Open with "+c.name)++ return nil+}++func ApplyModelSettings(path string, originalSettings *shared.PlanSettings) (*shared.PlanSettings, error) {+ jsonData, err := os.ReadFile(path)+ if err != nil {+ return nil, fmt.Errorf("error reading JSON file: %v", err)}- const openManually = "Open manually"- opts = append(opts, openManually)+ settings, err := originalSettings.DeepCopy()+ if err != nil {+ return nil, fmt.Errorf("error copying settings: %v", err)+ }- choice, err := term.SelectFromList("Open the file now?", opts)+ clientModelPackRoles, err := schema.ValidateModelPackInlineJSON(jsonData)if err != nil {- term.OutputErrorAndExit("Error selecting editor: %v", err)+ term.StopSpinner()+ color.New(color.Bold, term.ColorHiRed).Println("π¨ Error validating JSON file")+ fmt.Println(err.Error())+ os.Exit(1)}+ modelPackRoles := clientModelPackRoles.ToModelPackSchemaRoles()- if choice == openManually {- return false+ modelPackSchema := shared.ModelPackSchema{+ Name: "custom",+ Description: "Model pack with custom settings",+ ModelPackSchemaRoles: modelPackRoles,}+ modelPack := modelPackSchema.ToModelPack()+ settings.SetCustomModelPack(&modelPack)- var idx int- for i, c := range opts {- if c == choice {- idx = i- break- }+ err = SaveModelPackRolesHash(path, &modelPackRoles)+ if err != nil {+ return nil, fmt.Errorf("error saving model settings hash: %v", err)}- if idx < len(editors) {- sel := editors[idx]- err = exec.Command(sel.cmd, append(sel.args, path)...).Start()- if err != nil {- term.OutputErrorAndExit("Error opening template: %v", err)+ return settings, nil+}++func SaveLatestPlanModelSettingsIfNeeded() (bool, error) {+ path := GetPlanModelSettingsPath(CurrentPlanId)+ jsonData, err := os.ReadFile(path)+ if err != nil {+ if os.IsNotExist(err) {+ return false, nil}- return true+ return false, fmt.Errorf("error reading JSON file: %v", err)+ }++ var clientModelPackSchemaRoles *shared.ClientModelPackSchemaRoles+ err = json.Unmarshal(jsonData, &clientModelPackSchemaRoles)+ if err != nil {+ return false, fmt.Errorf("error unmarshalling JSON file: %v", err)+ }++ modelPackSchemaRoles := clientModelPackSchemaRoles.ToModelPackSchemaRoles()++ localHash, err := modelPackSchemaRoles.Hash()+ if err != nil {+ return false, fmt.Errorf("error hashing model pack: %v", err)}- return false+ settings, apiErr := api.Client.GetSettings(CurrentPlanId, CurrentBranch)+ if apiErr != nil {+ return false, fmt.Errorf("error getting settings: %v", apiErr)+ }++ serverHash, err := settings.GetModelPack().ToModelPackSchema().ModelPackSchemaRoles.Hash()+ if err != nil {+ return false, fmt.Errorf("error hashing model pack: %v", err)+ }++ if localHash == serverHash {+ return false, nil+ }++ err = WriteModelSettingsFile(path, settings)+ if err != nil {+ return false, fmt.Errorf("error writing model settings file: %v", err)+ }++ return true, nil+}++// save settings in file to server+func SyncPlanModelSettings() error {+ settings, err := api.Client.GetSettings(CurrentPlanId, CurrentBranch)+ if err != nil {+ return fmt.Errorf("error getting settings: %v", err)+ }++ updatedSettings, apiErr := ApplyModelSettings(GetPlanModelSettingsPath(CurrentPlanId), settings)+ if apiErr != nil {+ return fmt.Errorf("error applying model settings: %v", err)+ }++ res, updateErr := api.Client.UpdateSettings(CurrentPlanId, CurrentBranch, shared.UpdateSettingsRequest{+ ModelPackName: updatedSettings.ModelPackName,+ ModelPack: updatedSettings.ModelPack,+ })++ if updateErr != nil {+ return fmt.Errorf("error updating settings: %v", err)+ }++ if res == nil {+ return nil+ }++ fmt.Println(res.Msg)++ return nil+}++func SyncDefaultModelSettings() error {+ settings, err := api.Client.GetOrgDefaultSettings()+ if err != nil {+ return fmt.Errorf("error getting settings: %v", err)+ }++ updatedSettings, apiErr := ApplyModelSettings(DefaultModelSettingsPath, settings)+ if apiErr != nil {+ return fmt.Errorf("error applying model settings: %v", err)+ }++ res, updateErr := api.Client.UpdateOrgDefaultSettings(shared.UpdateSettingsRequest{+ ModelPackName: updatedSettings.ModelPackName,+ ModelPack: updatedSettings.ModelPack,+ })++ if updateErr != nil {+ return fmt.Errorf("error updating settings: %v", err)+ }++ if res == nil {+ return nil+ }++ fmt.Println(res.Msg)++ return nil}diff --git a/app/cli/lib/models_sync.go b/app/cli/lib/models_sync.gonew file mode 100644index 00000000..491a099e--- /dev/null+++ b/app/cli/lib/models_sync.go@@ -0,0 +1,83 @@+package lib++import (+ "fmt"+ "plandex-cli/term"++ "github.com/fatih/color"+)++func PromptSyncModelsIfNeeded() error {+ var changes []string+ var onApprove []func() error++ customModelsRes, err := CustomModelsCheckLocalChanges(CustomModelsDefaultPath)+ if err != nil {+ return fmt.Errorf("error checking custom models: %v", err)+ }++ if customModelsRes.HasLocalChanges {+ changes = append(+ changes,+ fmt.Sprintf("%s β %s", color.New(term.ColorHiCyan, color.Bold).Sprint("Custom models"), CustomModelsDefaultPath))++ onApprove = append(onApprove, SyncCustomModels)+ }++ defaultModelSettingsRes, err := ModelSettingsCheckLocalChanges(DefaultModelSettingsPath)+ if err != nil {+ return fmt.Errorf("error checking default model settings: %v", err)+ }++ if defaultModelSettingsRes.HasLocalChanges {+ changes = append(+ changes,+ fmt.Sprintf("%s β %s", color.New(term.ColorHiCyan, color.Bold).Sprint("Default model settings"), DefaultModelSettingsPath))++ onApprove = append(onApprove, SyncDefaultModelSettings)+ }++ planModelSettingsRes, err := ModelSettingsCheckLocalChanges(GetPlanModelSettingsPath(CurrentPlanId))+ if err != nil {+ return fmt.Errorf("error checking plan model settings: %v", err)+ }++ if planModelSettingsRes.HasLocalChanges {+ changes = append(+ changes,+ fmt.Sprintf("%s β %s", color.New(term.ColorHiCyan, color.Bold).Sprint("Plan model settings"), GetPlanModelSettingsPath(CurrentPlanId)))++ onApprove = append(onApprove, SyncPlanModelSettings)+ }++ if len(changes) == 0 {+ return nil+ }++ term.StopSpinner()+ color.New(color.Bold, term.ColorHiYellow).Println("β οΈ Model settings have local changes")++ fmt.Println()+ for _, change := range changes {+ fmt.Println(change)+ }+ fmt.Println()++ shouldSave, err := term.ConfirmYesNo("Save changes now?")+ if err != nil {+ return fmt.Errorf("error confirming: %v", err)+ }++ if !shouldSave {+ return nil+ }++ for _, fn := range onApprove {+ err := fn()+ if err != nil {+ return fmt.Errorf("error syncing models: %v", err)+ }+ }++ return nil+}diff --git a/app/cli/main.go b/app/cli/main.goindex 34cc9d33..692638c6 100644--- a/app/cli/main.go+++ b/app/cli/main.go@@ -30,6 +30,8 @@ func init() {term.SetOpenUnauthenticatedCloudURLFn(ui.OpenUnauthenticatedCloudURL)term.SetConvertTrialFn(auth.ConvertTrial)+ plan_exec.SetPromptSyncModelsIfNeeded(lib.PromptSyncModelsIfNeeded)+lib.SetBuildPlanInlineFn(func(autoConfirm bool, maybeContexts []*shared.Context) (bool, error) {var apiKeys map[string]stringif !auth.Current.IntegratedModelsMode {diff --git a/app/cli/plan_exec/build.go b/app/cli/plan_exec/build.goindex a6fccf5b..d94e928f 100644--- a/app/cli/plan_exec/build.go+++ b/app/cli/plan_exec/build.go@@ -18,6 +18,13 @@ func Build(params ExecParams, flags types.BuildFlags) (bool, error) {term.StartSpinner("")+ err := PromptSyncModelsIfNeeded()+ if err != nil {+ term.OutputErrorAndExit("Error syncing models: %v", err)+ }++ term.StartSpinner("")+contexts, apiErr := api.Client.ListContext(params.CurrentPlanId, params.CurrentBranch)if apiErr != nil {diff --git a/app/cli/plan_exec/params.go b/app/cli/plan_exec/params.goindex d0dfaba3..d7255457 100644--- a/app/cli/plan_exec/params.go+++ b/app/cli/plan_exec/params.go@@ -11,3 +11,9 @@ type ExecParams struct {AuthVars map[string]stringCheckOutdatedContext func(maybeContexts []*shared.Context, projectPaths *types.ProjectPaths) (bool, bool, error)}++var PromptSyncModelsIfNeeded func() error++func SetPromptSyncModelsIfNeeded(fn func() error) {+ PromptSyncModelsIfNeeded = fn+}diff --git a/app/cli/plan_exec/tell.go b/app/cli/plan_exec/tell.goindex f237507f..8e3ca9a1 100644--- a/app/cli/plan_exec/tell.go+++ b/app/cli/plan_exec/tell.go@@ -61,6 +61,15 @@ func TellPlan(}term.StartSpinner("")++ err := PromptSyncModelsIfNeeded()+ if err != nil {+ outputPromptIfTell()+ term.OutputErrorAndExit("Error syncing models: %v", err)+ }++ term.StartSpinner("")+contexts, apiErr := api.Client.ListContext(params.CurrentPlanId, params.CurrentBranch)if apiErr != nil {