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
wip: json custom models import
Dane Schneider16ecba5d9d86
diff --git a/app/cli/api/methods.go b/app/cli/api/methods.goindex 3a0ac39d..6719abe8 100644--- a/app/cli/api/methods.go+++ b/app/cli/api/methods.go@@ -2054,9 +2054,9 @@ func (a *Api) UpdateDefaultPlanConfig(req shared.UpdateDefaultPlanConfigRequest)return nil}-func (a *Api) CreateCustomModel(model *shared.CustomModel) *shared.ApiError {+func (a *Api) CreateCustomModels(input *shared.ModelsInput) *shared.ApiError {serverUrl := fmt.Sprintf("%s/custom_models", GetApiHost())- body, err := json.Marshal(model)+ body, err := json.Marshal(input)if err != nil {return &shared.ApiError{Msg: "Failed to marshal model"}}@@ -2073,7 +2073,7 @@ func (a *Api) CreateCustomModel(model *shared.CustomModel) *shared.ApiError {apiErr := HandleApiError(resp, errorBody)authRefreshed, apiErr := refreshAuthIfNeeded(apiErr)if authRefreshed {- return a.CreateCustomModel(model)+ return a.CreateCustomModels(input)}return apiErr}@@ -2136,96 +2136,6 @@ func (a *Api) DeleteCustomModel(modelId string) *shared.ApiError {return nil}-func (a *Api) UpdateCustomModel(model *shared.CustomModel) *shared.ApiError {- serverUrl := fmt.Sprintf("%s/custom_models/%s", GetApiHost(), model.Id)- body, err := json.Marshal(model)- if err != nil {- return &shared.ApiError{Msg: "Failed to marshal model"}- }-- req, err := http.NewRequest(http.MethodPut, serverUrl, bytes.NewBuffer(body))- if err != nil {- return &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error creating request: %v", err)}- }- req.Header.Set("Content-Type", "application/json")-- resp, err := authenticatedFastClient.Do(req)- if err != nil {- return &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error sending request: %v", err)}- }- defer resp.Body.Close()-- if resp.StatusCode >= 400 {- errorBody, _ := io.ReadAll(resp.Body)- apiErr := HandleApiError(resp, errorBody)- authRefreshed, apiErr := refreshAuthIfNeeded(apiErr)- if authRefreshed {- return a.UpdateCustomModel(model)- }- return apiErr- }-- return nil-}--func (a *Api) CreateCustomProvider(provider *shared.CustomProvider) *shared.ApiError {- serverUrl := fmt.Sprintf("%s/custom_providers", GetApiHost())- body, err := json.Marshal(provider)- if err != nil {- return &shared.ApiError{Msg: "Failed to marshal provider"}- }-- resp, err := authenticatedFastClient.Post(serverUrl, "application/json", bytes.NewBuffer(body))- if err != nil {- return &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error sending request: %v", err)}- }- defer resp.Body.Close()-- if resp.StatusCode >= 400 {- errorBody, _ := io.ReadAll(resp.Body)- apiErr := HandleApiError(resp, errorBody)- authRefreshed, apiErr := refreshAuthIfNeeded(apiErr)- if authRefreshed {- return a.CreateCustomProvider(provider)- }- return apiErr- }-- return nil-}--func (a *Api) UpdateCustomProvider(provider *shared.CustomProvider) *shared.ApiError {- serverUrl := fmt.Sprintf("%s/custom_providers/%s", GetApiHost(), provider.Id)- body, err := json.Marshal(provider)- if err != nil {- return &shared.ApiError{Msg: "Failed to marshal provider"}- }-- req, err := http.NewRequest(http.MethodPut, serverUrl, bytes.NewBuffer(body))- if err != nil {- return &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error creating request: %v", err)}- }- req.Header.Set("Content-Type", "application/json")-- resp, err := authenticatedFastClient.Do(req)- if err != nil {- return &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error sending request: %v", err)}- }- defer resp.Body.Close()-- if resp.StatusCode >= 400 {- errorBody, _ := io.ReadAll(resp.Body)- apiErr := HandleApiError(resp, errorBody)- authRefreshed, apiErr := refreshAuthIfNeeded(apiErr)- if authRefreshed {- return a.UpdateCustomProvider(provider)- }- return apiErr- }-- return nil-}-func (a *Api) ListCustomProviders() ([]*shared.CustomProvider, *shared.ApiError) {serverUrl := fmt.Sprintf("%s/custom_providers", GetApiHost())resp, err := authenticatedFastClient.Get(serverUrl)@@ -2279,34 +2189,6 @@ func (a *Api) DeleteCustomProvider(providerId string) *shared.ApiError {return nil}-func (a *Api) CreateModelPack(set *shared.ModelPack) *shared.ApiError {- serverUrl := fmt.Sprintf("%s/model_sets", GetApiHost())- body, err := json.Marshal(set)- if err != nil {- return &shared.ApiError{Msg: "Failed to marshal model pack"}- }-- resp, err := authenticatedFastClient.Post(serverUrl, "application/json", bytes.NewBuffer(body))- if err != nil {- return &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error sending request: %v", err)}- }- defer resp.Body.Close()-- if resp.StatusCode >= 400 {- errorBody, _ := io.ReadAll(resp.Body)-- apiErr := HandleApiError(resp, errorBody)- authRefreshed, apiErr := refreshAuthIfNeeded(apiErr)- if authRefreshed {- return a.CreateModelPack(set)- }- return apiErr- }-- return nil--}-func (a *Api) ListModelPacks() ([]*shared.ModelPack, *shared.ApiError) {serverUrl := fmt.Sprintf("%s/model_sets", GetApiHost())@@ -2365,39 +2247,6 @@ func (a *Api) DeleteModelPack(setId string) *shared.ApiError {return nil}-func (a *Api) UpdateModelPack(set *shared.ModelPack) *shared.ApiError {- serverUrl := fmt.Sprintf("%s/model_sets/%s", GetApiHost(), set.Id)- body, err := json.Marshal(set)- if err != nil {- return &shared.ApiError{Msg: "Failed to marshal model pack"}- }-- req, err := http.NewRequest(http.MethodPut, serverUrl, bytes.NewBuffer(body))- if err != nil {- return &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error creating request: %v", err)}- }-- req.Header.Set("Content-Type", "application/json")-- resp, err := authenticatedFastClient.Do(req)- if err != nil {- return &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error sending request: %v", err)}- }- defer resp.Body.Close()-- if resp.StatusCode >= 400 {- errorBody, _ := io.ReadAll(resp.Body)- apiErr := HandleApiError(resp, errorBody)- authRefreshed, apiErr := refreshAuthIfNeeded(apiErr)- if authRefreshed {- return a.UpdateModelPack(set)- }- return apiErr- }-- return nil-}-func (a *Api) GetCreditsTransactions(pageSize, pageNum int, req shared.CreditsLogRequest) (*shared.CreditsLogResponse, *shared.ApiError) {serverUrl := fmt.Sprintf("%s/billing/credits_transactions?size=%d&page=%d", GetApiHost(), pageSize, pageNum)diff --git a/app/cli/cmd/model_packs.go b/app/cli/cmd/model_packs.goindex cbb44b23..324a5aef 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: createModelPack,+ Run: customModelsNotImplemented,}var deleteModelPackCmd = &cobra.Command{@@ -38,10 +38,9 @@ var deleteModelPackCmd = &cobra.Command{}var updateModelPackCmd = &cobra.Command{- Use: "update [name]",+ Use: "update",Short: "Update a model pack by name",- Args: cobra.MaximumNArgs(1),- Run: updateModelPack,+ Run: customModelsNotImplemented,}var showModelPackCmd = &cobra.Command{@@ -189,194 +188,6 @@ func listModelPacks(cmd *cobra.Command, args []string) {}-func createModelPack(cmd *cobra.Command, args []string) {- auth.MustResolveAuthWithOrg()-- mp := &shared.ModelPack{}-- name, err := term.GetRequiredUserStringInput("Enter model pack name:")- if err != nil {- term.OutputErrorAndExit("Error reading model pack name: %v", err)- return- }- mp.Name = name-- description, err := term.GetUserStringInput("Enter description:")- if err != nil {- term.OutputErrorAndExit("Error reading description: %v", err)- return- }- mp.Description = description-- // term.StartSpinner("")- // customModels, apiErr := api.Client.ListCustomModels()- // term.StopSpinner()-- // if apiErr != nil {- // term.OutputErrorAndExit("Error fetching models: %v", apiErr)- // }-- // Selecting models for each role- // mp.Planner = getPlannerRoleConfig(customModels)-- // contextLoader := getModelRoleConfig(customModels, shared.ModelRoleArchitect)- // mp.Architect = &contextLoader-- // coder := getModelRoleConfig(customModels, shared.ModelRoleCoder)- // mp.Coder = &coder-- // mp.Builder = getModelRoleConfig(customModels, shared.ModelRoleBuilder)-- // wholeFileBuilder := getModelRoleConfig(customModels, shared.ModelRoleWholeFileBuilder)- // mp.WholeFileBuilder = &wholeFileBuilder-- // mp.Namer = getModelRoleConfig(customModels, shared.ModelRoleName)- // mp.CommitMsg = getModelRoleConfig(customModels, shared.ModelRoleCommitMsg)-- // mp.PlanSummary = getModelRoleConfig(customModels, shared.ModelRolePlanSummary)- // mp.ExecStatus = getModelRoleConfig(customModels, shared.ModelRoleExecStatus)-- term.StartSpinner("")- apiErr := api.Client.CreateModelPack(mp)- term.StopSpinner()-- if apiErr != nil {- term.OutputErrorAndExit("Error creating model pack: %v", apiErr.Msg)- return- }-- fmt.Println("β Created model pack", color.New(color.Bold, term.ColorHiCyan).Sprint(mp.Name))-- fmt.Println()-- term.PrintCmds("", "model-packs", "model-packs --custom", "model-packs delete")-}--func updateModelPack(cmd *cobra.Command, args []string) {- auth.MustResolveAuthWithOrg()-- term.StartSpinner("")- modelPacks, apiErr := api.Client.ListModelPacks()-- if apiErr != nil {- term.StopSpinner()- term.OutputErrorAndExit("Error fetching models: %v", apiErr)- }-- if len(modelPacks) == 0 {- term.StopSpinner()- fmt.Println("π€·ββοΈ No model packs")- return- }-- // customModels, apiErr := api.Client.ListCustomModels()- // term.StopSpinner()- // if apiErr != nil {- // term.OutputErrorAndExit("Error fetching models: %v", apiErr)- // }-- var toUpdate *shared.ModelPack-- var name string- if len(args) > 0 {- name = args[0]- }-- if name == "" {- opts := make([]string, len(modelPacks))- for i, mp := range modelPacks {- opts[i] = mp.Name- }-- selected, err := term.SelectFromList("Select a custom model pack:", opts)- if err != nil {- term.OutputErrorAndExit("Error selecting model pack: %v", err)- }-- for _, mp := range modelPacks {- if mp.Name == selected {- toUpdate = mp- break- }- }- }-- if toUpdate == nil {- term.OutputErrorAndExit("Model pack not found")- return- }-- // var role shared.ModelRole-- roleOpts := make([]string, len(shared.AllModelRoles))- for i, role := range shared.AllModelRoles {- roleOpts[i] = string(role)- }-- renderModelPack(toUpdate, allProperties)-- // for {- // selected, err := term.SelectFromList("Select a role to update:", roleOpts)- // if err != nil {- // term.OutputErrorAndExit("Error selecting role: %v", err)- // }-- // role = shared.ModelRole(selected)-- // switch role {- // case shared.ModelRolePlanner:- // toUpdate.Planner = getPlannerRoleConfig(customModels)- // case shared.ModelRoleArchitect:- // contextLoader := getModelRoleConfig(customModels, shared.ModelRoleArchitect)- // toUpdate.Architect = &contextLoader- // case shared.ModelRoleCoder:- // coder := getModelRoleConfig(customModels, shared.ModelRoleCoder)- // toUpdate.Coder = &coder- // case shared.ModelRoleBuilder:- // builder := getModelRoleConfig(customModels, shared.ModelRoleBuilder)- // toUpdate.Builder = builder- // case shared.ModelRoleWholeFileBuilder:- // wholeFileBuilder := getModelRoleConfig(customModels, shared.ModelRoleWholeFileBuilder)- // toUpdate.WholeFileBuilder = &wholeFileBuilder- // case shared.ModelRolePlanSummary:- // toUpdate.PlanSummary = getModelRoleConfig(customModels, role)- // case shared.ModelRoleExecStatus:- // toUpdate.ExecStatus = getModelRoleConfig(customModels, role)- // case shared.ModelRoleCommitMsg:- // toUpdate.CommitMsg = getModelRoleConfig(customModels, role)- // case shared.ModelRoleName:- // toUpdate.Namer = getModelRoleConfig(customModels, role)- // }-- // updateOpt := "Update another role"- // saveOpt := "Save model pack and exit"- // opts := []string{updateOpt, saveOpt}-- // selected, err = term.SelectFromList("Finished editing?", opts)- // if err != nil {- // term.OutputErrorAndExit("Error selecting option: %v", err)- // }-- // if selected == saveOpt {- // break- // }- // }-- term.StartSpinner("")- apiErr = api.Client.UpdateModelPack(toUpdate)- term.StopSpinner()-- if apiErr != nil {- term.OutputErrorAndExit("Error updating model pack: %v", apiErr.Msg)- }-- fmt.Println("β Model pack updated")-- fmt.Println()-- term.PrintCmds("", "model-packs show", "set-model", "set-model default")-}-func showModelPack(cmd *cobra.Command, args []string) {auth.MustResolveAuthWithOrg()diff --git a/app/cli/cmd/model_providers.go b/app/cli/cmd/model_providers.goindex 6bc20aaf..c89b4c5e 100644--- a/app/cli/cmd/model_providers.go+++ b/app/cli/cmd/model_providers.go@@ -25,13 +25,6 @@ var providersCmd = &cobra.Command{Run: listProviders,}-var addProviderCmd = &cobra.Command{- Use: "add",- Aliases: []string{"create"},- Short: "Add a custom model provider",- Run: addProvider,-}-var showProviderCmd = &cobra.Command{Use: "show [id|name]",Short: "Show a custom model provider",@@ -39,19 +32,25 @@ var showProviderCmd = &cobra.Command{Run: showProvider,}+var addProviderCmd = &cobra.Command{+ Use: "add",+ Aliases: []string{"create"},+ Short: "Add a custom model provider",+ Run: customModelsNotImplemented,+}+var updateProviderCmd = &cobra.Command{- Use: "update [id|name]",+ Use: "update",Aliases: []string{"edit"},Short: "Update a custom model provider",- Args: cobra.MaximumNArgs(1),- Run: updateProvider,+ Run: customModelsNotImplemented,}func init() {RootCmd.AddCommand(providersCmd)providersCmd.Flags().BoolVarP(&customProvidersOnly, "custom", "c", false, "List custom providers only")- providersCmd.AddCommand(addProviderCmd)providersCmd.AddCommand(showProviderCmd)+ providersCmd.AddCommand(addProviderCmd)providersCmd.AddCommand(updateProviderCmd)}@@ -144,61 +143,7 @@ func listProviders(cmd *cobra.Command, args []string) {fmt.Println()}- term.PrintCmds("", "providers show", "providers update", "providers add")-}--func addProvider(cmd *cobra.Command, args []string) {- auth.MustResolveAuthWithOrg()-- if auth.Current.IsCloud {- term.OutputErrorAndExit("Custom providers are not supported on Plandex Cloud")- return- }-- name, err := term.GetRequiredUserStringInput("Provider name:")- if err != nil {- term.OutputErrorAndExit("Error reading name: %v", err)- return- }-- baseUrl, err := term.GetRequiredUserStringInput("Base URL:")- if err != nil {- term.OutputErrorAndExit("Error reading base URL: %v", err)- return- }- baseUrl = strings.TrimSuffix(baseUrl, "/")-- skipAuth, err := term.ConfirmYesNo("Skip auth?")- if err != nil {- term.OutputErrorAndExit("Error reading skip auth: %v", err)- return- }-- var apiKeyEnvVar string- if !skipAuth {- apiKeyEnvVar, err = term.GetRequiredUserStringInput("API key env var:")- if err != nil {- term.OutputErrorAndExit("Error reading env var: %v", err)- return- }- }-- provider := &shared.CustomProvider{- Name: name,- BaseUrl: baseUrl,- SkipAuth: skipAuth,- ApiKeyEnvVar: apiKeyEnvVar,- }-- term.StartSpinner("")- apiErr := api.Client.CreateCustomProvider(provider)- term.StopSpinner()- if apiErr != nil {- term.OutputErrorAndExit("Error creating provider: %v", apiErr.Msg)- return- }-- fmt.Println("β Added custom provider", color.New(color.Bold, term.ColorHiCyan).Sprint(name))+ term.PrintCmds("", "providers show", "providers update", "models import")}func showProvider(cmd *cobra.Command, args []string) {@@ -270,107 +215,3 @@ func showProvider(cmd *cobra.Command, args []string) {fmt.Println()term.PrintCmds("", "providers update", "providers list")}--func updateProvider(cmd *cobra.Command, args []string) {- auth.MustResolveAuthWithOrg()-- term.StartSpinner("")- providers, apiErr := api.Client.ListCustomProviders()- term.StopSpinner()- if apiErr != nil {- term.OutputErrorAndExit("Error fetching providers: %v", apiErr.Msg)- return- }-- if len(providers) == 0 {- fmt.Println("π€·ββοΈ No custom providers")- fmt.Println()- term.PrintCmds("", "providers add")- return- }-- var selected *shared.CustomProvider- if len(args) == 1 {- input := args[0]- idx, err := strconv.Atoi(input)- if err == nil && idx > 0 && idx <= len(providers) {- selected = providers[idx-1]- } else {- for _, p := range providers {- if p.Name == input || p.Id == input {- selected = p- break- }- }- }- }-- if selected == nil {- opts := make([]string, len(providers))- for i, p := range providers {- opts[i] = fmt.Sprintf("%s (%s)", p.Name, p.BaseUrl)- }- choice, err := term.SelectFromList("Select provider:", opts)- if err != nil {- term.OutputErrorAndExit("Error selecting provider: %v", err)- return- }- for i, o := range opts {- if o == choice {- selected = providers[i]- break- }- }- }-- newName, err := term.GetRequiredUserStringInputWithDefault("Provider name:", selected.Name)- if err != nil {- term.OutputErrorAndExit("Error reading name: %v", err)- return- }-- newBaseUrl, err := term.GetRequiredUserStringInputWithDefault("Base URL:", selected.BaseUrl)- if err != nil {- term.OutputErrorAndExit("Error reading base URL: %v", err)- return- }- newBaseUrl = strings.TrimSuffix(newBaseUrl, "/")-- newSkipAuth := selected.SkipAuth- changeSkip, err := term.ConfirmYesNo("Change skip auth? (current: " + fmt.Sprintf("%v", selected.SkipAuth) + ")")- if err == nil && changeSkip {- newSkipAuth, err = term.ConfirmYesNo("Skip auth?")- if err != nil {- term.OutputErrorAndExit("Error reading skip auth: %v", err)- return- }- }-- var newApiKeyEnvVar string- if !newSkipAuth {- newApiKeyEnvVar, err = term.GetRequiredUserStringInputWithDefault("API key env var:", selected.ApiKeyEnvVar)- if err != nil {- term.OutputErrorAndExit("Error reading env var: %v", err)- return- }- }-- provider := &shared.CustomProvider{- Id: selected.Id,- Name: newName,- BaseUrl: newBaseUrl,- SkipAuth: newSkipAuth,- ApiKeyEnvVar: newApiKeyEnvVar,- ExtraAuthVars: selected.ExtraAuthVars,- }-- term.StartSpinner("")- apiErr = api.Client.UpdateCustomProvider(provider)- term.StopSpinner()- if apiErr != nil {- term.OutputErrorAndExit("Error updating provider: %v", apiErr.Msg)- return- }-- fmt.Println("β Updated custom provider", color.New(color.Bold, term.ColorHiCyan).Sprint(newName))-}diff --git a/app/cli/cmd/models.go b/app/cli/cmd/models.goindex d3c28bce..2b84291b 100644--- a/app/cli/cmd/models.go+++ b/app/cli/cmd/models.go@@ -4,10 +4,15 @@ import ("encoding/json""fmt""os"+ "os/exec"+ "path/filepath"+ "sort"+ "strings""plandex-cli/api""plandex-cli/auth""plandex-cli/lib"+ "plandex-cli/schema""plandex-cli/term""strconv"@@ -21,7 +26,7 @@ import (var customModelsOnly boolvar allProperties bool-var jsonFile string+var genTemplatePath stringfunc init() {RootCmd.AddCommand(modelsCmd)@@ -29,11 +34,13 @@ func init() {modelsCmd.Flags().BoolVarP(&allProperties, "all", "a", false, "Show all properties")modelsCmd.AddCommand(listAvailableModelsCmd)- modelsCmd.AddCommand(createCustomModelCmd)+ modelsCmd.AddCommand(addCustomModelCmd)+ modelsCmd.AddCommand(updateCustomModelCmd)+ modelsCmd.AddCommand(importCustomModelCmd)modelsCmd.AddCommand(deleteCustomModelCmd)modelsCmd.AddCommand(defaultModelsCmd)- createCustomModelCmd.Flags().StringVar(&jsonFile, "json", "", "Path to a JSON file containing model configuration")+ importCustomModelCmd.Flags().StringVarP(&genTemplatePath, "generate", "g", "", "Generate a template JSON file")listAvailableModelsCmd.Flags().BoolVarP(&customModelsOnly, "custom", "c", false, "List custom models only")}@@ -57,11 +64,25 @@ var listAvailableModelsCmd = &cobra.Command{Run: listAvailableModels,}-var createCustomModelCmd = &cobra.Command{+var importCustomModelCmd = &cobra.Command{+ Use: "import [json-file]",+ Short: "Create or update custom models, providers, and model packs from a JSON file",+ Run: importCustomModels,+ Args: cobra.MaximumNArgs(1),+}++var addCustomModelCmd = &cobra.Command{Use: "add",Aliases: []string{"create"},Short: "Add a custom model",- Run: createCustomModel,+ Run: customModelsNotImplemented,+}++var updateCustomModelCmd = &cobra.Command{+ Use: "update",+ Aliases: []string{"edit"},+ Short: "Update a custom model",+ Run: customModelsNotImplemented,}var deleteCustomModelCmd = &cobra.Command{@@ -72,235 +93,170 @@ var deleteCustomModelCmd = &cobra.Command{Run: deleteCustomModel,}-func createCustomModel(cmd *cobra.Command, args []string) {+func importCustomModels(cmd *cobra.Command, args []string) {auth.MustResolveAuthWithOrg()- var model *shared.CustomModel-- if jsonFile != "" {- // Load model from JSON file- jsonData, err := os.ReadFile(jsonFile)- if err != nil {- term.OutputErrorAndExit("Error reading JSON file: %v", err)- return- }-- // Parse JSON into a map- var jsonMap map[string]interface{}- if err := json.Unmarshal(jsonData, &jsonMap); err != nil {- term.OutputErrorAndExit("Error parsing JSON: %v", err)- return- }-- // Convert to CustomModel- model = &shared.CustomModel{- BaseModelShared: shared.BaseModelShared{- ModelCompatibility: shared.ModelCompatibility{},- },- }-- // Extract required fields- if modelId, ok := jsonMap["modelId"].(string); ok {- model.ModelId = shared.ModelId(modelId)- } else {- term.OutputErrorAndExit("Missing or invalid 'modelId' in JSON")- return- }-- // Extract optional fields- if description, ok := jsonMap["description"].(string); ok {- model.Description = description- }+ var jsonFile string+ genTemplate := genTemplatePath != ""- // Extract numeric fields- if maxTokens, ok := jsonMap["maxTokens"].(float64); ok {- model.MaxTokens = int(maxTokens)- } else {- term.OutputErrorAndExit("Missing or invalid 'maxTokens' in JSON")- return- }-- if maxConvoTokens, ok := jsonMap["defaultMaxConvoTokens"].(float64); ok {- model.DefaultMaxConvoTokens = int(maxConvoTokens)- } else {- term.OutputErrorAndExit("Missing or invalid 'defaultMaxConvoTokens' in JSON")- return- }+ if len(args) == 0 && !genTemplate {+ fmt.Println(color.New(color.Bold, color.FgHiCyan).Sprint("To add custom models, providers, or model packs π") + `+1. Generate a template JSON file+2. Update it in an IDE or editor+3. Load the template and finish import`)+ fmt.Println()- if maxOutputTokens, ok := jsonMap["maxOutputTokens"].(float64); ok {- model.MaxOutputTokens = int(maxOutputTokens)- } else {- term.OutputErrorAndExit("Missing or invalid 'maxOutputTokens' in JSON")- return- }+ fmt.Println("βΉοΈ You can also " + color.New(color.Bold, color.FgHiCyan).Sprint("update") + " existing custom models, providers, or model packs with the same JSON file")+ fmt.Println()- if reservedOutputTokens, ok := jsonMap["reservedOutputTokens"].(float64); ok {- model.ReservedOutputTokens = int(reservedOutputTokens)- } else {- term.OutputErrorAndExit("Missing or invalid 'reservedOutputTokens' in JSON")+ const createTemplate = "Generate template"+ const loadTemplate = "Load template"+ const cancel = "Cancel"+ opts := []string{createTemplate, loadTemplate, cancel}+ selected, err := term.SelectFromList("What do you want to do?", opts)+ if err != nil {+ term.OutputErrorAndExit("Error selecting option: %v", err)return}- // Extract output format- if outputFormat, ok := jsonMap["preferredOutputFormat"].(string); ok {- model.PreferredOutputFormat = shared.ModelOutputFormat(outputFormat)- } else {- term.OutputErrorAndExit("Missing or invalid 'preferredOutputFormat' in JSON")+ if selected == cancel {return}- // Extract image support- if hasImageSupport, ok := jsonMap["hasImageSupport"].(bool); ok {- model.HasImageSupport = hasImageSupport- } else {- // Default to false if not specified- model.HasImageSupport = false+ if selected == createTemplate {+ genTemplate = true+ } else if selected == loadTemplate {+ jsonFile, err = term.GetRequiredUserStringInput("Template path:")+ if err != nil {+ term.OutputErrorAndExit("Error getting template file path: %v", err)+ return+ }}} else {- // Interactive mode- model = &shared.CustomModel{- BaseModelShared: shared.BaseModelShared{- ModelCompatibility: shared.ModelCompatibility{},- },- }+ jsonFile = args[0]+ }- fmt.Println("For model id, use something like 'openai/gpt-4.1' that uniquely identifies the model. This doesn't need to match the model name for any particular provider (this is set when you add providers for the model).")- modelId, err := term.GetRequiredUserStringInput("Model id:")- if err != nil {- term.OutputErrorAndExit("Error reading model id: %v", err)- return+ if genTemplate {+ var path string+ if genTemplatePath != "" {+ path = genTemplatePath+ // Check if file already exists+ if _, err := os.Stat(path); err == nil {+ term.OutputErrorAndExit("Template file already exists: %s", path)+ return+ } else if !os.IsNotExist(err) {+ term.OutputErrorAndExit("Error checking template file: %v", err)+ return+ }+ } else {+ tmpDir := os.TempDir()+ // Generate a unique temporary file if no path is specified+ tmpFile, err := os.CreateTemp(tmpDir, "plandex-models-*.json")+ if err != nil {+ term.OutputErrorAndExit("Error creating template file: %v", err)+ return+ }+ path = tmpFile.Name()+ tmpFile.Close()}- model.ModelId = shared.ModelId(modelId)- fmt.Println("Add a human friendly description if you want to.")- description, err := term.GetUserStringInput("Description (optional):")+ jsonData, err := json.MarshalIndent(getExampleTemplate(), "", " ")if err != nil {- term.OutputErrorAndExit("Error reading description: %v", err)+ term.OutputErrorAndExit("Error marshalling custom model: %v", err)return}- model.Description = description-- fmt.Println("Max Tokens is the total maximum context size of the model.")- maxTokensStr, err := term.GetRequiredUserStringInput("Max Tokens:")- if err != nil {- term.OutputErrorAndExit("Error reading max tokens: %v", err)- return- }- maxTokens, err := strconv.Atoi(maxTokensStr)+ err = os.WriteFile(path, jsonData, 0644)if err != nil {- term.OutputErrorAndExit("Invalid number for max tokens: %v", err)+ term.OutputErrorAndExit("Error writing template file: %v", err)return}- model.MaxTokens = maxTokens- fmt.Println("'Default Max Convo Tokens' is the default maximum size a conversation can reach in the 'planner' role before it is shortened by summarization. For 128k context, ~10000 is recommended. For 200k context, ~15000 is recommended.")+ fmt.Printf("β Created template %s\n", color.New(color.Bold, term.ColorHiGreen).Sprint(path))- var defaultMaxConvoTokens int+ fmt.Println()- if maxTokens >= 180000 {- defaultMaxConvoTokens = 15000- } else if maxTokens >= 100000 {- defaultMaxConvoTokens = 10000- }+ selectedEditor := maybePromptAndOpen(path)- var maxConvoTokensStr string- if defaultMaxConvoTokens == 0 {- maxConvoTokensStr, err = term.GetRequiredUserStringInput("Default Max Convo Tokens:")- } else {- maxConvoTokensStr, err = term.GetRequiredUserStringInputWithDefault("Default Max Convo Tokens:", strconv.Itoa(defaultMaxConvoTokens))+ pf := "\\"+ if !term.IsRepl {+ pf = "plandex "}+ manualImport := `β’ Run ` + color.New(color.Bold, color.BgCyan, color.FgHiWhite).Sprintf(" %smodels import ", pf) + ` again and select ` + color.New(color.Bold, color.FgHiCyan).Sprint("Load template") + `+β’ Run ` + color.New(color.Bold, color.BgCyan, color.FgHiWhite).Sprintf(" %smodels import %s ", pf, path)- if err != nil {- term.OutputErrorAndExit("Error reading max convo tokens: %v", err)- return- }- maxConvoTokens, err := strconv.Atoi(maxConvoTokensStr)- if err != nil {- term.OutputErrorAndExit("Invalid number for max convo tokens: %v", err)- return- }- model.DefaultMaxConvoTokens = maxConvoTokens+ if selectedEditor {+ fmt.Println("π Opened template")+ fmt.Println(`π¨βπ» Edit it, then come back here to finish importing`)- fmt.Println("'Max Output Tokens' is the hard limit on output length for the model. Check with the model provider for the recommended value. 8k is a reasonable default if it's not documented, though some models have no max output limitβin that case 'Max Output Tokens' should be set to the same value as 'Max Tokens'.")+ fmt.Println()- maxOutputTokensStr, err := term.GetRequiredUserStringInputWithDefault("Max Output Tokens:", "8192")- if err != nil {- term.OutputErrorAndExit("Error reading reserved output tokens: %v", err)- return- }- maxOutputTokens, err := strconv.Atoi(maxOutputTokensStr)- if err != nil {- term.OutputErrorAndExit("Invalid number for reserved output tokens: %v", err)- return- }- model.MaxOutputTokens = maxOutputTokens+ confirmed, err := term.ConfirmYesNo("Done editing and ready to import?")+ if err != nil {+ term.OutputErrorAndExit("Error confirming template: %v", err)+ return+ }- fmt.Println("'Reserved Output Tokens' is the default number of tokens reserved for model output. This ensures the model has enough tokens to generate a response. It can be lower than the 'Max Output Tokens' limit and should be set to what a *realistic* output could reach under normal circumstances. If the 'Max Output Tokens' limit is fairly low, just use that. If the 'Max Output Tokens' is very high, or is equal to the 'Max Tokens' input limit, set a lower value so that there's enough room for input. For reasoning models, make sure enough space is included for reasoning tokens.")+ fmt.Println()- var defaultReservedOutputTokens int- if maxOutputTokens <= int(float64(maxTokens)*0.2) {- defaultReservedOutputTokens = maxOutputTokens- }+ if confirmed {+ jsonFile = path+ } else {+ fmt.Println("π€·ββοΈ Didn't import")+ fmt.Println()+ fmt.Println("When you're ready, either:")+ fmt.Println(manualImport)+ return+ }- var reservedOutputTokensStr string- if defaultReservedOutputTokens == 0 {- reservedOutputTokensStr, err = term.GetRequiredUserStringInputWithDefault("Reserved Output Tokens:", "8192")} else {- reservedOutputTokensStr, err = term.GetRequiredUserStringInputWithDefault("Reserved Output Tokens:", strconv.Itoa(defaultReservedOutputTokens))- }- if err != nil {- term.OutputErrorAndExit("Error reading reserved output tokens: %v", err)- return- }-- reservedOutputTokens, err := strconv.Atoi(reservedOutputTokensStr)- if err != nil {- term.OutputErrorAndExit("Invalid number for reserved output tokens: %v", err)+ fmt.Println(`π¨βπ» Edit the template in your IDE or JSON editor of choice, then either:`)+ fmt.Println(manualImport)return}- model.ReservedOutputTokens = reservedOutputTokens-- fmt.Println("'Preferred Output Format' is the format for roles needing structured output. Currently, OpenAI models do best with 'Tool Call JSON' and other models generally do better with 'XML'. Choose 'XML' if you're unsure as it offers the widest compatibility. 'Tool Call JSON' requires tool call support and reliable JSON generation.")-- outputFormatLabels := map[string]string{- string(shared.ModelOutputFormatXml): "XML",- string(shared.ModelOutputFormatToolCallJson): "Tool Call JSON",- }+ }- res, err := term.SelectFromList("Preferred Output Format:", []string{- outputFormatLabels[string(shared.ModelOutputFormatXml)],- outputFormatLabels[string(shared.ModelOutputFormatToolCallJson)],- })- if err != nil {- term.OutputErrorAndExit("Error selecting output format: %v", err)- return- }- for key, label := range outputFormatLabels {- if label == res {- model.PreferredOutputFormat = shared.ModelOutputFormat(key)- break- }- }+ jsonData, err := os.ReadFile(jsonFile)+ if err != nil {+ term.OutputErrorAndExit("Error reading JSON file: %v", err)+ return+ }- model.HasImageSupport, err = term.ConfirmYesNo("Is multi-modal image support enabled?")- if err != nil {- term.OutputErrorAndExit("Error confirming image support: %v", err)- return- }+ modelsInput, err := schema.ValidateModelsInputJSON(jsonData)+ if err != nil {+ color.New(color.Bold, term.ColorHiRed).Println("π¨ Error validating JSON file")+ fmt.Println(err.Error())+ return}term.StartSpinner("")- apiErr := api.Client.CreateCustomModel(model)+ apiErr := api.Client.CreateCustomModels(&modelsInput)term.StopSpinner()if apiErr != nil {- term.OutputErrorAndExit("Error adding model: %v", apiErr.Msg)+ term.OutputErrorAndExit("Error importing models: %v", apiErr.Msg)return}- fmt.Println("β Added custom model", color.New(color.Bold, term.ColorHiCyan).Sprint(string(model.ModelId)))+ for _, provider := range modelsInput.CustomProviders {+ fmt.Println("β Imported custom", color.New(term.ColorHiCyan).Sprint("provider"), "β", color.New(color.Bold, term.ColorHiGreen).Sprint(provider.Name))+ }++ for _, model := range modelsInput.CustomModels {+ fmt.Println("β Imported custom", color.New(term.ColorHiCyan).Sprint("model"), "β", color.New(color.Bold, term.ColorHiGreen).Sprint(string(model.ModelId)))+ }++ for _, modelPack := range modelsInput.CustomModelPacks {+ fmt.Println("β Imported custom", color.New(term.ColorHiCyan).Sprint("model pack"), "β", color.New(color.Bold, term.ColorHiGreen).Sprint(modelPack.Name))+ }++ if genTemplate || looksLikeEphemeralTemplate(jsonFile) {+ err = os.Remove(jsonFile)+ if err != nil {+ term.OutputErrorAndExit("Error cleaning up template: %v", err)+ }+ }}func models(cmd *cobra.Command, args []string) {@@ -653,3 +609,233 @@ func renderModelPack(modelPack *shared.ModelPack, allProperties bool) {fmt.Println()}++func customModelsNotImplemented(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")+ os.Exit(1)+}++type editorCandidate struct {+ name string+ cmd string+ args []string+ isJetBrains bool+}++const maxEditorOpts = 5++func detectEditors() []editorCandidate {+ guess := []editorCandidate{+ // Popular non-JetBrains launchers+ {"VS Code", "code", nil, false},+ {"Cursor", "cursor", nil, false},+ {"Zed", "zed", nil, false},+ {"Neovim", "nvim", nil, false},++ // JetBrains IDE-specific launchers+ {"IntelliJ IDEA", "idea", nil, true},+ {"GoLand", "goland", nil, true},+ {"PyCharm", "pycharm", nil, true},+ {"CLion", "clion", nil, true},+ {"WebStorm", "webstorm", nil, true},+ {"PhpStorm", "phpstorm", nil, true},+ {"DataGrip", "datagrip", nil, true},+ {"RubyMine", "rubymine", nil, true},+ {"Rider", "rider", nil, true},+ {"DataSpell", "dataspell", nil, true},++ // JetBrains universal CLI (2023.2+)+ {"JetBrains (jb)", "jb", []string{"open"}, true},++ {"Vim", "vim", nil, false},+ {"Nano", "nano", nil, false},+ {"Helix", "hx", nil, false},+ {"Micro", "micro", nil, false},+ {"Sublime Text", "subl", nil, false},+ {"TextMate", "mate", nil, false},+ {"Kakoune", "kak", nil, false},+ {"Emacs", "emacs", nil, false},+ {"Kate", "kate", nil, false},+ }+ pref := map[string]bool{}+ for _, env := range []string{"VISUAL", "EDITOR"} {+ if v := os.Getenv(env); v != "" {+ // keep only the binary name, drop path/flags+ cmd := filepath.Base(strings.Fields(v)[0])+ pref[cmd] = true+ }+ }++ _, err := exec.LookPath("jb") // true if universal launcher exists+ jbOnPath := err == nil++ var found []editorCandidate+ for _, c := range guess {+ if _, err := exec.LookPath(c.cmd); err != nil {+ continue // not on PATH+ }++ // If jb is present, drop per-IDE launchers *unless* this exact cmd+ // is marked preferred by VISUAL/EDITOR.+ if jbOnPath && c.isJetBrains && !pref[c.cmd] {+ continue+ }+ found = append(found, c)+ }++ for cmd := range pref {+ if _, err := exec.LookPath(cmd); err == nil {+ already := false+ for _, c := range found {+ if c.cmd == cmd {+ already = true+ break+ }+ }+ if !already {+ found = append(found, editorCandidate{name: cmd, cmd: cmd})+ }+ }+ }+ sort.SliceStable(found, func(i, j int) bool {+ pi, pj := pref[found[i].cmd], pref[found[j].cmd]+ if pi == pj {+ return false // keep original order+ }+ return pi // true β i comes before j+ })+ if len(found) > maxEditorOpts {+ found = found[:maxEditorOpts]+ }++ return found+}++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("Edit the template 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+}++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() shared.ModelsInput {+ exampleProviderName := "togetherai"++ return shared.ModelsInput{+ SchemaUrl: shared.SchemaUrlInputConfig,+ CustomProviders: []shared.CustomProvider{+ {+ Name: exampleProviderName,+ BaseUrl: "https://api.together.xyz/v1",+ ApiKeyEnvVar: "TOGETHER_API_KEY",+ },+ },+ CustomModels: []shared.CustomModel{+ {+ ModelId: shared.ModelId("meta-llama/llama-4-maverick"),+ Publisher: shared.ModelPublisher("meta-llama"),+ Description: "Meta Llama 4 Maverick",++ BaseModelShared: shared.BaseModelShared{+ DefaultMaxConvoTokens: 75000,+ MaxTokens: 1048576,+ MaxOutputTokens: 16000,+ ReservedOutputTokens: 16000,+ ModelCompatibility: shared.FullCompatibility,+ 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",+ },+ },+ },+ },+ CustomModelPacks: []shared.ModelPackSchema{+ {+ Name: "example-model-pack",+ Description: "Example model pack",+ Planner: shared.ModelRoleConfigSchema{+ ModelId: shared.ModelId("deepseek/r1-reasoning-visible"),+ },+ Architect: &shared.ModelRoleConfigSchema{+ ModelId: shared.ModelId("deepseek/r1-reasoning-visible"),+ },+ Coder: &shared.ModelRoleConfigSchema{+ ModelId: shared.ModelId("deepseek/v3-0324"),+ },+ PlanSummary: shared.ModelRoleConfigSchema{+ ModelId: shared.ModelId("meta-llama/llama-4-maverick"),+ },+ Builder: shared.ModelRoleConfigSchema{+ ModelId: shared.ModelId("deepseek/r1-reasoning-hidden"),+ },+ WholeFileBuilder: &shared.ModelRoleConfigSchema{+ ModelId: shared.ModelId("deepseek/r1-reasoning-hidden"),+ },+ ExecStatus: shared.ModelRoleConfigSchema{+ ModelId: shared.ModelId("deepseek/r1-reasoning-hidden"),+ },+ Namer: shared.ModelRoleConfigSchema{+ ModelId: shared.ModelId("meta-llama/llama-4-maverick"),+ },+ CommitMsg: shared.ModelRoleConfigSchema{+ ModelId: shared.ModelId("meta-llama/llama-4-maverick"),+ },+ },+ },+ }+}diff --git a/app/cli/cmd/schema_validation.go b/app/cli/cmd/schema_validation.godeleted file mode 100644index 4a9e802b..00000000--- a/app/cli/cmd/schema_validation.go+++ /dev/null@@ -1,243 +0,0 @@-package cmd--import (- "embed"- "encoding/json"- "fmt"- "path/filepath"- "strings"-- shared "plandex-shared"-- "github.com/xeipuuv/gojsonschema"-)--//go:embed ../json-schemas/*.schema.json ../json-schemas/definitions/*.schema.json-var schemaFS embed.FS--// embeddedSchemaLoader implements a custom loader for embedded JSON schemas-// that can resolve references between schemas-type embeddedSchemaLoader struct {- source string- fs embed.FS-}--// newEmbeddedSchemaLoader creates a new loader for embedded schemas-func newEmbeddedSchemaLoader(source string) embeddedSchemaLoader {- return embeddedSchemaLoader{- source: source,- fs: schemaFS,- }-}--// JsonSource returns the source of the schema-func (l *embeddedSchemaLoader) JsonSource() interface{} {- return l.source-}--// LoadJSON loads the schema from the embedded filesystem-func (l *embeddedSchemaLoader) LoadJSON() (interface{}, error) {- // If the source is a reference to another schema- if strings.HasPrefix(l.source, "definitions/") || strings.HasSuffix(l.source, ".schema.json") {- // Construct the path to the schema in the embedded filesystem- schemaPath := l.source- if !strings.HasPrefix(schemaPath, "../json-schemas/") {- schemaPath = filepath.Join("../json-schemas", schemaPath)- }-- // Read the schema from the embedded filesystem- schemaData, err := l.fs.ReadFile(schemaPath)- if err != nil {- return nil, fmt.Errorf("error reading embedded schema %s: %v", schemaPath, err)- }-- // Parse the schema- var schemaMap map[string]interface{}- if err := json.Unmarshal(schemaData, &schemaMap); err != nil {- return nil, fmt.Errorf("error parsing embedded schema %s: %v", schemaPath, err)- }-- return schemaMap, nil- }-- // If the source is a JSON string- var schemaMap map[string]interface{}- if err := json.Unmarshal([]byte(l.source), &schemaMap); err != nil {- return nil, fmt.Errorf("error parsing schema JSON: %v", err)- }-- return schemaMap, nil-}--// JsonReference returns a new loader for the referenced schema-func (l *embeddedSchemaLoader) JsonReference() gojsonschema.JSONLoader {- return newEmbeddedSchemaLoader(l.source)-}--// ValidateModelConfigJSON validates a JSON file against the model configuration schema-// and returns a CustomModel if validation succeeds.-func ValidateModelConfigJSON(jsonFilePath string) (*shared.CustomModel, error) {- // Read the JSON file- jsonData, err := schemaFS.ReadFile(jsonFilePath)- if err != nil {- // Fall back to reading from the filesystem if not found in embedded FS- jsonData, err = schemaFS.ReadFile(jsonFilePath)- if err != nil {- return nil, fmt.Errorf("error reading JSON file: %v", err)- }- }-- // Create a schema loader for the embedded schema- schemaLoader := newEmbeddedSchemaLoader("../json-schemas/model-config.schema.json")- documentLoader := gojsonschema.NewBytesLoader(jsonData)-- // Validate- result, err := gojsonschema.Validate(schemaLoader, documentLoader)- if err != nil {- return nil, fmt.Errorf("schema validation error: %v", err)- }-- // Check validation result- if !result.Valid() {- var errorMessages []string- for _, desc := range result.Errors() {- errorMessages = append(errorMessages, fmt.Sprintf("- %s", desc))- }- return nil, fmt.Errorf("JSON validation failed:\n%s", strings.Join(errorMessages, "\n"))- }-- // Parse the validated JSON into a CustomModel- var jsonMap map[string]interface{}- if err := json.Unmarshal(jsonData, &jsonMap); err != nil {- return nil, fmt.Errorf("error parsing JSON: %v", err)- }-- // Create the model- model := &shared.CustomModel{- BaseModelShared: shared.BaseModelShared{- ModelCompatibility: shared.ModelCompatibility{},- },- }-- // Extract required fields- if modelId, ok := jsonMap["modelId"].(string); ok {- model.ModelId = shared.ModelId(modelId)- } else {- return nil, fmt.Errorf("missing or invalid 'modelId' in JSON")- }-- // Extract optional fields- if description, ok := jsonMap["description"].(string); ok {- model.Description = description- }-- // Extract numeric fields- if maxTokens, ok := jsonMap["maxTokens"].(float64); ok {- model.MaxTokens = int(maxTokens)- } else {- return nil, fmt.Errorf("missing or invalid 'maxTokens' in JSON")- }-- if maxConvoTokens, ok := jsonMap["defaultMaxConvoTokens"].(float64); ok {- model.DefaultMaxConvoTokens = int(maxConvoTokens)- } else {- return nil, fmt.Errorf("missing or invalid 'defaultMaxConvoTokens' in JSON")- }-- if maxOutputTokens, ok := jsonMap["maxOutputTokens"].(float64); ok {- model.MaxOutputTokens = int(maxOutputTokens)- } else {- return nil, fmt.Errorf("missing or invalid 'maxOutputTokens' in JSON")- }-- if reservedOutputTokens, ok := jsonMap["reservedOutputTokens"].(float64); ok {- model.ReservedOutputTokens = int(reservedOutputTokens)- } else {- return nil, fmt.Errorf("missing or invalid 'reservedOutputTokens' in JSON")- }-- // Extract output format- if outputFormat, ok := jsonMap["preferredOutputFormat"].(string); ok {- model.PreferredOutputFormat = shared.ModelOutputFormat(outputFormat)- } else {- return nil, fmt.Errorf("missing or invalid 'preferredOutputFormat' in JSON")- }-- // Extract boolean fields- if hasImageSupport, ok := jsonMap["hasImageSupport"].(bool); ok {- model.HasImageSupport = hasImageSupport- }-- if systemPromptDisabled, ok := jsonMap["systemPromptDisabled"].(bool); ok {- model.SystemPromptDisabled = systemPromptDisabled- }-- if roleParamsDisabled, ok := jsonMap["roleParamsDisabled"].(bool); ok {- model.RoleParamsDisabled = roleParamsDisabled- }-- if stopDisabled, ok := jsonMap["stopDisabled"].(bool); ok {- model.StopDisabled = stopDisabled- }-- if predictedOutputEnabled, ok := jsonMap["predictedOutputEnabled"].(bool); ok {- model.PredictedOutputEnabled = predictedOutputEnabled- }-- if includeReasoning, ok := jsonMap["includeReasoning"].(bool); ok {- model.IncludeReasoning = includeReasoning- }-- if reasoningEffortEnabled, ok := jsonMap["reasoningEffortEnabled"].(bool); ok {- model.ReasoningEffortEnabled = reasoningEffortEnabled- }-- if reasoningEffort, ok := jsonMap["reasoningEffort"].(string); ok {- model.ReasoningEffort = reasoningEffort- }-- if supportsCacheControl, ok := jsonMap["supportsCacheControl"].(bool); ok {- model.SupportsCacheControl = supportsCacheControl- }-- if singleMessageNoSystemPrompt, ok := jsonMap["singleMessageNoSystemPrompt"].(bool); ok {- model.SingleMessageNoSystemPrompt = singleMessageNoSystemPrompt- }-- if tokenEstimatePaddingPct, ok := jsonMap["tokenEstimatePaddingPct"].(float64); ok {- model.TokenEstimatePaddingPct = tokenEstimatePaddingPct- }-- if reasoningBudget, ok := jsonMap["reasoningBudget"].(float64); ok {- model.ReasoningBudget = int(reasoningBudget)- }-- // Extract providers- if providersArray, ok := jsonMap["providers"].([]interface{}); ok {- for _, providerItem := range providersArray {- if providerMap, ok := providerItem.(map[string]interface{}); ok {- provider := shared.ModelProvider{}-- if providerName, ok := providerMap["provider"].(string); ok {- provider.Provider = providerName- } else {- return nil, fmt.Errorf("missing or invalid 'provider' in providers array")- }-- if modelName, ok := providerMap["modelName"].(string); ok {- provider.ModelName = modelName- } else {- return nil, fmt.Errorf("missing or invalid 'modelName' in providers array")- }-- if customProvider, ok := providerMap["customProvider"].(string); ok {- provider.CustomProvider = customProvider- }-- model.Providers = append(model.Providers, provider)- }- }- }-- return model, nil-}diff --git a/app/cli/json-schemas/definitions/model-roles.schema.json b/app/cli/json-schemas/definitions/model-roles.schema.jsondeleted file mode 100644index 84ae3844..00000000--- a/app/cli/json-schemas/definitions/model-roles.schema.json+++ /dev/null@@ -1,17 +0,0 @@-{- "$schema": "https://json-schema.org/draft/2020-12/schema",- "$id": "https://plandex.ai/schemas/definitions/model-roles.schema.json",- "title": "Model Role Enum",- "description": "Reusable enum for model roles",- "enum": [- "planner",- "coder",- "architect",- "summarizer",- "builder",- "whole-file-builder",- "names",- "commit-messages",- "auto-continue"- ]-}\ No newline at end of filediff --git a/app/cli/json-schemas/model-provider-config.schema.json b/app/cli/json-schemas/model-provider-config.schema.jsondeleted file mode 100644index 3a79fcef..00000000--- a/app/cli/json-schemas/model-provider-config.schema.json+++ /dev/null@@ -1,109 +0,0 @@-{- "$schema": "https://json-schema.org/draft/2020-12/schema",- "$id": "https://plandex.ai/schemas/model-provider-config.schema.json",- "title": "Model Provider Config",- "description": "Config for a model provider",- "type": "object",- "properties": {- "provider": {- "$ref": "./definitions/model-providers.schema.json"- },- "customProvider": {- "type": "string"- },- "baseUrl": {- "type": "string"- },- "skipAuth": {- "type": "boolean",- "default": false- },- "apiKeyEnvVar": {- "type": "string"- },- "extraAuthVars": {- "type": "array",- "items": {- "type": "object",- "properties": {- "var": {- "type": "string"- },- "maybeJSONFilePath": {- "type": "boolean"- },- "required": {- "type": "boolean"- },- "default": {- "type": "string"- }- },- "required": [- "var"- ]- },- "minItems": 1- }- },- "required": [- "provider",- "baseUrl"- ],- "allOf": [- {- "if": {- "properties": {- "provider": {- "const": "custom"- }- }- },- "then": {- "required": [- "customProvider"- ]- },- "else": {- "not": {- "required": [- "customProvider"- ]- }- }- },- {- "anyOf": [- {- "properties": {- "provider": {- "not": {- "const": "custom"- }- }- }- },- {- "required": [- "apiKeyEnvVar"- ]- },- {- "required": [- "extraAuthVars"- ]- },- {- "required": [- "skipAuth"- ],- "properties": {- "skipAuth": {- "const": true- }- }- }- ]- }- ]-}\ No newline at end of filediff --git a/app/cli/json-schemas/definitions/auto-modes.schema.json b/app/cli/schema/json-schemas/definitions/auto-modes.schema.jsonsimilarity index 100%rename from app/cli/json-schemas/definitions/auto-modes.schema.jsonrename to app/cli/schema/json-schemas/definitions/auto-modes.schema.jsondiff --git a/app/cli/json-schemas/definitions/model-providers.schema.json b/app/cli/schema/json-schemas/definitions/model-providers.schema.jsonsimilarity index 100%rename from app/cli/json-schemas/definitions/model-providers.schema.jsonrename to app/cli/schema/json-schemas/definitions/model-providers.schema.jsondiff --git a/app/cli/json-schemas/model-config.schema.json b/app/cli/schema/json-schemas/model-config.schema.jsonsimilarity index 100%rename from app/cli/json-schemas/model-config.schema.jsonrename to app/cli/schema/json-schemas/model-config.schema.jsondiff --git a/app/cli/json-schemas/model-pack-config.schema.json b/app/cli/schema/json-schemas/model-pack-config.schema.jsonsimilarity index 100%rename from app/cli/json-schemas/model-pack-config.schema.jsonrename to app/cli/schema/json-schemas/model-pack-config.schema.jsondiff --git a/app/cli/schema/json-schemas/model-provider-config.schema.json b/app/cli/schema/json-schemas/model-provider-config.schema.jsonnew file mode 100644index 00000000..2ff85c32--- /dev/null+++ b/app/cli/schema/json-schemas/model-provider-config.schema.json@@ -0,0 +1,69 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "$id": "https://plandex.ai/schemas/model-provider-config.schema.json",+ "title": "Model Provider Config",+ "description": "Config for a model provider",+ "type": "object",+ "properties": {+ "baseUrl": {+ "type": "string"+ },+ "skipAuth": {+ "type": "boolean",+ "default": false+ },+ "apiKeyEnvVar": {+ "type": "string"+ },+ "extraAuthVars": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "var": {+ "type": "string"+ },+ "maybeJSONFilePath": {+ "type": "boolean"+ },+ "required": {+ "type": "boolean"+ },+ "default": {+ "type": "string"+ }+ },+ "required": [+ "var"+ ]+ },+ "minItems": 1+ }+ },+ "required": [+ "name",+ "baseUrl"+ ],+ "anyOf": [+ {+ "required": [+ "apiKeyEnvVar"+ ]+ },+ {+ "required": [+ "extraAuthVars"+ ]+ },+ {+ "required": [+ "skipAuth"+ ],+ "properties": {+ "skipAuth": {+ "const": true+ }+ }+ }+ ]+}\ No newline at end of filediff --git a/app/cli/json-schemas/model-role-config.schema.json b/app/cli/schema/json-schemas/model-role-config.schema.jsonsimilarity index 68%rename from app/cli/json-schemas/model-role-config.schema.jsonrename to app/cli/schema/json-schemas/model-role-config.schema.jsonindex 0170bb3a..a27d37ca 100644--- a/app/cli/json-schemas/model-role-config.schema.json+++ b/app/cli/schema/json-schemas/model-role-config.schema.json@@ -5,9 +5,6 @@"description": "Config for a defined model role within a model pack","type": "object","properties": {- "role": {- "$ref": "./definitions/model-roles.schema.json"- },"modelId": {"type": "string"},@@ -24,20 +21,19 @@"type": "number"},"largeContextFallback": {- "$ref": "./definitions/model-role-config.schema.json"+ "$ref": "./model-role-config.schema.json"},"largeOutputFallback": {- "$ref": "./definitions/model-role-config.schema.json"+ "$ref": "./model-role-config.schema.json"},"errorFallback": {- "$ref": "./definitions/model-role-config.schema.json"+ "$ref": "./model-role-config.schema.json"},"strongModel": {- "$ref": "./definitions/model-role-config.schema.json"+ "$ref": "./model-role-config.schema.json"}},"required": [- "role","modelId"]}\ No newline at end of filediff --git a/app/cli/schema/json-schemas/models-input.schema.json b/app/cli/schema/json-schemas/models-input.schema.jsonnew file mode 100644index 00000000..06d01009--- /dev/null+++ b/app/cli/schema/json-schemas/models-input.schema.json@@ -0,0 +1,27 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "$id": "https://plandex.ai/schemas/models-input.schema.json",+ "title": "Models Input",+ "description": "Input schema for custom models, providers, and model packs",+ "type": "object",+ "properties": {+ "customModels": {+ "type": "array",+ "items": {+ "$ref": "./model-config.schema.json"+ }+ },+ "customProviders": {+ "type": "array",+ "items": {+ "$ref": "./model-provider-config.schema.json"+ }+ },+ "customModelPacks": {+ "type": "array",+ "items": {+ "$ref": "./model-pack-config.schema.json"+ }+ }+ }+}\ No newline at end of filediff --git a/app/cli/json-schemas/plan-config.schema.json b/app/cli/schema/json-schemas/plan-config.schema.jsonsimilarity index 100%rename from app/cli/json-schemas/plan-config.schema.jsonrename to app/cli/schema/json-schemas/plan-config.schema.jsondiff --git a/app/cli/schema/schemas.go b/app/cli/schema/schemas.gonew file mode 100644index 00000000..ffa6b6ed--- /dev/null+++ b/app/cli/schema/schemas.go@@ -0,0 +1,127 @@+package schema++import (+ "bytes"+ "embed"+ "encoding/json"+ "errors"+ "fmt"+ "path"+ "strings"++ shared "plandex-shared"++ gojsonreference "github.com/xeipuuv/gojsonreference"+ "github.com/xeipuuv/gojsonschema"+)++const scheme = "embed://"++type SchemaPath string++const (+ SchemaPathInputConfig SchemaPath = "json-schemas/models-input.schema.json"+ SchemaPathPlanConfig SchemaPath = "json-schemas/plan-config.schema.json"+)++//go:embed json-schemas/*.schema.json json-schemas/definitions/*.schema.json+var schemaFS embed.FS++type embeddedSchemaLoader struct {+ source string+ fs embed.FS+}++func ValidateModelsInputJSON(jsonData []byte) (shared.ModelsInput, error) {+ return validateJSON[shared.ModelsInput](jsonData, SchemaPathInputConfig)+}++func validateJSON[T any](jsonData []byte, schemaPath SchemaPath) (T, error) {+ var zero T++ schemaLoader := newEmbeddedSchemaLoader(schemaPath)+ documentLoader := gojsonschema.NewBytesLoader(jsonData)++ result, err := gojsonschema.Validate(schemaLoader, documentLoader)+ if err != nil {+ return zero, err+ }+ if !result.Valid() {+ var msgs []string+ for _, d := range result.Errors() {+ msgs = append(msgs, "β’ "+d.String())+ }+ return zero, errors.New(strings.Join(msgs, "\n"))+ }++ var v T+ if err := json.Unmarshal(jsonData, &v); err != nil {+ return zero, fmt.Errorf("unmarshal error: %w", err)+ }+ return v, nil+}++func newEmbeddedSchemaLoader(source SchemaPath) *embeddedSchemaLoader {+ return &embeddedSchemaLoader{+ source: string(source),+ fs: schemaFS,+ }+}++func (l *embeddedSchemaLoader) JsonSource() interface{} {+ return l.source+}++func (l *embeddedSchemaLoader) LoadJSON() (interface{}, error) {+ // remove both "./" and the scheme prefix+ source := strings.TrimPrefix(l.source, "./")+ source = strings.TrimPrefix(source, scheme)++ // convert absolute Plandex URLs to our embed path+ const webPrefix = "https://plandex.ai/schemas/"+ if strings.HasPrefix(source, webPrefix) {+ source = path.Join("json-schemas", strings.TrimPrefix(source, webPrefix))+ }++ if strings.HasSuffix(source, ".schema.json") {+ schemaPath := source+ // for schemas with relative path references, add the json-schemas prefix+ if !strings.HasPrefix(schemaPath, "json-schemas/") {+ schemaPath = path.Join("json-schemas", schemaPath)+ }+ data, err := l.fs.ReadFile(schemaPath)+ if err != nil {+ return nil, fmt.Errorf("error reading embedded schema %s: %v", schemaPath, err)+ }+ var v interface{}+ dec := json.NewDecoder(bytes.NewReader(data))+ dec.UseNumber() // use numbers instead of floats+ if err := dec.Decode(&v); err != nil {+ return nil, fmt.Errorf("error parsing embedded schema %s: %v", source, err)+ }+ return v, nil+ }++ var v interface{}+ dec := json.NewDecoder(bytes.NewReader([]byte(source)))+ dec.UseNumber() // use numbers instead of floats+ if err := dec.Decode(&v); err != nil {+ return nil, fmt.Errorf("error parsing schema JSON: %v", err)+ }+ return v, nil+}++func (l *embeddedSchemaLoader) JsonReference() (gojsonreference.JsonReference, error) {+ return gojsonreference.NewJsonReference(scheme + l.source)+}++type embeddedLoaderFactory struct{}++func (embeddedLoaderFactory) New(source string) gojsonschema.JSONLoader {+ source = strings.TrimPrefix(source, scheme)+ return newEmbeddedSchemaLoader(SchemaPath(source))+}++func (l *embeddedSchemaLoader) LoaderFactory() gojsonschema.JSONLoaderFactory {+ return embeddedLoaderFactory{}+}diff --git a/app/cli/types/api.go b/app/cli/types/api.goindex 5efb9f3b..331a9f67 100644--- a/app/cli/types/api.go+++ b/app/cli/types/api.go@@ -103,18 +103,13 @@ type ApiClient interface {GetDefaultPlanConfig() (*shared.PlanConfig, *shared.ApiError)UpdateDefaultPlanConfig(req shared.UpdateDefaultPlanConfigRequest) *shared.ApiError- CreateCustomModel(model *shared.CustomModel) *shared.ApiError- UpdateCustomModel(model *shared.CustomModel) *shared.ApiError+ CreateCustomModels(input *shared.ModelsInput) *shared.ApiErrorListCustomModels() ([]*shared.CustomModel, *shared.ApiError)DeleteCustomModel(modelId string) *shared.ApiError- CreateCustomProvider(provider *shared.CustomProvider) *shared.ApiError- UpdateCustomProvider(provider *shared.CustomProvider) *shared.ApiErrorListCustomProviders() ([]*shared.CustomProvider, *shared.ApiError)DeleteCustomProvider(providerId string) *shared.ApiError- CreateModelPack(set *shared.ModelPack) *shared.ApiError- UpdateModelPack(set *shared.ModelPack) *shared.ApiErrorListModelPacks() ([]*shared.ModelPack, *shared.ApiError)DeleteModelPack(setId string) *shared.ApiErrordiff --git a/app/server/db/data_models.go b/app/server/db/data_models.goindex 69866136..b28d3689 100644--- a/app/server/db/data_models.go+++ b/app/server/db/data_models.go@@ -315,6 +315,21 @@ type ModelPack struct {CreatedAt time.Time `db:"created_at"`}+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,+ }+}+func (modelPack *ModelPack) ToApi() *shared.ModelPack {return &shared.ModelPack{Id: modelPack.Id,@@ -331,28 +346,6 @@ func (modelPack *ModelPack) ToApi() *shared.ModelPack {}}-// old version prior to 2.2.0 models refactor-// type AvailableModel struct {-// Id string `db:"id"`-// OrgId string `db:"org_id"`-// Provider shared.ModelProvider `db:"provider"`-// CustomProvider *string `db:"custom_provider"`-// BaseUrl string `db:"base_url"`-// ModelTag shared.ModelTag `db:"model_tag"`-// ModelId shared.ModelId `db:"model_id"`-// ModelName shared.ModelName `db:"model_name"`-// Description string `db:"description"`-// MaxTokens int `db:"max_tokens"`-// ApiKeyEnvVar string `db:"api_key_env_var"`-// DefaultMaxConvoTokens int `db:"default_max_convo_tokens"`-// MaxOutputTokens int `db:"max_output_tokens"`-// ReservedOutputTokens int `db:"reserved_output_tokens"`-// HasImageSupport bool `db:"has_image_support"`-// PreferredOutputFormat shared.ModelOutputFormat `db:"preferred_output_format"`-// CreatedAt time.Time `db:"created_at"`-// UpdatedAt time.Time `db:"updated_at"`-// }-type CustomModel struct {Id string `db:"id"`OrgId string `db:"org_id"`@@ -457,6 +450,8 @@ func (model *CustomModel) ToApi() *shared.CustomModel {},},Providers: providers,+ CreatedAt: &model.CreatedAt,+ UpdatedAt: &model.UpdatedAt,}}@@ -546,7 +541,7 @@ func (providers *CustomModelProviders) Scan(src interface{}) error {return fmt.Errorf("unsupported data type: %T", src)}-func (providers *CustomModelProviders) Value() (driver.Value, error) {+func (providers CustomModelProviders) Value() (driver.Value, error) {return json.Marshal(providers)}diff --git a/app/server/db/models.go b/app/server/db/models.goindex 7b3e82a8..1a520516 100644--- a/app/server/db/models.go+++ b/app/server/db/models.go@@ -3,93 +3,65 @@ package dbimport ("database/sql""fmt"++ "github.com/jmoiron/sqlx"+ "github.com/lib/pq")-func CreateCustomModel(model *CustomModel) error {- query := `INSERT INTO custom_models (- org_id,- model_id,- publisher,- description,- max_tokens,- default_max_convo_tokens,- max_output_tokens,- reserved_output_tokens,- has_image_support,- preferred_output_format,- system_prompt_disabled,- role_params_disabled,- stop_disabled,- predicted_output_enabled,- reasoning_effort_enabled,- reasoning_effort,- include_reasoning,- reasoning_budget,- supports_cache_control,- single_message_no_system_prompt,- token_estimate_padding_pct,- providers- ) VALUES (- $1,$2,$3,$4,$5,$6,$7,$8,$9,$10,- $11,$12,$13,$14,$15,$16,$17,$18,$19,$20,$21,$22- )- RETURNING id, created_at, updated_at`-- return Conn.QueryRow(- query,- model.OrgId,- model.ModelId,- model.Publisher,- model.Description,- model.MaxTokens,- model.DefaultMaxConvoTokens,- model.MaxOutputTokens,- model.ReservedOutputTokens,- model.HasImageSupport,- model.PreferredOutputFormat,- model.SystemPromptDisabled,- model.RoleParamsDisabled,- model.StopDisabled,- model.PredictedOutputEnabled,- model.ReasoningEffortEnabled,- model.ReasoningEffort,- model.IncludeReasoning,- model.ReasoningBudget,- model.SupportsCacheControl,- model.SingleMessageNoSystemPrompt,- model.TokenEstimatePaddingPct,- model.Providers,- ).Scan(&model.Id, &model.CreatedAt, &model.UpdatedAt)-}+func UpsertCustomModel(tx *sqlx.Tx, model *CustomModel) error {+ if tx == nil {+ return fmt.Errorf("tx is nil")+ }+ query := `+INSERT INTO custom_models (+ org_id, model_id,+ publisher, description,+ max_tokens, default_max_convo_tokens, max_output_tokens, reserved_output_tokens,+ has_image_support, preferred_output_format,+ system_prompt_disabled, role_params_disabled, stop_disabled,+ predicted_output_enabled, reasoning_effort_enabled, reasoning_effort,+ include_reasoning, reasoning_budget, supports_cache_control,+ single_message_no_system_prompt, token_estimate_padding_pct,+ providers+)+VALUES (+ $1,$2,+ $3,$4,+ $5,$6,$7,$8,+ $9,$10,+ $11,$12,$13,+ $14,$15,$16,+ $17,$18,$19,+ $20,$21,+ $22+)+ON CONFLICT (org_id, model_id)+DO UPDATE SET+ publisher = EXCLUDED.publisher,+ description = EXCLUDED.description,+ max_tokens = EXCLUDED.max_tokens,+ default_max_convo_tokens = EXCLUDED.default_max_convo_tokens,+ max_output_tokens = EXCLUDED.max_output_tokens,+ reserved_output_tokens = EXCLUDED.reserved_output_tokens,+ has_image_support = EXCLUDED.has_image_support,+ preferred_output_format = EXCLUDED.preferred_output_format,+ system_prompt_disabled = EXCLUDED.system_prompt_disabled,+ role_params_disabled = EXCLUDED.role_params_disabled,+ stop_disabled = EXCLUDED.stop_disabled,+ predicted_output_enabled = EXCLUDED.predicted_output_enabled,+ reasoning_effort_enabled = EXCLUDED.reasoning_effort_enabled,+ reasoning_effort = EXCLUDED.reasoning_effort,+ include_reasoning = EXCLUDED.include_reasoning,+ reasoning_budget = EXCLUDED.reasoning_budget,+ supports_cache_control = EXCLUDED.supports_cache_control,+ single_message_no_system_prompt = EXCLUDED.single_message_no_system_prompt,+ token_estimate_padding_pct = EXCLUDED.token_estimate_padding_pct,+ providers = EXCLUDED.providers+RETURNING id, created_at, updated_at;+`-func UpdateCustomModel(model *CustomModel) error {- query := `UPDATE custom_models SET- model_id = $3,- publisher = $4,- description = $5,- max_tokens = $6,- default_max_convo_tokens = $7,- max_output_tokens = $8,- reserved_output_tokens = $9,- has_image_support = $10,- preferred_output_format = $11,- system_prompt_disabled = $12,- role_params_disabled = $13,- stop_disabled = $14,- predicted_output_enabled = $15,- reasoning_effort_enabled = $16,- reasoning_effort = $17,- include_reasoning = $18,- reasoning_budget = $19,- supports_cache_control = $20,- single_message_no_system_prompt = $21,- token_estimate_padding_pct = $22,- providers = $23- WHERE id = $1 AND org_id = $2`-- _, err := Conn.Exec(+ return tx.QueryRow(query,- model.Id,model.OrgId,model.ModelId,model.Publisher,@@ -112,8 +84,7 @@ func UpdateCustomModel(model *CustomModel) error {model.SingleMessageNoSystemPrompt,model.TokenEstimatePaddingPct,model.Providers,- )- return err+ ).Scan(&model.Id, &model.CreatedAt, &model.UpdatedAt)}func ListCustomModels(orgId string) ([]*CustomModel, error) {@@ -122,6 +93,13 @@ func ListCustomModels(orgId string) ([]*CustomModel, error) {return models, err}+func ListCustomModelsForModelIds(orgId string, modelIds []string) ([]*CustomModel, error) {+ var models []*CustomModel+ query := `SELECT * FROM custom_models WHERE org_id = $1 AND model_id = ANY($2) ORDER BY created_at`+ err := Conn.Select(&models, query, orgId, pq.Array(modelIds))+ return models, err+}+func GetCustomModel(orgId, id string) (*CustomModel, error) {var model CustomModelerr := Conn.Get(&model, `SELECT * FROM custom_models WHERE org_id = $1 AND id = $2`, orgId, id)@@ -139,18 +117,29 @@ func DeleteCustomModel(orgId, id string) error {return err}-func CreateCustomProvider(p *CustomProvider) error {- query := `INSERT INTO custom_providers (- org_id,- name,- base_url,- skip_auth,- api_key_env_var,- extra_auth_vars- ) VALUES ($1,$2,$3,$4,$5,$6)- RETURNING id, created_at, updated_at`- return Conn.QueryRow(- query,+func UpsertCustomProvider(tx *sqlx.Tx, p *CustomProvider) error {+ if tx == nil {+ return fmt.Errorf("tx is nil")+ }+ const q = `+INSERT INTO custom_providers (+ org_id, name, base_url,+ skip_auth, api_key_env_var, extra_auth_vars+)+VALUES (+ $1,$2,$3,+ $4,$5,$6+)+ON CONFLICT (org_id, name)+DO UPDATE SET+ base_url = EXCLUDED.base_url,+ skip_auth = EXCLUDED.skip_auth,+ api_key_env_var = EXCLUDED.api_key_env_var,+ extra_auth_vars = EXCLUDED.extra_auth_vars+RETURNING id, created_at, updated_at;+`+ return tx.QueryRow(+ q,p.OrgId,p.Name,p.BaseUrl,@@ -160,27 +149,6 @@ func CreateCustomProvider(p *CustomProvider) error {).Scan(&p.Id, &p.CreatedAt, &p.UpdatedAt)}-func UpdateCustomProvider(p *CustomProvider) error {- query := `UPDATE custom_providers SET- name = $3,- base_url = $4,- skip_auth = $5,- api_key_env_var = $6,- extra_auth_vars = $7- WHERE id = $1 AND org_id = $2`- _, err := Conn.Exec(- query,- p.Id,- p.OrgId,- p.Name,- p.BaseUrl,- p.SkipAuth,- p.ApiKeyEnvVar,- p.ExtraAuthVars,- )- return err-}-func GetCustomProvider(orgId, id string) (*CustomProvider, error) {var provider CustomProvidererr := Conn.Get(&provider, `SELECT * FROM custom_providers WHERE org_id = $1 AND id = $2`, orgId, id)@@ -199,33 +167,64 @@ func ListCustomProviders(orgId string) ([]*CustomProvider, error) {return providers, err}+func ListCustomProvidersForNames(orgId string, names []string) ([]*CustomProvider, error) {+ var providers []*CustomProvider+ query := `SELECT * FROM custom_providers WHERE org_id = $1 AND name = ANY($2) ORDER BY name`+ err := Conn.Select(&providers, query, orgId, pq.Array(names))+ return providers, err+}+func DeleteCustomProvider(orgId, id string) error {_, err := Conn.Exec(`DELETE FROM custom_providers WHERE org_id = $1 AND id = $2`, orgId, id)return err}-func CreateModelPack(ms *ModelPack) error {- query := `INSERT INTO model_sets (org_id, name, description, planner, coder, plan_summary, builder, whole_file_builder, namer, commit_msg, exec_status, context_loader) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)- RETURNING id, created_at`-- err := Conn.QueryRow(query, ms.OrgId, ms.Name, ms.Description, ms.Planner, ms.Coder, ms.PlanSummary, ms.Builder, ms.WholeFileBuilder, ms.Namer, ms.CommitMsg, ms.ExecStatus, ms.Architect).Scan(&ms.Id, &ms.CreatedAt)-- if err != nil {- return fmt.Errorf("error inserting new model pack: %v", err)+func UpsertModelPack(tx *sqlx.Tx, mp *ModelPack) error {+ if tx == nil {+ return fmt.Errorf("tx is nil")}-- return nil-}--func UpdateModelPack(ms *ModelPack) error {- query := `UPDATE model_sets SET name = $2, description = $3, planner = $4, coder = $5, plan_summary = $6, builder = $7, whole_file_builder = $8, namer = $9, commit_msg = $10, exec_status = $11, context_loader = $12 WHERE id = $1`- _, err := Conn.Exec(query, ms.Id, ms.Name, ms.Description, ms.Planner, ms.Coder, ms.PlanSummary, ms.Builder, ms.WholeFileBuilder, ms.Namer, ms.CommitMsg, ms.ExecStatus, ms.Architect)-- if err != nil {- return fmt.Errorf("error updating model pack: %v", err)- }-- return nil+ const q = `+INSERT INTO model_sets (+ org_id, name, description,+ planner, coder, plan_summary,+ builder, whole_file_builder, namer,+ commit_msg, exec_status, context_loader+)+VALUES (+ $1,$2,$3,+ $4,$5,$6,+ $7,$8,$9,+ $10,$11,$12+)+ON CONFLICT (org_id, name)+DO UPDATE SET+ description = EXCLUDED.description,+ planner = EXCLUDED.planner,+ coder = EXCLUDED.coder,+ plan_summary = EXCLUDED.plan_summary,+ builder = EXCLUDED.builder,+ whole_file_builder = EXCLUDED.whole_file_builder,+ namer = EXCLUDED.namer,+ commit_msg = EXCLUDED.commit_msg,+ exec_status = EXCLUDED.exec_status,+ context_loader = EXCLUDED.context_loader+RETURNING id, created_at;+`+ return tx.QueryRow(+ q,+ mp.OrgId,+ mp.Name,+ mp.Description,+ mp.Planner,+ mp.Coder,+ mp.PlanSummary,+ mp.Builder,+ mp.WholeFileBuilder,+ mp.Namer,+ mp.CommitMsg,+ mp.ExecStatus,+ mp.Architect,+ ).Scan(&mp.Id, &mp.CreatedAt)}func ListModelPacks(orgId string) ([]*ModelPack, error) {@@ -241,6 +240,13 @@ func ListModelPacks(orgId string) ([]*ModelPack, error) {return modelPacks, nil}+func ListModelPacksForNames(orgId string, names []string) ([]*ModelPack, error) {+ var modelPacks []*ModelPack+ query := `SELECT * FROM model_sets WHERE org_id = $1 AND name = ANY($2)`+ err := Conn.Select(&modelPacks, query, orgId, names)+ return modelPacks, err+}+func DeleteModelPack(setId string) error {query := `DELETE FROM model_sets WHERE id = $1`_, err := Conn.Exec(query, setId)diff --git a/app/server/handlers/models.go b/app/server/handlers/models.goindex d8748e2b..7aa56460 100644--- a/app/server/handlers/models.go+++ b/app/server/handlers/models.go@@ -11,6 +11,7 @@ import (shared "plandex-shared""github.com/gorilla/mux"+ "github.com/jmoiron/sqlx")const CustomModelsMinClientVersion = "2.2.0"@@ -27,87 +28,194 @@ func CreateCustomModelHandler(w http.ResponseWriter, r *http.Request) {return}- var model shared.CustomModel- if err := json.NewDecoder(r.Body).Decode(&model); err != nil {+ var modelsInput shared.ModelsInput+ if err := json.NewDecoder(r.Body).Decode(&modelsInput); err != nil {log.Printf("Error decoding request body: %v\n", err)http.Error(w, "Invalid request body", http.StatusBadRequest)return}- if model.ModelId == "" {- msg := "Model id is required"- log.Println(msg)- http.Error(w, msg, http.StatusBadRequest)+ if len(modelsInput.CustomModels)+len(modelsInput.CustomProviders)+len(modelsInput.CustomModelPacks) == 0 {+ http.Error(w, "No custom models, providers, or model packs provided", http.StatusBadRequest)return}- if shared.BuiltInBaseModelsById[model.ModelId] != nil {- msg := fmt.Sprintf("%s is a built-in base model id, so it can't be used for a custom model", model.ModelId)- log.Println(msg)- http.Error(w, msg, http.StatusUnprocessableEntity)- return+ for _, model := range modelsInput.CustomModels {+ if model.ModelId == "" {+ msg := "Model id is required"+ log.Println(msg)+ http.Error(w, msg, http.StatusBadRequest)+ return+ }++ if shared.BuiltInBaseModelsById[model.ModelId] != nil {+ msg := fmt.Sprintf("%s is a built-in base model id, so it can't be used for a custom model", model.ModelId)+ log.Println(msg)+ http.Error(w, msg, http.StatusUnprocessableEntity)+ return+ }}- dbModel := db.CustomModelFromApi(&model)- dbModel.OrgId = auth.OrgId+ for _, provider := range modelsInput.CustomProviders {+ if provider.Name == "" {+ msg := "Provider name is required"+ log.Println(msg)+ http.Error(w, msg, http.StatusBadRequest)+ return+ }+ }- if err := db.CreateCustomModel(dbModel); err != nil {- log.Printf("Error creating custom model: %v\n", err)- http.Error(w, "Failed to create custom model: "+err.Error(), http.StatusInternalServerError)- return+ for _, modelPack := range modelsInput.CustomModelPacks {+ if modelPack.Name == "" {+ msg := "Model pack name is required"+ log.Println(msg)+ http.Error(w, msg, http.StatusBadRequest)+ return+ }}- w.WriteHeader(http.StatusCreated)+ var customModelIds = make(map[string]bool)+ var customProviderNames = make(map[string]bool)- log.Println("Successfully created custom model")-}+ if len(modelsInput.CustomModels) > 0 {-func UpdateCustomModelHandler(w http.ResponseWriter, r *http.Request) {- log.Println("Received request for UpdateCustomModelHandler")+ var modelIds []string+ for _, model := range modelsInput.CustomModels {+ modelIds = append(modelIds, string(model.ModelId))+ }- auth := Authenticate(w, r, true)- if auth == nil {- return- }+ 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+ }- if !requireMinClientVersion(w, r, CustomModelsMinClientVersion) {- return}- id := mux.Vars(r)["modelId"]+ if len(modelsInput.CustomProviders) > 0 {+ var names []string+ for _, provider := range modelsInput.CustomProviders {+ names = append(names, provider.Name)+ }- var model shared.CustomModel- if err := json.NewDecoder(r.Body).Decode(&model); err != nil {- log.Printf("Error decoding request body: %v\n", err)- http.Error(w, "Invalid request body", http.StatusBadRequest)- return- }+ customProviders, err := db.ListCustomProvidersForNames(auth.OrgId, names)+ if err != nil {+ log.Printf("Error fetching custom providers: %v\n", err)+ http.Error(w, "Failed to create custom model: "+err.Error(), http.StatusInternalServerError)+ return+ }- res, err := db.GetCustomModel(auth.OrgId, id)- if err != nil {- log.Printf("Error fetching custom model: %v\n", err)- http.Error(w, "Failed to fetch custom model: "+err.Error(), http.StatusInternalServerError)- return+ for _, provider := range customProviders {+ customProviderNames[provider.Name] = true+ }}- if res == nil {- http.Error(w, "Custom model not found", http.StatusNotFound)- return+ var toUpsertCustomModels []*db.CustomModel+ var toUpsertCustomProviders []*db.CustomProvider+ var toUpsertModelPacks []*db.ModelPack++ willCreateModelIds := make(map[string]bool)+ willCreateProviderNames := make(map[string]bool)++ for _, provider := range modelsInput.CustomProviders {+ dbProvider := db.CustomProviderFromApi(&provider)+ dbProvider.Id = provider.Id+ dbProvider.OrgId = auth.OrgId++ toUpsertCustomProviders = append(toUpsertCustomProviders, dbProvider)+ willCreateProviderNames[provider.Name] = true+ }++ for _, model := range modelsInput.CustomModels {+ // ensure that providers are either built-in, being created, or already exist+ for _, provider := range model.Providers {+ if provider.Provider == shared.ModelProviderCustom {+ _, exists := customProviderNames[*provider.CustomProvider]+ _, creating := willCreateProviderNames[*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)+ http.Error(w, msg, http.StatusUnprocessableEntity)+ return+ }+ } else {+ _, builtIn := shared.BuiltInModelProviderConfigs[provider.Provider]+ if !builtIn {+ msg := fmt.Sprintf("'%s' is not a built-in model provider", provider.Provider)+ log.Println(msg)+ http.Error(w, msg, http.StatusUnprocessableEntity)+ return+ }+ }+ }++ dbModel := db.CustomModelFromApi(&model)+ dbModel.Id = model.Id+ dbModel.OrgId = auth.OrgId++ toUpsertCustomModels = append(toUpsertCustomModels, dbModel)+ willCreateModelIds[string(model.ModelId)] = true+ }++ for _, modelPack := range modelsInput.CustomModelPacks {+ // ensure that all models are either built-in, being created, or already exist+ allModelIds := modelPack.AllModelIds()+ for _, modelId := range allModelIds {+ _, exists := customModelIds[string(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)+ http.Error(w, msg, http.StatusUnprocessableEntity)+ return+ }+ }++ mp := modelPack.ToModelPack()+ dbMp := db.ModelPackFromApi(&mp)+ dbMp.OrgId = auth.OrgId+ dbMp.Id = mp.Id++ toUpsertModelPacks = append(toUpsertModelPacks, dbMp)}- dbModel := db.CustomModelFromApi(&model)- dbModel.Id = id- dbModel.OrgId = auth.OrgId+ 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)+ }+ }- if err := db.UpdateCustomModel(dbModel); err != nil {- log.Printf("Error updating custom model: %v\n", err)- http.Error(w, "Failed to update custom model: "+err.Error(), http.StatusInternalServerError)+ for _, provider := range toUpsertCustomProviders {+ if err := db.UpsertCustomProvider(tx, provider); err != nil {+ return fmt.Errorf("error creating custom provider: %w", err)+ }+ }++ for _, modelPack := range toUpsertModelPacks {+ if err := db.UpsertModelPack(tx, modelPack); err != nil {+ return fmt.Errorf("error creating model pack: %w", err)+ }+ }++ return nil+ })++ if err != nil {+ log.Printf("Error: %v\n", err)+ http.Error(w, "Failed to create custom model: "+err.Error(), http.StatusInternalServerError)return}w.WriteHeader(http.StatusOK)- log.Println("Successfully updated custom model")+ log.Println("Successfully created custom model")}func GetCustomModelHandler(w http.ResponseWriter, r *http.Request) {@@ -221,67 +329,6 @@ func DeleteCustomModelHandler(w http.ResponseWriter, r *http.Request) {log.Println("Successfully deleted custom model")}-func CreateCustomProviderHandler(w http.ResponseWriter, r *http.Request) {- auth := Authenticate(w, r, true)- if auth == nil {- return- }-- if os.Getenv("IS_CLOUD") != "" {- http.Error(w, "Custom model providers are not supported on Plandex Cloud", http.StatusBadRequest)- return- }-- var p shared.CustomProvider- if err := json.NewDecoder(r.Body).Decode(&p); err != nil {- http.Error(w, "invalid body", http.StatusBadRequest)- return- }-- dbP := db.CustomProviderFromApi(&p)- dbP.OrgId = auth.OrgId-- if err := db.CreateCustomProvider(dbP); err != nil {- http.Error(w, err.Error(), http.StatusInternalServerError)- return- }- w.WriteHeader(http.StatusCreated)-- log.Println("Successfully created custom provider")-}--func UpdateCustomProviderHandler(w http.ResponseWriter, r *http.Request) {- auth := Authenticate(w, r, true)- if auth == nil {- return- }-- if os.Getenv("IS_CLOUD") != "" {- http.Error(w, "Custom model providers are not supported on Plandex Cloud", http.StatusBadRequest)- return- }-- id := mux.Vars(r)["providerId"]-- var p shared.CustomProvider- if err := json.NewDecoder(r.Body).Decode(&p); err != nil {- http.Error(w, "invalid body", http.StatusBadRequest)- return- }- p.Id = id-- dbP := db.CustomProviderFromApi(&p)- dbP.OrgId = auth.OrgId-- if err := db.UpdateCustomProvider(dbP); err != nil {- http.Error(w, err.Error(), http.StatusInternalServerError)- return- }- w.WriteHeader(http.StatusOK)-- log.Println("Successfully updated custom provider")-}-func GetCustomProviderHandler(w http.ResponseWriter, r *http.Request) {auth := Authenticate(w, r, true)if auth == nil {@@ -371,36 +418,7 @@ func CreateModelPackHandler(w http.ResponseWriter, r *http.Request) {return}- var ms shared.ModelPack- if err := json.NewDecoder(r.Body).Decode(&ms); err != nil {- http.Error(w, "Invalid request body", http.StatusBadRequest)- return- }-- dbMs := &db.ModelPack{- OrgId: auth.OrgId,- Name: ms.Name,- Description: ms.Description,- Planner: ms.Planner,- Architect: ms.Architect,- Coder: ms.Coder,- Builder: ms.Builder,- WholeFileBuilder: ms.WholeFileBuilder,- Namer: ms.Namer,- CommitMsg: ms.CommitMsg,- PlanSummary: ms.PlanSummary,- ExecStatus: ms.ExecStatus,- }-- if err := db.CreateModelPack(dbMs); err != nil {- log.Printf("Error creating model pack: %v\n", err)- http.Error(w, "Failed to create model pack: "+err.Error(), http.StatusInternalServerError)- return- }-- w.WriteHeader(http.StatusCreated)-- log.Println("Successfully created model pack")+ http.Error(w, "Use POST /custom_models instead to create model packs", http.StatusBadRequest)}func UpdateModelPackHandler(w http.ResponseWriter, r *http.Request) {@@ -415,59 +433,7 @@ func UpdateModelPackHandler(w http.ResponseWriter, r *http.Request) {return}- mpId := mux.Vars(r)["setId"]-- var ms shared.ModelPack- if err := json.NewDecoder(r.Body).Decode(&ms); err != nil {- http.Error(w, "Invalid request body", http.StatusBadRequest)- return- }-- packs, err := db.ListModelPacks(auth.OrgId)- if err != nil {- log.Printf("Error fetching model packs: %v\n", err)- http.Error(w, "Failed to fetch model packs: "+err.Error(), http.StatusInternalServerError)- return- }-- found := false- for _, m := range packs {- if m.Id == mpId {- found = true- break- }- }-- if !found {- http.Error(w, "Model pack not found", http.StatusNotFound)- return- }-- dbMs := &db.ModelPack{- Id: mpId,- OrgId: auth.OrgId,- Name: ms.Name,- Description: ms.Description,- Planner: ms.Planner,- Coder: ms.Coder,- PlanSummary: ms.PlanSummary,- Builder: ms.Builder,- WholeFileBuilder: ms.WholeFileBuilder,- Namer: ms.Namer,- CommitMsg: ms.CommitMsg,- ExecStatus: ms.ExecStatus,- Architect: ms.Architect,- }-- if err := db.UpdateModelPack(dbMs); err != nil {- log.Printf("Error updating model pack: %v\n", err)- http.Error(w, "Failed to update model pack: "+err.Error(), http.StatusInternalServerError)- return- }-- w.WriteHeader(http.StatusOK)-- log.Println("Successfully updated model pack")+ http.Error(w, "Use POST /custom_models instead to update model packs", http.StatusBadRequest)}func ListModelPacksHandler(w http.ResponseWriter, r *http.Request) {diff --git a/app/server/migrations/2025052200_model_pack_cols.down.sql b/app/server/migrations/2025052200_model_pack_cols.down.sqlnew file mode 100644index 00000000..c7f9d49e--- /dev/null+++ b/app/server/migrations/2025052200_model_pack_cols.down.sql@@ -0,0 +1,6 @@+ALTER TABLE model_sets+ DROP COLUMN IF EXISTS updated_at;++DROP TRIGGER IF EXISTS model_set_modtime ON model_sets;++DROP INDEX IF EXISTS model_set_unique_idx;diff --git a/app/server/migrations/2025052200_model_pack_cols.up.sql b/app/server/migrations/2025052200_model_pack_cols.up.sqlnew file mode 100644index 00000000..f3fde587--- /dev/null+++ b/app/server/migrations/2025052200_model_pack_cols.up.sql@@ -0,0 +1,7 @@+ALTER TABLE model_sets+ ADD COLUMN updated_at TIMESTAMP NOT NULL DEFAULT NOW();++CREATE TRIGGER model_set_modtime BEFORE UPDATE ON model_sets+ FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();++CREATE UNIQUE INDEX IF NOT EXISTS model_set_unique_idx ON model_sets(org_id, name);\ No newline at end of filediff --git a/app/server/model/plan/tell_stream_finish.go b/app/server/model/plan/tell_stream_finish.goindex f4a57b55..2325d401 100644--- a/app/server/model/plan/tell_stream_finish.go+++ b/app/server/model/plan/tell_stream_finish.go@@ -70,13 +70,19 @@ func (state *activeTellStreamState) handleStreamFinished() handleStreamFinishedR}autoLoadContextResult := state.checkAutoLoadContext()- addedSubtasks := state.checkNewSubtasks()- removedSubtasks := state.checkRemoveSubtasks()- hasNewSubtasks := len(addedSubtasks) > 0+ checkNewSubtasksResult := state.checkNewSubtasks()++ hasExplicitTasks := checkNewSubtasksResult.hasExplicitTasks+ addedSubtasks := checkNewSubtasksResult.newSubtasks++ checkRemoveSubtasksResult := state.checkRemoveSubtasks()++ removedSubtasks := checkRemoveSubtasksResult.removedSubtasks+ hasExplicitRemoveTasks := checkRemoveSubtasksResult.hasExplicitRemoveTaskslog.Println("removedSubtasks:\n", spew.Sdump(removedSubtasks))log.Println("addedSubtasks:\n", spew.Sdump(addedSubtasks))- log.Println("hasNewSubtasks:\n", hasNewSubtasks)+ log.Println("hasNewSubtasks:\n", hasExplicitTasks)handleDescAndExecStatusRes := state.handleDescAndExecStatus()if handleDescAndExecStatusRes.shouldContinueMainLoop || handleDescAndExecStatusRes.shouldReturn {@@ -91,7 +97,7 @@ func (state *activeTellStreamState) handleStreamFinished() handleStreamFinishedRreplyOperations: replyOperations,generatedDescription: generatedDescription,subtaskFinished: subtaskFinished,- hasNewSubtasks: hasNewSubtasks,+ hasNewSubtasks: hasExplicitTasks,autoLoadContextResult: autoLoadContextResult,addedSubtasks: addedSubtasks,removedSubtasks: removedSubtasks,@@ -175,10 +181,10 @@ func (state *activeTellStreamState) handleStreamFinished() handleStreamFinishedR}willContinue := state.willContinuePlan(willContinuePlanParams{- hasNewSubtasks: hasNewSubtasks,+ hasNewSubtasks: hasExplicitTasks,allSubtasksFinished: allSubtasksFinished,activatePaths: autoLoadContextResult.activatePaths,- removedSubtasks: len(removedSubtasks) > 0,+ removedSubtasks: hasExplicitRemoveTasks,hasExplicitPaths: autoLoadContextResult.hasExplicitPaths,})diff --git a/app/server/model/plan/tell_stream_status.go b/app/server/model/plan/tell_stream_status.goindex 509e0dfd..0a1f1a22 100644--- a/app/server/model/plan/tell_stream_status.go+++ b/app/server/model/plan/tell_stream_status.go@@ -155,7 +155,7 @@ func (state *activeTellStreamState) willContinuePlan(params willContinuePlanPara}// if there are new subtasks, continue- if hasNewSubtasks {+ if hasNewSubtasks && !allSubtasksFinished {log.Println("[willContinuePlan] Has new subtasks - continuing")return true}diff --git a/app/server/model/plan/tell_subtasks.go b/app/server/model/plan/tell_subtasks.goindex b2d78708..f77603ce 100644--- a/app/server/model/plan/tell_subtasks.go+++ b/app/server/model/plan/tell_subtasks.go@@ -77,11 +77,19 @@ func (state *activeTellStreamState) formatSubtasks() string {return subtasksText}-func (state *activeTellStreamState) checkNewSubtasks() []*db.Subtask {+type checkNewSubtasksResult struct {+ hasExplicitTasks bool+ newSubtasks []*db.Subtask+}++func (state *activeTellStreamState) checkNewSubtasks() checkNewSubtasksResult {activePlan := GetActivePlan(state.plan.Id, state.branch)if activePlan == nil {- return nil+ return checkNewSubtasksResult{+ hasExplicitTasks: false,+ newSubtasks: nil,+ }}content := activePlan.CurrentReplyContent@@ -90,7 +98,10 @@ func (state *activeTellStreamState) checkNewSubtasks() []*db.Subtask {if len(subtasks) == 0 {log.Println("No new subtasks found")- return nil+ return checkNewSubtasksResult{+ hasExplicitTasks: false,+ newSubtasks: nil,+ }}log.Println("Found new subtasks:", len(subtasks))@@ -154,14 +165,25 @@ func (state *activeTellStreamState) checkNewSubtasks() []*db.Subtask {// log.Println("state.subtasks:\n", spew.Sdump(state.subtasks))log.Println("state.currentSubtask:\n", spew.Sdump(state.currentSubtask))- return newSubtasks+ return checkNewSubtasksResult{+ hasExplicitTasks: len(subtasks) > 0,+ newSubtasks: newSubtasks,+ }+}++type checkRemoveSubtasksResult struct {+ hasExplicitRemoveTasks bool+ removedSubtasks []string}-func (state *activeTellStreamState) checkRemoveSubtasks() []string {+func (state *activeTellStreamState) checkRemoveSubtasks() checkRemoveSubtasksResult {activePlan := GetActivePlan(state.plan.Id, state.branch)if activePlan == nil {- return nil+ return checkRemoveSubtasksResult{+ hasExplicitRemoveTasks: false,+ removedSubtasks: nil,+ }}content := activePlan.CurrentReplyContent@@ -171,7 +193,10 @@ func (state *activeTellStreamState) checkRemoveSubtasks() []string {if len(tasksToRemove) == 0 {log.Println("No tasks to remove found")- return nil+ return checkRemoveSubtasksResult{+ hasExplicitRemoveTasks: false,+ removedSubtasks: nil,+ }}log.Println("Found tasks to remove:", len(tasksToRemove))@@ -218,5 +243,8 @@ func (state *activeTellStreamState) checkRemoveSubtasks() []string {}log.Println("removedSubtaskTitles:\n", spew.Sdump(removedSubtaskTitles))- return removedSubtaskTitles+ return checkRemoveSubtasksResult{+ hasExplicitRemoveTasks: len(tasksToRemove) > 0,+ removedSubtasks: removedSubtaskTitles,+ }}diff --git a/app/server/routes/routes.go b/app/server/routes/routes.goindex ed878597..f0ff24e4 100644--- a/app/server/routes/routes.go+++ b/app/server/routes/routes.go@@ -164,14 +164,12 @@ func addApiRoutes(r *mux.Router, prefix string) {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/{modelId}", false, handlers.DeleteCustomModelHandler).Methods("DELETE")- HandlePlandexFn(r, prefix+"/custom_models/{modelId}", false, handlers.UpdateCustomModelHandler).Methods("PUT")HandlePlandexFn(r, prefix+"/custom_models/{modelId}", false, handlers.GetCustomModelHandler).Methods("GET")HandlePlandexFn(r, prefix+"/custom_providers", false, handlers.ListCustomProvidersHandler).Methods("GET")- HandlePlandexFn(r, prefix+"/custom_providers", false, handlers.CreateCustomProviderHandler).Methods("POST")HandlePlandexFn(r, prefix+"/custom_providers/{providerId}", false, handlers.DeleteCustomProviderHandler).Methods("DELETE")- HandlePlandexFn(r, prefix+"/custom_providers/{providerId}", false, handlers.UpdateCustomProviderHandler).Methods("PUT")HandlePlandexFn(r, prefix+"/custom_providers/{providerId}", false, handlers.GetCustomProviderHandler).Methods("GET")HandlePlandexFn(r, prefix+"/model_sets", false, handlers.ListModelPacksHandler).Methods("GET")diff --git a/app/shared/ai_models_available.go b/app/shared/ai_models_available.goindex 798b306d..b80356c1 100644--- a/app/shared/ai_models_available.go+++ b/app/shared/ai_models_available.go@@ -57,7 +57,7 @@ var BuiltInModels = []*BaseModelConfigSchema{MaxTokens: 200000,MaxOutputTokens: 100000,ReservedOutputTokens: 40000, // 25k for reasoning, 15k for output- ModelCompatibility: fullCompatibility,+ ModelCompatibility: FullCompatibility,PreferredOutputFormat: ModelOutputFormatXml,SystemPromptDisabled: true,RoleParamsDisabled: true,@@ -118,7 +118,7 @@ var BuiltInModels = []*BaseModelConfigSchema{MaxTokens: 200000,MaxOutputTokens: 100000,ReservedOutputTokens: 40000, // 25k for reasoning, 15k for output- ModelCompatibility: fullCompatibility,+ ModelCompatibility: FullCompatibility,PreferredOutputFormat: ModelOutputFormatToolCallJson,SystemPromptDisabled: true,RoleParamsDisabled: true,@@ -183,7 +183,7 @@ var BuiltInModels = []*BaseModelConfigSchema{MaxTokens: 1047576,MaxOutputTokens: 32768,ReservedOutputTokens: 32768,- ModelCompatibility: fullCompatibility,+ ModelCompatibility: FullCompatibility,PreferredOutputFormat: ModelOutputFormatToolCallJson,},@@ -213,7 +213,7 @@ var BuiltInModels = []*BaseModelConfigSchema{MaxTokens: 1047576,MaxOutputTokens: 32768,ReservedOutputTokens: 32768,- ModelCompatibility: fullCompatibility,+ ModelCompatibility: FullCompatibility,PreferredOutputFormat: ModelOutputFormatToolCallJson,},@@ -243,7 +243,7 @@ var BuiltInModels = []*BaseModelConfigSchema{MaxTokens: 1047576,MaxOutputTokens: 32768,ReservedOutputTokens: 32768,- ModelCompatibility: fullCompatibility,+ ModelCompatibility: FullCompatibility,PreferredOutputFormat: ModelOutputFormatToolCallJson,},@@ -273,7 +273,7 @@ var BuiltInModels = []*BaseModelConfigSchema{MaxTokens: 200000,MaxOutputTokens: 100000,ReservedOutputTokens: 40000, // 25k for reasoning, 15k for output- ModelCompatibility: fullCompatibility,+ ModelCompatibility: FullCompatibility,PreferredOutputFormat: ModelOutputFormatToolCallJson,SystemPromptDisabled: true,RoleParamsDisabled: true,diff --git a/app/shared/ai_models_compatibility.go b/app/shared/ai_models_compatibility.goindex e2bd83f0..dff0bf96 100644--- a/app/shared/ai_models_compatibility.go+++ b/app/shared/ai_models_compatibility.go@@ -1,6 +1,6 @@package shared-var fullCompatibility = ModelCompatibility{+var FullCompatibility = ModelCompatibility{HasImageSupport: true,}diff --git a/app/shared/ai_models_custom.go b/app/shared/ai_models_custom.goindex fd2f80ff..03c9b39d 100644--- a/app/shared/ai_models_custom.go+++ b/app/shared/ai_models_custom.go@@ -2,8 +2,12 @@ package sharedimport "time"+type SchemaUrl string++const SchemaUrlInputConfig SchemaUrl = "https://plandex.ai/schemas/models-input.schema.json"+type CustomModel struct {- Id string `json:"id"`+ Id string `json:"id,omitempty"`ModelId ModelId `json:"modelId"`Publisher ModelPublisher `json:"publisher"`Description string `json:"description"`@@ -12,12 +16,12 @@ type CustomModel struct {Providers []BaseModelUsesProvider `json:"providers"`- CreatedAt time.Time `json:"createdAt"`- UpdatedAt time.Time `json:"updatedAt"`+ CreatedAt *time.Time `json:"createdAt,omitempty"`+ UpdatedAt *time.Time `json:"updatedAt,omitempty"`}type CustomProvider struct {- Id string `json:"id"`+ Id string `json:"id,omitempty"`Name string `json:"name"`BaseUrl string `json:"baseUrl"`@@ -29,4 +33,14 @@ type CustomProvider struct {ApiKeyEnvVar string `json:"apiKeyEnvVar,omitempty"`ExtraAuthVars []ModelProviderExtraAuthVars `json:"extraAuthVars,omitempty"`++ CreatedAt *time.Time `json:"createdAt,omitempty"`+ UpdatedAt *time.Time `json:"updatedAt,omitempty"`+}++type ModelsInput struct {+ SchemaUrl SchemaUrl `json:"schemaUrl"`+ CustomModels []CustomModel `json:"customModels"`+ CustomProviders []CustomProvider `json:"customProviders"`+ CustomModelPacks []ModelPackSchema `json:"customModelPacks"`}diff --git a/app/shared/ai_models_data_models.go b/app/shared/ai_models_data_models.goindex f6e03d31..4828b1e5 100644--- a/app/shared/ai_models_data_models.go+++ b/app/shared/ai_models_data_models.go@@ -31,20 +31,20 @@ type BaseModelShared struct {MaxOutputTokens int `json:"maxOutputTokens"`ReservedOutputTokens int `json:"reservedOutputTokens"`PreferredOutputFormat ModelOutputFormat `json:"preferredOutputFormat"`- SystemPromptDisabled bool `json:"systemPromptDisabled"`- RoleParamsDisabled bool `json:"roleParamsDisabled"`- StopDisabled bool `json:"stopDisabled"`- PredictedOutputEnabled bool `json:"predictedOutputEnabled"`- ReasoningEffortEnabled bool `json:"reasoningEffortEnabled"`- ReasoningEffort ReasoningEffort `json:"reasoningEffort"`- IncludeReasoning bool `json:"includeReasoning"`- ReasoningBudget int `json:"reasoningBudget"`- SupportsCacheControl bool `json:"supportsCacheControl"`+ SystemPromptDisabled bool `json:"systemPromptDisabled,omitempty"`+ RoleParamsDisabled bool `json:"roleParamsDisabled,omitempty"`+ StopDisabled bool `json:"stopDisabled,omitempty"`+ PredictedOutputEnabled bool `json:"predictedOutputEnabled,omitempty"`+ ReasoningEffortEnabled bool `json:"reasoningEffortEnabled,omitempty"`+ ReasoningEffort ReasoningEffort `json:"reasoningEffort,omitempty"`+ IncludeReasoning bool `json:"includeReasoning,omitempty"`+ ReasoningBudget int `json:"reasoningBudget,omitempty"`+ SupportsCacheControl bool `json:"supportsCacheControl,omitempty"`// for anthropic, single message system prompt needs to be flipped to 'user'- SingleMessageNoSystemPrompt bool `json:"singleMessageNoSystemPrompt"`+ SingleMessageNoSystemPrompt bool `json:"singleMessageNoSystemPrompt,omitempty"`// for anthropic, token estimate padding percentage- TokenEstimatePaddingPct float64 `json:"tokenEstimatePaddingPct"`+ TokenEstimatePaddingPct float64 `json:"tokenEstimatePaddingPct,omitempty"`ModelCompatibility}@@ -281,49 +281,73 @@ type ModelRoleModelConfig struct {}type ModelRoleConfigSchema struct {- Role ModelRole `json:"role"`- ModelId ModelId `json:"modelId"`+ ModelId ModelId `json:"modelId"`- Temperature float32 `json:"temperature"`- TopP float32 `json:"topP"`- ReservedOutputTokens int `json:"reservedOutputTokens"`- MaxConvoTokens int `json:"maxConvoTokens"`+ Temperature float32 `json:"temperature,omitempty"`+ TopP float32 `json:"topP,omitempty"`+ ReservedOutputTokens int `json:"reservedOutputTokens,omitempty"`+ MaxConvoTokens int `json:"maxConvoTokens,omitempty"`- LargeContextFallback *ModelRoleConfigSchema `json:"largeContextFallback"`- LargeOutputFallback *ModelRoleConfigSchema `json:"largeOutputFallback"`- ErrorFallback *ModelRoleConfigSchema `json:"errorFallback"`- StrongModel *ModelRoleConfigSchema `json:"strongModel"`+ LargeContextFallback *ModelRoleConfigSchema `json:"largeContextFallback,omitempty"`+ LargeOutputFallback *ModelRoleConfigSchema `json:"largeOutputFallback,omitempty"`+ ErrorFallback *ModelRoleConfigSchema `json:"errorFallback,omitempty"`+ StrongModel *ModelRoleConfigSchema `json:"strongModel,omitempty"`}-func (m *ModelRoleConfigSchema) ToModelRoleConfig() ModelRoleConfig {+func (m *ModelRoleConfigSchema) AllModelIds() []ModelId {+ ids := []ModelId{}- return m.toModelRoleConfig()+ if m.ModelId != "" {+ ids = append(ids, m.ModelId)+ }++ if m.LargeContextFallback != nil {+ ids = append(ids, m.LargeContextFallback.AllModelIds()...)+ }++ if m.LargeOutputFallback != nil {+ ids = append(ids, m.LargeOutputFallback.AllModelIds()...)+ }++ if m.ErrorFallback != nil {+ ids = append(ids, m.ErrorFallback.AllModelIds()...)+ }++ if m.StrongModel != nil {+ ids = append(ids, m.StrongModel.AllModelIds()...)+ }++ return ids+}++func (m *ModelRoleConfigSchema) ToModelRoleConfig(role ModelRole) ModelRoleConfig {+ return m.toModelRoleConfig(role)}-func (m *ModelRoleConfigSchema) toModelRoleConfig() ModelRoleConfig {+func (m *ModelRoleConfigSchema) toModelRoleConfig(role ModelRole) ModelRoleConfig {var largeContextFallback *ModelRoleConfigif m.LargeContextFallback != nil {- c := m.LargeContextFallback.ToModelRoleConfig()+ c := m.LargeContextFallback.ToModelRoleConfig(role)largeContextFallback = &c}var largeOutputFallback *ModelRoleConfigif m.LargeOutputFallback != nil {- c := m.LargeOutputFallback.ToModelRoleConfig()+ c := m.LargeOutputFallback.ToModelRoleConfig(role)largeOutputFallback = &c}var errorFallback *ModelRoleConfigif m.ErrorFallback != nil {- c := m.ErrorFallback.ToModelRoleConfig()+ c := m.ErrorFallback.ToModelRoleConfig(role)errorFallback = &c}var strongModel *ModelRoleConfigif m.StrongModel != nil {- c := m.StrongModel.ToModelRoleConfig()+ c := m.StrongModel.ToModelRoleConfig(role)strongModel = &c}return ModelRoleConfig{- Role: m.Role,+ Role: role,ModelId: m.ModelId,@@ -456,6 +480,33 @@ type ModelPackSchema struct {Architect *ModelRoleConfigSchema `json:"contextLoader"`}+func (m *ModelPackSchema) AllModelIds() []ModelId {+ ids := []ModelId{}++ ids = append(ids, m.Planner.AllModelIds()...)++ if m.Coder != nil {+ ids = append(ids, m.Coder.AllModelIds()...)+ }++ ids = append(ids, m.PlanSummary.AllModelIds()...)+ ids = append(ids, m.Builder.AllModelIds()...)++ if m.WholeFileBuilder != nil {+ ids = append(ids, m.WholeFileBuilder.AllModelIds()...)+ }++ ids = append(ids, m.Namer.AllModelIds()...)+ ids = append(ids, m.CommitMsg.AllModelIds()...)+ ids = append(ids, m.ExecStatus.AllModelIds()...)++ if m.Architect != nil {+ ids = append(ids, m.Architect.AllModelIds()...)+ }++ return ids+}+func (m *ModelPackSchema) ToModelPack() ModelPack {var (coder *ModelRoleConfig@@ -464,17 +515,17 @@ func (m *ModelPackSchema) ToModelPack() ModelPack {)if m.Coder != nil {- c := m.Coder.ToModelRoleConfig()+ c := m.Coder.ToModelRoleConfig(ModelRoleCoder)coder = &c}if m.WholeFileBuilder != nil {- c := m.WholeFileBuilder.ToModelRoleConfig()+ c := m.WholeFileBuilder.ToModelRoleConfig(ModelRoleBuilder)wholeFileBuilder = &c}if m.Architect != nil {- c := m.Architect.ToModelRoleConfig()+ c := m.Architect.ToModelRoleConfig(ModelRoleArchitect)architect = &c}@@ -482,18 +533,18 @@ func (m *ModelPackSchema) ToModelPack() ModelPack {Name: m.Name,Description: m.Description,Planner: PlannerRoleConfig{- ModelRoleConfig: m.Planner.ToModelRoleConfig(),+ ModelRoleConfig: m.Planner.ToModelRoleConfig(ModelRolePlanner),PlannerModelConfig: PlannerModelConfig{MaxConvoTokens: m.Planner.MaxConvoTokens,},},Coder: coder,- PlanSummary: m.PlanSummary.ToModelRoleConfig(),- Builder: m.Builder.ToModelRoleConfig(),+ PlanSummary: m.PlanSummary.ToModelRoleConfig(ModelRolePlanner),+ Builder: m.Builder.ToModelRoleConfig(ModelRoleBuilder),WholeFileBuilder: wholeFileBuilder,- Namer: m.Namer.ToModelRoleConfig(),- CommitMsg: m.CommitMsg.ToModelRoleConfig(),- ExecStatus: m.ExecStatus.ToModelRoleConfig(),+ Namer: m.Namer.ToModelRoleConfig(ModelRoleName),+ CommitMsg: m.CommitMsg.ToModelRoleConfig(ModelRoleCommitMsg),+ ExecStatus: m.ExecStatus.ToModelRoleConfig(ModelRoleExecStatus),Architect: architect,}}diff --git a/app/shared/ai_models_packs.go b/app/shared/ai_models_packs.goindex 97bb1740..4c14dd65 100644--- a/app/shared/ai_models_packs.go+++ b/app/shared/ai_models_packs.go@@ -35,7 +35,6 @@ var DefaultModelPack *ModelPack = &DailyDriverModelPackfunc getModelRoleConfig(role ModelRole, modelId ModelId, fns ...func(*ModelRoleConfigSchema)) ModelRoleConfigSchema {c := ModelRoleConfigSchema{- Role: role,ModelId: modelId,Temperature: DefaultConfigByRole[role].Temperature,TopP: DefaultConfigByRole[role].TopP,@@ -46,9 +45,9 @@ func getModelRoleConfig(role ModelRole, modelId ModelId, fns ...func(*ModelRoleCreturn c}-func getLargeContextFallback(modelId ModelId, fns ...func(*ModelRoleConfigSchema)) func(*ModelRoleConfigSchema) {+func getLargeContextFallback(role ModelRole, modelId ModelId, fns ...func(*ModelRoleConfigSchema)) func(*ModelRoleConfigSchema) {return func(c *ModelRoleConfigSchema) {- n := getModelRoleConfig(c.Role, modelId)+ n := getModelRoleConfig(role, modelId)for _, f := range fns {f(&n)}@@ -56,9 +55,9 @@ func getLargeContextFallback(modelId ModelId, fns ...func(*ModelRoleConfigSchema}}-func getErrorFallback(modelId ModelId, fns ...func(*ModelRoleConfigSchema)) func(*ModelRoleConfigSchema) {+func getErrorFallback(role ModelRole, modelId ModelId, fns ...func(*ModelRoleConfigSchema)) func(*ModelRoleConfigSchema) {return func(c *ModelRoleConfigSchema) {- n := getModelRoleConfig(c.Role, modelId)+ n := getModelRoleConfig(role, modelId)for _, f := range fns {f(&n)}@@ -66,9 +65,9 @@ func getErrorFallback(modelId ModelId, fns ...func(*ModelRoleConfigSchema)) func}}-func getStrongModelFallback(modelId ModelId, fns ...func(*ModelRoleConfigSchema)) func(*ModelRoleConfigSchema) {+func getStrongModelFallback(role ModelRole, modelId ModelId, fns ...func(*ModelRoleConfigSchema)) func(*ModelRoleConfigSchema) {return func(c *ModelRoleConfigSchema) {- n := getModelRoleConfig(c.Role, modelId)+ n := getModelRoleConfig(role, modelId)for _, f := range fns {f(&n)}@@ -107,24 +106,24 @@ var BuiltInModelPackSchemas = []*ModelPackSchema{func init() {defaultBuilder := getModelRoleConfig(ModelRoleBuilder, "openai/o4-mini-medium",- getStrongModelFallback("openai/o4-mini-high"),+ getStrongModelFallback(ModelRoleBuilder, "openai/o4-mini-high"),)DailyDriverPackSchema = ModelPackSchema{Name: "daily-driver",Description: "A mix of models from Anthropic, OpenAI, and Google that balances speed, quality, and cost. Supports up to 2M context.",Planner: getModelRoleConfig(ModelRolePlanner, "anthropic/claude-3.7-sonnet",- getLargeContextFallback("google/gemini-2.5-pro-preview",- getLargeContextFallback("google/gemini-pro-1.5"),+ getLargeContextFallback(ModelRolePlanner, "google/gemini-2.5-pro-preview",+ getLargeContextFallback(ModelRolePlanner, "google/gemini-pro-1.5"),),),Architect: Pointer(getModelRoleConfig(ModelRoleArchitect, "anthropic/claude-3.7-sonnet",- getLargeContextFallback("google/gemini-2.5-pro-preview",- getLargeContextFallback("google/gemini-pro-1.5"),+ getLargeContextFallback(ModelRoleArchitect, "google/gemini-2.5-pro-preview",+ getLargeContextFallback(ModelRoleArchitect, "google/gemini-pro-1.5"),),)),Coder: Pointer(getModelRoleConfig(ModelRoleCoder, "anthropic/claude-3.7-sonnet",- getLargeContextFallback("openai/gpt-4.1"),+ getLargeContextFallback(ModelRoleCoder, "openai/gpt-4.1"),)),PlanSummary: getModelRoleConfig(ModelRolePlanSummary, "openai/o4-mini-low"),Builder: defaultBuilder,@@ -135,18 +134,16 @@ func init() {}ReasoningPackSchema = ModelPackSchema{- Name: "reasoning",- Description: "Like the daily driver, but uses 3.7-sonnet:thinking with reasoning enabled for planning and coding. Supports up to 160k input context.",- Planner: getModelRoleConfig(ModelRolePlanner, "anthropic/claude-3.7-sonnet-thinking-hidden"),- Coder: Pointer(getModelRoleConfig(ModelRoleCoder, "anthropic/claude-3.7-sonnet-thinking-hidden")),- PlanSummary: getModelRoleConfig(ModelRolePlanSummary, "openai/o4-mini-low", getErrorFallback("openai/o3-mini-low")),- Builder: defaultBuilder,- WholeFileBuilder: Pointer(getModelRoleConfig(ModelRoleWholeFileBuilder, "openai/o4-mini-medium",- getErrorFallback("openai/o3-mini-medium"),- )),- Namer: getModelRoleConfig(ModelRoleName, "openai/gpt-4.1-mini"),- CommitMsg: getModelRoleConfig(ModelRoleCommitMsg, "openai/gpt-4.1-mini"),- ExecStatus: getModelRoleConfig(ModelRoleExecStatus, "openai/o4-mini-low", getErrorFallback("openai/o3-mini-low")),+ Name: "reasoning",+ Description: "Like the daily driver, but uses 3.7-sonnet:thinking with reasoning enabled for planning and coding. Supports up to 160k input context.",+ Planner: getModelRoleConfig(ModelRolePlanner, "anthropic/claude-3.7-sonnet-thinking-hidden"),+ Coder: Pointer(getModelRoleConfig(ModelRoleCoder, "anthropic/claude-3.7-sonnet-thinking-hidden")),+ PlanSummary: getModelRoleConfig(ModelRolePlanSummary, "openai/o4-mini-low"),+ Builder: defaultBuilder,+ WholeFileBuilder: Pointer(getModelRoleConfig(ModelRoleWholeFileBuilder, "openai/o4-mini-medium")),+ Namer: getModelRoleConfig(ModelRoleName, "openai/gpt-4.1-mini"),+ CommitMsg: getModelRoleConfig(ModelRoleCommitMsg, "openai/gpt-4.1-mini"),+ ExecStatus: getModelRoleConfig(ModelRoleExecStatus, "openai/o4-mini-low"),}StrongPackSchema = ModelPackSchema{@@ -155,25 +152,25 @@ func init() {Planner: getModelRoleConfig(ModelRolePlanner, "openai/o3-high"),Architect: Pointer(getModelRoleConfig(ModelRoleArchitect, "openai/o3-high")),Coder: Pointer(getModelRoleConfig(ModelRoleCoder, "anthropic/claude-3.7-sonnet-thinking-hidden")),- PlanSummary: getModelRoleConfig(ModelRolePlanSummary, "openai/o4-mini-low", getErrorFallback("openai/o3-mini-low")),- Builder: getModelRoleConfig(ModelRoleBuilder, "openai/o4-mini-high", getErrorFallback("openai/o3-mini-high")),- WholeFileBuilder: Pointer(getModelRoleConfig(ModelRoleWholeFileBuilder, "openai/o4-mini-high", getErrorFallback("openai/o3-mini-high"))),+ PlanSummary: getModelRoleConfig(ModelRolePlanSummary, "openai/o4-mini-low"),+ Builder: getModelRoleConfig(ModelRoleBuilder, "openai/o4-mini-high"),+ WholeFileBuilder: Pointer(getModelRoleConfig(ModelRoleWholeFileBuilder, "openai/o4-mini-high")),Namer: getModelRoleConfig(ModelRoleName, "openai/gpt-4.1-mini"),CommitMsg: getModelRoleConfig(ModelRoleCommitMsg, "openai/gpt-4.1-mini"),- ExecStatus: getModelRoleConfig(ModelRoleExecStatus, "openai/o4-mini-medium", getErrorFallback("openai/o3-mini-medium")),+ ExecStatus: getModelRoleConfig(ModelRoleExecStatus, "openai/o4-mini-medium"),}CheapModelPackSchema = ModelPackSchema{Name: "cheap",Description: "Cost-effective models that can still get the job done for easier tasks. Supports up to 160k context. Uses OpenAI's o4-mini model for planning, GPT-4.1 for coding, and GPT-4.1 Mini for lighter tasks.",- Planner: getModelRoleConfig(ModelRolePlanner, "openai/o4-mini-medium", getErrorFallback("openai/o3-mini-medium")),+ Planner: getModelRoleConfig(ModelRolePlanner, "openai/o4-mini-medium"),Coder: Pointer(getModelRoleConfig(ModelRoleCoder, "openai/gpt-4.1")),PlanSummary: getModelRoleConfig(ModelRolePlanSummary, "openai/gpt-4.1-mini"),- Builder: getModelRoleConfig(ModelRoleBuilder, "openai/o4-mini-low", getStrongModelFallback("openai/o4-mini-medium"), getErrorFallback("openai/o3-mini-low")),- WholeFileBuilder: Pointer(getModelRoleConfig(ModelRoleWholeFileBuilder, "openai/o4-mini-low", getErrorFallback("openai/o3-mini-low"))),+ Builder: getModelRoleConfig(ModelRoleBuilder, "openai/o4-mini-low"),+ WholeFileBuilder: Pointer(getModelRoleConfig(ModelRoleWholeFileBuilder, "openai/o4-mini-low")),Namer: getModelRoleConfig(ModelRoleName, "openai/gpt-4.1-mini"),CommitMsg: getModelRoleConfig(ModelRoleCommitMsg, "openai/gpt-4.1-mini"),- ExecStatus: getModelRoleConfig(ModelRoleExecStatus, "openai/o4-mini-low", getErrorFallback("openai/o3-mini-low")),+ ExecStatus: getModelRoleConfig(ModelRoleExecStatus, "openai/o4-mini-low"),}OSSModelPackSchema = ModelPackSchema{@@ -193,12 +190,12 @@ func init() {Name: "openai",Description: "OpenAI blend. Supports up to 1M context. Uses OpenAI's GPT-4.1 model for heavy lifting, GPT-4.1 Mini for lighter tasks.",Planner: getModelRoleConfig(ModelRolePlanner, "openai/gpt-4.1"),- PlanSummary: getModelRoleConfig(ModelRolePlanSummary, "openai/o4-mini-low", getErrorFallback("openai/o3-mini-low")),+ PlanSummary: getModelRoleConfig(ModelRolePlanSummary, "openai/o4-mini-low"),Builder: defaultBuilder,- WholeFileBuilder: Pointer(getModelRoleConfig(ModelRoleWholeFileBuilder, "openai/o4-mini-medium", getErrorFallback("openai/o3-mini-medium"))),+ WholeFileBuilder: Pointer(getModelRoleConfig(ModelRoleWholeFileBuilder, "openai/o4-mini-medium")),Namer: getModelRoleConfig(ModelRoleName, "openai/gpt-4.1-mini"),CommitMsg: getModelRoleConfig(ModelRoleCommitMsg, "openai/gpt-4.1-mini"),- ExecStatus: getModelRoleConfig(ModelRoleExecStatus, "openai/o4-mini-low", getErrorFallback("openai/o3-mini-low")),+ ExecStatus: getModelRoleConfig(ModelRoleExecStatus, "openai/o4-mini-low"),}AnthropicPackSchema = ModelPackSchema{@@ -219,12 +216,12 @@ func init() {Description: "Uses Gemini 2.5 Pro Preview for planning and coding, default models for other roles. Supports up to 1M input context.",Planner: getModelRoleConfig(ModelRolePlanner, "google/gemini-2.5-pro-preview"),Coder: Pointer(getModelRoleConfig(ModelRoleCoder, "google/gemini-2.5-pro-preview")),- PlanSummary: getModelRoleConfig(ModelRolePlanSummary, "openai/o4-mini-low", getErrorFallback("openai/o3-mini-low")),+ PlanSummary: getModelRoleConfig(ModelRolePlanSummary, "openai/o4-mini-low"),Builder: defaultBuilder,- WholeFileBuilder: Pointer(getModelRoleConfig(ModelRoleWholeFileBuilder, "openai/o4-mini-medium", getErrorFallback("openai/o3-mini-medium"))),+ WholeFileBuilder: Pointer(getModelRoleConfig(ModelRoleWholeFileBuilder, "openai/o4-mini-medium")),Namer: getModelRoleConfig(ModelRoleName, "openai/gpt-4.1-mini"),CommitMsg: getModelRoleConfig(ModelRoleCommitMsg, "openai/gpt-4.1-mini"),- ExecStatus: getModelRoleConfig(ModelRoleExecStatus, "openai/o4-mini-low", getErrorFallback("openai/o3-mini-low")),+ ExecStatus: getModelRoleConfig(ModelRoleExecStatus, "openai/o4-mini-low"),}GeminiExperimentalPackSchema = ModelPackSchema{@@ -232,12 +229,12 @@ func init() {Description: "Uses Gemini 2.5 Pro Experimental (free) for planning and coding, default models for other roles. Supports up to 1M input context.",Planner: getModelRoleConfig(ModelRolePlanner, "google/gemini-2.5-pro-exp"),Coder: Pointer(getModelRoleConfig(ModelRoleCoder, "google/gemini-2.5-pro-exp")),- PlanSummary: getModelRoleConfig(ModelRolePlanSummary, "openai/o4-mini-low", getErrorFallback("openai/o3-mini-low")),+ PlanSummary: getModelRoleConfig(ModelRolePlanSummary, "openai/o4-mini-low"),Builder: defaultBuilder,- WholeFileBuilder: Pointer(getModelRoleConfig(ModelRoleWholeFileBuilder, "openai/o4-mini-medium", getErrorFallback("openai/o3-mini-medium"))),+ WholeFileBuilder: Pointer(getModelRoleConfig(ModelRoleWholeFileBuilder, "openai/o4-mini-medium")),Namer: getModelRoleConfig(ModelRoleName, "openai/gpt-4.1-mini"),CommitMsg: getModelRoleConfig(ModelRoleCommitMsg, "openai/gpt-4.1-mini"),- ExecStatus: getModelRoleConfig(ModelRoleExecStatus, "openai/o4-mini-low", getErrorFallback("openai/o3-mini-low")),+ ExecStatus: getModelRoleConfig(ModelRoleExecStatus, "openai/o4-mini-low"),}R1PlannerPackSchema = ModelPackSchema{@@ -245,12 +242,12 @@ func init() {Description: "Uses DeepSeek R1 for planning, Qwen for light tasks, and default models for implementation. Supports up to 56k input context.",Planner: getModelRoleConfig(ModelRolePlanner, "deepseek/r1-reasoning-visible"),Coder: Pointer(getModelRoleConfig(ModelRoleCoder, "anthropic/claude-3.7-sonnet")),- PlanSummary: getModelRoleConfig(ModelRolePlanSummary, "openai/o4-mini-low", getErrorFallback("openai/o3-mini-low")),- Builder: getModelRoleConfig(ModelRoleBuilder, "openai/o4-mini-medium", getErrorFallback("openai/o3-mini-medium")),- WholeFileBuilder: Pointer(getModelRoleConfig(ModelRoleWholeFileBuilder, "openai/o4-mini-low", getErrorFallback("openai/o3-mini-low"))),+ PlanSummary: getModelRoleConfig(ModelRolePlanSummary, "openai/o4-mini-low"),+ Builder: getModelRoleConfig(ModelRoleBuilder, "openai/o4-mini-medium"),+ WholeFileBuilder: Pointer(getModelRoleConfig(ModelRoleWholeFileBuilder, "openai/o4-mini-low")),Namer: getModelRoleConfig(ModelRoleName, "openai/gpt-4.1-mini"),CommitMsg: getModelRoleConfig(ModelRoleCommitMsg, "openai/gpt-4.1-mini"),- ExecStatus: getModelRoleConfig(ModelRoleExecStatus, "openai/o4-mini-medium", getErrorFallback("openai/o3-mini-medium")),+ ExecStatus: getModelRoleConfig(ModelRoleExecStatus, "openai/o4-mini-medium"),}PerplexityPlannerPackSchema = ModelPackSchema{@@ -258,12 +255,12 @@ func init() {Description: "Uses Perplexity Sonar for planning, Qwen for light tasks, and default models for implementation. Supports up to 97k input context.",Planner: getModelRoleConfig(ModelRolePlanner, "perplexity/sonar-reasoning-visible"),Coder: Pointer(getModelRoleConfig(ModelRoleCoder, "anthropic/claude-3.7-sonnet")),- PlanSummary: getModelRoleConfig(ModelRolePlanSummary, "openai/o4-mini-low", getErrorFallback("openai/o3-mini-low")),- Builder: getModelRoleConfig(ModelRoleBuilder, "openai/o4-mini-medium", getErrorFallback("openai/o3-mini-medium")),- WholeFileBuilder: Pointer(getModelRoleConfig(ModelRoleWholeFileBuilder, "openai/o4-mini-low", getErrorFallback("openai/o3-mini-low"))),+ PlanSummary: getModelRoleConfig(ModelRolePlanSummary, "openai/o4-mini-low"),+ Builder: getModelRoleConfig(ModelRoleBuilder, "openai/o4-mini-medium"),+ WholeFileBuilder: Pointer(getModelRoleConfig(ModelRoleWholeFileBuilder, "openai/o4-mini-low")),Namer: getModelRoleConfig(ModelRoleName, "openai/gpt-4.1-mini"),CommitMsg: getModelRoleConfig(ModelRoleCommitMsg, "openai/gpt-4.1-mini"),- ExecStatus: getModelRoleConfig(ModelRoleExecStatus, "openai/o4-mini-medium", getErrorFallback("openai/o3-mini-medium")),+ ExecStatus: getModelRoleConfig(ModelRoleExecStatus, "openai/o4-mini-medium"),}DailyDriverModelPack = DailyDriverPackSchema.ToModelPack()