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
Enhance server stability, error handling, and add API endpoints
Dane Schneidereedaf01c2c61
diff --git a/app/server/db/locks.go b/app/server/db/locks.goindex 6bb64211..4c5289b3 100644--- a/app/server/db/locks.go+++ b/app/server/db/locks.go@@ -25,7 +25,7 @@ const locksVerboseLogging = falseconst lockHeartbeatInterval = 3 * time.Secondconst lockHeartbeatTimeout = 60 * time.Secondconst maxLockRetries = 6-const initialLockRetryDelay = 100 * time.Millisecond+const initialLockRetryDelay = 300 * time.Millisecondconst backoffFactor = 2 // Exponential baseconst jitterFraction = 0.3 // e.g. ±30% of the backoffdiff --git a/app/server/db/models.go b/app/server/db/models.goindex 03072fbd..2144456c 100644--- a/app/server/db/models.go+++ b/app/server/db/models.go@@ -16,6 +16,16 @@ func CreateCustomModel(model *AvailableModel) error {return nil}+func UpdateCustomModel(model *AvailableModel) error {+ query := `UPDATE custom_models SET provider = $2, custom_provider = $3, base_url = $4, model_name = $5, model_id = $6, description = $7, max_tokens = $8, api_key_env_var = $9, default_max_convo_tokens = $10, max_output_tokens = $11, reserved_output_tokens = $12, preferred_output_format = $13, has_image_support = $14 WHERE id = $1`+ _, err := Conn.Exec(query, model.Id, model.Provider, model.CustomProvider, model.BaseUrl, model.ModelName, model.ModelId, model.Description, model.MaxTokens, model.ApiKeyEnvVar, model.DefaultMaxConvoTokens, model.MaxOutputTokens, model.ReservedOutputTokens, model.PreferredOutputFormat, model.HasImageSupport)+ if err != nil {+ return fmt.Errorf("error updating custom model: %v", err)+ }++ return nil+}+func ListCustomModels(orgId string) ([]*AvailableModel, error) {var models []*AvailableModel@@ -42,10 +52,10 @@ func DeleteAvailableModel(modelId string) error {}func CreateModelPack(ms *ModelPack) error {- query := `INSERT INTO model_sets (org_id, name, description, planner, plan_summary, builder, namer, commit_msg, exec_status, context_loader, coder) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)+ 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.PlanSummary, ms.Builder, ms.Namer, ms.CommitMsg, ms.ExecStatus, ms.Architect, ms.Coder).Scan(&ms.Id, &ms.CreatedAt)+ 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)@@ -54,6 +64,17 @@ func CreateModelPack(ms *ModelPack) error {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+}+func ListModelPacks(orgId string) ([]*ModelPack, error) {var modelPacks []*ModelPackdiff --git a/app/server/go.mod b/app/server/go.modindex 607b6823..3183f7df 100644--- a/app/server/go.mod+++ b/app/server/go.mod@@ -7,12 +7,12 @@ require (github.com/google/uuid v1.6.0github.com/gorilla/mux v1.8.1github.com/pkg/errors v0.9.1- github.com/sashabaranov/go-openai v1.36.1+ github.com/sashabaranov/go-openai v1.38.1plandex-shared v0.0.0-00010101000000-000000000000)require (- github.com/dlclark/regexp2 v1.11.4 // indirect+ github.com/dlclark/regexp2 v1.11.5 // indirectgithub.com/go-toast/toast v0.0.0-20190211030409-01e6764cf0a4 // indirectgithub.com/godbus/dbus/v5 v5.1.0 // indirectgithub.com/hashicorp/errwrap v1.1.0 // indirect@@ -29,7 +29,7 @@ require (github.com/shopspring/decimal v1.4.0 // indirectgithub.com/tadvi/systray v0.0.0-20190226123456-11a2b8fa57af // indirectgo.uber.org/atomic v1.11.0 // indirect- golang.org/x/image v0.23.0 // indirect+ golang.org/x/image v0.25.0 // indirectgolang.org/x/sys v0.29.0 // indirectgopkg.in/yaml.v3 v3.0.1 // indirect)diff --git a/app/server/go.sum b/app/server/go.sumindex dca1c3d7..925ac064 100644--- a/app/server/go.sum+++ b/app/server/go.sum@@ -15,8 +15,8 @@ github.com/dhui/dktest v0.4.4 h1:+I4s6JRE1yGuqflzwqG+aIaMdgXIorCf5P98JnaAWa8=github.com/dhui/dktest v0.4.4/go.mod h1:4+22R4lgsdAXrDyaH4Nqx2JEz2hLp49MqQmm9HLCQhM=github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk=github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E=-github.com/dlclark/regexp2 v1.11.4 h1:rPYF9/LECdNymJufQKmri9gV604RvvABwgOA8un7yAo=-github.com/dlclark/regexp2 v1.11.4/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=+github.com/dlclark/regexp2 v1.11.5 h1:Q/sSnsKerHeCkc/jSTNq1oCm7KiVgUMZRDUoRu0JQZQ=+github.com/dlclark/regexp2 v1.11.5/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=github.com/docker/docker v27.2.0+incompatible h1:Rk9nIVdfH3+Vz4cyI/uhbINhEZ/oLmc+CBXmH6fbNk4=github.com/docker/docker v27.2.0+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk=github.com/docker/go-connections v0.5.0 h1:USnMq7hx7gwdVZq1L49hLXaFtUdTADjXGp+uj1Br63c=@@ -92,8 +92,8 @@ github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNgithub.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=-github.com/sashabaranov/go-openai v1.36.1 h1:EVfRXwIlW2rUzpx6vR+aeIKCK/xylSrVYAx1TMTSX3g=-github.com/sashabaranov/go-openai v1.36.1/go.mod h1:lj5b/K+zjTSFxVLijLSTDZuP7adOgerWeFyZLUhAKRg=+github.com/sashabaranov/go-openai v1.38.1 h1:TtZabbFQZa1nEni/IhVtDF/WQjVqDgd+cWR5OeddzF8=+github.com/sashabaranov/go-openai v1.38.1/go.mod h1:lj5b/K+zjTSFxVLijLSTDZuP7adOgerWeFyZLUhAKRg=github.com/shopspring/decimal v1.4.0 h1:bxl37RwXBklmTi0C79JfXCEBD1cqqHt0bbgBAGFp81k=github.com/shopspring/decimal v1.4.0/go.mod h1:gawqmDU56v4yIKSwfBSFip1HdCCXN8/+DMd9qYNcwME=github.com/smacker/go-tree-sitter v0.0.0-20240827094217-dd81d9e9be82 h1:6C8qej6f1bStuePVkLSFxoU22XBS165D3klxlzRg8F4=@@ -113,8 +113,8 @@ go.opentelemetry.io/otel/trace v1.29.0 h1:J/8ZNK4XgR7a21DZUAsbF8pZ5Jcw1VhACmnYt3go.opentelemetry.io/otel/trace v1.29.0/go.mod h1:eHl3w0sp3paPkYstJOmAimxhiFXPg+MMTlEh3nsQgWQ=go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=-golang.org/x/image v0.23.0 h1:HseQ7c2OpPKTPVzNjG5fwJsOTCiiwS4QdsYi5XU6H68=-golang.org/x/image v0.23.0/go.mod h1:wJJBTdLfCCf3tiHa1fNxpZmUI4mmoZvwMCPP0ddoNKY=+golang.org/x/image v0.25.0 h1:Y6uW6rH1y5y/LK1J8BPWZtr6yZ7hrsy6hFrXjgsc2fQ=+golang.org/x/image v0.25.0/go.mod h1:tCAmOEGthTtkalusGp1g3xa2gke8J6c2N565dTyl9Rs=golang.org/x/net v0.34.0 h1:Mb7Mrk043xzHgnRM88suvJFwzVrRfHEHJEl5/71CKw0=golang.org/x/net v0.34.0/go.mod h1:di0qlW3YNM5oh6GqDGQr92MyTozJPmybPK4Ev/Gm31k=golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=diff --git a/app/server/handlers/models.go b/app/server/handlers/models.goindex 2694472e..5fc7c0e1 100644--- a/app/server/handlers/models.go+++ b/app/server/handlers/models.go@@ -63,6 +63,77 @@ func CreateCustomModelHandler(w http.ResponseWriter, r *http.Request) {log.Println("Successfully created custom model")}+func UpdateCustomModelHandler(w http.ResponseWriter, r *http.Request) {+ log.Println("Received request for UpdateCustomModelHandler")++ auth := Authenticate(w, r, true)+ if auth == nil {+ return+ }++ modelId := mux.Vars(r)["modelId"]++ var model shared.AvailableModel+ 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+ }++ models, err := db.ListCustomModels(auth.OrgId)+ if err != nil {+ log.Printf("Error fetching custom models: %v\n", err)+ http.Error(w, "Failed to fetch custom models: "+err.Error(), http.StatusInternalServerError)+ return+ }++ found := false+ for _, m := range models {+ if m.Id == modelId {+ found = true+ break+ }+ }++ if !found {+ http.Error(w, "Custom model not found", http.StatusNotFound)+ return+ }++ if os.Getenv("IS_CLOUD") != "" && model.Provider == shared.ModelProviderCustom {+ http.Error(w, "Custom model providers are not supported on Plandex Cloud", http.StatusBadRequest)+ return+ }++ dbModel := &db.AvailableModel{+ Id: modelId,+ OrgId: auth.OrgId,+ Provider: model.BaseModelConfig.Provider,+ CustomProvider: model.BaseModelConfig.CustomProvider,+ BaseUrl: model.BaseModelConfig.BaseUrl,+ ModelId: model.BaseModelConfig.ModelId,+ ModelName: model.BaseModelConfig.ModelName,+ Description: model.Description,+ MaxTokens: model.BaseModelConfig.MaxTokens,+ ApiKeyEnvVar: model.BaseModelConfig.ApiKeyEnvVar,+ HasImageSupport: model.BaseModelConfig.ModelCompatibility.HasImageSupport,+ DefaultMaxConvoTokens: model.DefaultMaxConvoTokens,+ MaxOutputTokens: model.BaseModelConfig.MaxOutputTokens,+ ReservedOutputTokens: model.BaseModelConfig.ReservedOutputTokens,+ PreferredOutputFormat: model.BaseModelConfig.PreferredModelOutputFormat,+ }++ 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)+ return+ }++ w.WriteHeader(http.StatusOK)++ log.Println("Successfully updated custom model")+}+func ListCustomModelsHandler(w http.ResponseWriter, r *http.Request) {log.Println("Received request for ListCustomModelsHandler")@@ -92,6 +163,27 @@ func DeleteAvailableModelHandler(w http.ResponseWriter, r *http.Request) {}modelId := mux.Vars(r)["modelId"]++ models, err := db.ListCustomModels(auth.OrgId)+ if err != nil {+ log.Printf("Error fetching custom models: %v\n", err)+ http.Error(w, "Failed to fetch custom models: "+err.Error(), http.StatusInternalServerError)+ return+ }++ found := false+ for _, m := range models {+ if m.Id == modelId {+ found = true+ break+ }+ }++ if !found {+ http.Error(w, "Custom model not found", http.StatusNotFound)+ return+ }+if err := db.DeleteAvailableModel(modelId); err != nil {log.Printf("Error deleting custom model: %v\n", err)http.Error(w, "Failed to delete custom model: "+err.Error(), http.StatusInternalServerError)@@ -118,16 +210,18 @@ func CreateModelPackHandler(w http.ResponseWriter, r *http.Request) {}dbMs := &db.ModelPack{- OrgId: auth.OrgId,- Name: ms.Name,- Description: ms.Description,- PlanSummary: ms.PlanSummary,- Builder: ms.Builder,- Namer: ms.Namer,- CommitMsg: ms.CommitMsg,- ExecStatus: ms.ExecStatus,- Architect: ms.Architect,- Coder: ms.Coder,+ 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 {@@ -141,6 +235,69 @@ func CreateModelPackHandler(w http.ResponseWriter, r *http.Request) {log.Println("Successfully created model pack")}+func UpdateModelPackHandler(w http.ResponseWriter, r *http.Request) {+ log.Println("Received request for UpdateModelPackHandler")++ auth := Authenticate(w, r, true)+ if auth == nil {+ 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")+}+func ListModelPacksHandler(w http.ResponseWriter, r *http.Request) {log.Println("Received request for ListModelPacksHandler")@@ -175,11 +332,31 @@ func DeleteModelPackHandler(w http.ResponseWriter, r *http.Request) {return}- setId := mux.Vars(r)["setId"]+ mpId := mux.Vars(r)["setId"]++ 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+ }- log.Printf("Deleting model pack with id: %s\n", setId)+ log.Printf("Deleting model pack with id: %s\n", mpId)- if err := db.DeleteModelPack(setId); err != nil {+ if err := db.DeleteModelPack(mpId); err != nil {log.Printf("Error deleting model pack: %v\n", err)http.Error(w, "Failed to delete model pack: "+err.Error(), http.StatusInternalServerError)returndiff --git a/app/server/handlers/plans_exec.go b/app/server/handlers/plans_exec.goindex 1577b0ef..df9ce117 100644--- a/app/server/handlers/plans_exec.go+++ b/app/server/handlers/plans_exec.go@@ -3,6 +3,7 @@ package handlersimport ("context""encoding/json"+ "fmt""io""log""net/http"@@ -10,6 +11,7 @@ import ("plandex-server/hooks""plandex-server/host"modelPlan "plandex-server/model/plan"+ "plandex-server/notify""plandex-server/types""time"@@ -40,6 +42,7 @@ func TellPlanHandler(w http.ResponseWriter, r *http.Request) {body, err := io.ReadAll(r.Body)if err != nil {log.Printf("Error reading request body: %v\n", err)+ go notify.NotifyErr(notify.SeverityError, fmt.Errorf("error reading request body: %v", err))http.Error(w, "Error reading request body", http.StatusInternalServerError)return}@@ -51,6 +54,7 @@ func TellPlanHandler(w http.ResponseWriter, r *http.Request) {var requestBody shared.TellPlanRequestif err := json.Unmarshal(body, &requestBody); err != nil {log.Printf("Error parsing request body: %v\n", err)+ go notify.NotifyErr(notify.SeverityError, fmt.Errorf("error parsing request body: %v", err))http.Error(w, "Error parsing request body", http.StatusBadRequest)return}@@ -60,6 +64,7 @@ func TellPlanHandler(w http.ResponseWriter, r *http.Request) {Plan: plan,})if apiErr != nil {+ go notify.NotifyErr(notify.SeverityError, fmt.Errorf("error executing will tell plan hook: %v", apiErr))writeApiError(w, *apiErr)return}@@ -80,6 +85,7 @@ func TellPlanHandler(w http.ResponseWriter, r *http.Request) {if err != nil {log.Printf("Error telling plan: %v\n", err)+ go notify.NotifyErr(notify.SeverityError, fmt.Errorf("error telling plan: %v", err))http.Error(w, "Error telling plan", http.StatusInternalServerError)return}@@ -111,6 +117,7 @@ func BuildPlanHandler(w http.ResponseWriter, r *http.Request) {body, err := io.ReadAll(r.Body)if err != nil {log.Printf("Error reading request body: %v\n", err)+ go notify.NotifyErr(notify.SeverityError, fmt.Errorf("error reading request body: %v", err))http.Error(w, "Error reading request body", http.StatusInternalServerError)return}@@ -122,6 +129,7 @@ func BuildPlanHandler(w http.ResponseWriter, r *http.Request) {var requestBody shared.BuildPlanRequestif err := json.Unmarshal(body, &requestBody); err != nil {log.Printf("Error parsing request body: %v\n", err)+ go notify.NotifyErr(notify.SeverityError, fmt.Errorf("error parsing request body: %v", err))http.Error(w, "Error parsing request body", http.StatusBadRequest)return}@@ -142,12 +150,14 @@ func BuildPlanHandler(w http.ResponseWriter, r *http.Request) {if err != nil {log.Printf("Error building plan: %v\n", err)+ go notify.NotifyErr(notify.SeverityError, fmt.Errorf("error building plan: %v", err))http.Error(w, "Error building plan", http.StatusInternalServerError)return}if numBuilds == 0 {log.Println("No builds were executed")+ go notify.NotifyErr(notify.SeverityInfo, fmt.Errorf("no builds were executed"))http.Error(w, shared.NoBuildsErr, http.StatusNotFound)return}@@ -173,6 +183,7 @@ func ConnectPlanHandler(w http.ResponseWriter, r *http.Request) {if active == nil {if isProxy {log.Println("No active plan on proxied request")+ go notify.NotifyErr(notify.SeverityInfo, fmt.Errorf("no active plan on proxied request"))http.Error(w, "No active plan", http.StatusNotFound)return}diff --git a/app/server/main.go b/app/server/main.goindex 172bea72..d44cd0ef 100644--- a/app/server/main.go+++ b/app/server/main.go@@ -13,6 +13,10 @@ func main() {// Configure the default logger to include milliseconds in timestampslog.SetFlags(log.LstdFlags | log.Lmicroseconds | log.Lshortfile)+ routes.RegisterHandlePlandex(func(router *mux.Router, path string, isStreaming bool, handler routes.PlandexHandler) *mux.Route {+ return router.HandleFunc(path, handler)+ })+r := mux.NewRouter()routes.AddHealthRoutes(r)routes.AddApiRoutes(r)diff --git a/app/server/model/client.go b/app/server/model/client.goindex 3a2f16a6..a10855de 100644--- a/app/server/model/client.go+++ b/app/server/model/client.go@@ -155,12 +155,19 @@ func createChatCompletionExtended(extendedReq types.ExtendedChatCompletionRequest,) (openai.ChatCompletionResponse, error) {var openaiReq *types.ExtendedOpenAIChatCompletionRequest- if modelConfig.BaseModelConfig.Provider == shared.ModelProviderOpenAI {+ if modelConfig.BaseModelConfig.Provider == shared.ModelProviderOpenAI && !modelConfig.BaseModelConfig.UsesOpenAIResponsesAPI {log.Println("Creating chat completion with direct OpenAI provider request")openaiReq = extendedReq.ToOpenAI()}- req, err := http.NewRequestWithContext(ctx, "POST", baseUrl+"/chat/completions", nil)+ var url string+ if modelConfig.BaseModelConfig.UsesOpenAIResponsesAPI {+ url = baseUrl + "/responses"+ } else {+ url = baseUrl + "/chat/completions"+ }++ req, err := http.NewRequestWithContext(ctx, "POST", url, nil)if err != nil {return openai.ChatCompletionResponse{}, err}@@ -216,7 +223,7 @@ func createChatCompletionStreamExtended(extendedReq types.ExtendedChatCompletionRequest,) (*ExtendedChatCompletionStream, error) {var openaiReq *types.ExtendedOpenAIChatCompletionRequest- if modelConfig.BaseModelConfig.Provider == shared.ModelProviderOpenAI {+ if modelConfig.BaseModelConfig.Provider == shared.ModelProviderOpenAI && !modelConfig.BaseModelConfig.UsesOpenAIResponsesAPI {openaiReq = extendedReq.ToOpenAI()log.Println("Creating chat completion stream with direct OpenAI provider request")}@@ -236,7 +243,14 @@ func createChatCompletionStreamExtended(// log.Println("request jsonBody", string(jsonBody))// Create new request- req, err := http.NewRequestWithContext(ctx, "POST", baseUrl+"/chat/completions", bytes.NewReader(jsonBody))+ var url string+ if modelConfig.BaseModelConfig.UsesOpenAIResponsesAPI {+ url = baseUrl + "/responses"+ } else {+ url = baseUrl + "/chat/completions"+ }++ req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(jsonBody))if err != nil {return nil, fmt.Errorf("error creating request: %w", err)}@@ -457,6 +471,53 @@ func resolveReq(req *types.ExtendedChatCompletionRequest, modelConfig *shared.Mo}}+ // this isn't working yet+ // if modelConfig.BaseModelConfig.UsesOpenAIResponsesAPI {+ // log.Println("Using OpenAI Responses API")+ // input := make([]types.ExtendedChatMessage, 0)++ // for _, msg := range req.Messages {+ // // isDevRole := false+ // isAssistantRole := false+ // if msg.Role == openai.ChatMessageRoleSystem {+ // log.Println("Changing role of system message to 'developer'")+ // msg.Role = openai.ChatMessageRoleDeveloper+ // // isDevRole = true+ // } else if msg.Role == openai.ChatMessageRoleAssistant {+ // isAssistantRole = true+ // }++ // for j, part := range msg.Content {+ // if part.Type == "text" {+ // if isAssistantRole {+ // part.Type = "output_text"+ // } else {+ // part.Type = "input_text"+ // }+ // }++ // msg.Content[j] = part+ // }++ // input = append(input, msg)+ // }++ // // stop is not supported for the responses API+ // if req.Stop != nil {+ // req.Stop = nil+ // }++ // if req.StreamOptions != nil {+ // req.StreamOptions = nil+ // }++ // req.Input = input+ // req.Messages = nil++ // log.Println("req.Input", len(req.Input))+ // log.Println("req.Messages", len(req.Messages))+ // }+if modelConfig.BaseModelConfig.RoleParamsDisabled {log.Println("Role params disabled - setting temperature and top p to 1")req.Temperature = 1diff --git a/app/server/model/plan/build_exec.go b/app/server/model/plan/build_exec.goindex 0c404028..6a0cab61 100644--- a/app/server/model/plan/build_exec.go+++ b/app/server/model/plan/build_exec.go@@ -8,6 +8,7 @@ import ("plandex-server/db""plandex-server/hooks""plandex-server/model"+ "plandex-server/notify""plandex-server/types""runtime/debug""time"@@ -140,6 +141,9 @@ func (buildState *activeBuildStreamState) execPlanBuild(activeBuild *types.Activdefer func() {if r := recover(); r != nil {log.Printf("execPlanBuild: Panic: %v\n%s\n", r, string(debug.Stack()))++ go notify.NotifyErr(notify.SeverityError, fmt.Errorf("execPlanBuild: Panic: %v\n%s", r, string(debug.Stack())))+activePlan.StreamDoneCh <- &shared.ApiError{Type: shared.ApiErrorTypeOther,Status: http.StatusInternalServerError,diff --git a/app/server/model/plan/build_finish.go b/app/server/model/plan/build_finish.goindex 8b630361..312e999f 100644--- a/app/server/model/plan/build_finish.go+++ b/app/server/model/plan/build_finish.go@@ -7,6 +7,7 @@ import ("net/http""plandex-server/db""plandex-server/hooks"+ "plandex-server/notify""plandex-server/types""strings""time"@@ -143,6 +144,8 @@ func (state *activeBuildStreamFileState) onFinishBuild() {log.Printf("Error finishing build: %v\n", err)if err.Error() != context.Canceled.Error() {+ go notify.NotifyErr(notify.SeverityError, fmt.Errorf("error finishing build: %v", err))+ap.StreamDoneCh <- &shared.ApiError{Type: shared.ApiErrorTypeOther,Status: http.StatusInternalServerError,@@ -179,6 +182,8 @@ func (fileState *activeBuildStreamFileState) onFinishBuildFile(planRes *db.PlanFif planRes == nil {log.Println("onFinishBuildFile - planRes is nil")+ go notify.NotifyErr(notify.SeverityError, fmt.Errorf("onFinishBuildFile: planRes is nil"))+activePlan.StreamDoneCh <- &shared.ApiError{Type: shared.ApiErrorTypeOther,Status: http.StatusInternalServerError,@@ -211,6 +216,8 @@ func (fileState *activeBuildStreamFileState) onFinishBuildFile(planRes *db.PlanFif err != nil {log.Printf("Error storing plan build result: %v\n", err)+ go notify.NotifyErr(notify.SeverityError, fmt.Errorf("error storing plan build result: %v", err))+activePlan.StreamDoneCh <- &shared.ApiError{Type: shared.ApiErrorTypeOther,Status: http.StatusInternalServerError,@@ -285,6 +292,8 @@ func (fileState *activeBuildStreamFileState) onBuildFileError(err error) {activeBuild.Success = falseactiveBuild.Error = err+ go notify.NotifyErr(notify.SeverityError, fmt.Errorf("error for file %s: %v", filePath, err))+activePlan.StreamDoneCh <- &shared.ApiError{Type: shared.ApiErrorTypeOther,Status: http.StatusInternalServerError,diff --git a/app/server/model/plan/build_load.go b/app/server/model/plan/build_load.goindex ccfdb56b..a93e49d0 100644--- a/app/server/model/plan/build_load.go+++ b/app/server/model/plan/build_load.go@@ -5,6 +5,7 @@ import ("log""net/http""plandex-server/db"+ "plandex-server/notify""plandex-server/syntax""plandex-server/types"@@ -157,6 +158,8 @@ func (state *activeBuildStreamFileState) loadBuildFile(activeBuild *types.ActiveUpdateActivePlan(activePlan.Id, activePlan.Branch, func(ap *types.ActivePlan) {ap.IsBuildingByPath[filePath] = false})+ go notify.NotifyErr(notify.SeverityError, fmt.Errorf("error storing plan build: %v", err))+activePlan.StreamDoneCh <- &shared.ApiError{Type: shared.ApiErrorTypeOther,Status: http.StatusInternalServerError,@@ -194,6 +197,8 @@ func (state *activeBuildStreamFileState) loadBuildFile(activeBuild *types.ActiveUpdateActivePlan(activePlan.Id, activePlan.Branch, func(ap *types.ActivePlan) {ap.IsBuildingByPath[filePath] = false})+ go notify.NotifyErr(notify.SeverityError, fmt.Errorf("error getting current plan state: %v", err))+activePlan.StreamDoneCh <- &shared.ApiError{Type: shared.ApiErrorTypeOther,Status: http.StatusInternalServerError,@@ -236,6 +241,8 @@ func (state *activeBuildStreamFileState) loadBuildFile(activeBuild *types.ActiveUpdateActivePlan(activePlan.Id, activePlan.Branch, func(ap *types.ActivePlan) {ap.IsBuildingByPath[filePath] = false})+ go notify.NotifyErr(notify.SeverityError, fmt.Errorf("error loading build file: %v", err))+activePlan.StreamDoneCh <- &shared.ApiError{Type: shared.ApiErrorTypeOther,Status: http.StatusInternalServerError,diff --git a/app/server/model/plan/commit_msg.go b/app/server/model/plan/commit_msg.goindex 3f1e2403..b3826444 100644--- a/app/server/model/plan/commit_msg.go+++ b/app/server/model/plan/commit_msg.go@@ -9,6 +9,7 @@ import ("plandex-server/db""plandex-server/model""plandex-server/model/prompts"+ "plandex-server/notify""plandex-server/types""plandex-server/utils"@@ -28,6 +29,8 @@ func (state *activeTellStreamState) genPlanDescription() (*db.ConvoMessageDescriactivePlan := GetActivePlan(planId, branch)if activePlan == nil {+ go notify.NotifyErr(notify.SeverityError, fmt.Errorf("active plan not found for plan %s and branch %s", planId, branch))+return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther,Status: http.StatusInternalServerError,@@ -101,6 +104,8 @@ func (state *activeTellStreamState) genPlanDescription() (*db.ConvoMessageDescrimodelRes, err := model.ModelRequest(activePlan.Ctx, reqParams)if err != nil {+ go notify.NotifyErr(notify.SeverityError, fmt.Errorf("error during plan description model call: %v", err))+return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther,Status: http.StatusInternalServerError,@@ -117,6 +122,8 @@ func (state *activeTellStreamState) genPlanDescription() (*db.ConvoMessageDescriif config.BaseModelConfig.PreferredModelOutputFormat == shared.ModelOutputFormatXml {commitMsg = utils.GetXMLContent(content, "commitMsg")if commitMsg == "" {+ go notify.NotifyErr(notify.SeverityError, fmt.Errorf("no commitMsg tag found in XML response"))+return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther,Status: http.StatusInternalServerError,@@ -128,6 +135,8 @@ func (state *activeTellStreamState) genPlanDescription() (*db.ConvoMessageDescriif content == "" {fmt.Println("no describePlan function call found in response")+ go notify.NotifyErr(notify.SeverityError, fmt.Errorf("no describePlan function call found in response"))+return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther,Status: http.StatusInternalServerError,@@ -139,6 +148,9 @@ func (state *activeTellStreamState) genPlanDescription() (*db.ConvoMessageDescrierr = json.Unmarshal([]byte(content), &desc)if err != nil {fmt.Printf("Error unmarshalling plan description response: %v\n", err)++ go notify.NotifyErr(notify.SeverityError, fmt.Errorf("error unmarshalling plan description response: %v", err))+return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther,Status: http.StatusInternalServerError,diff --git a/app/server/model/plan/exec_status.go b/app/server/model/plan/exec_status.goindex e133a2fb..6e80a1e0 100644--- a/app/server/model/plan/exec_status.go+++ b/app/server/model/plan/exec_status.go@@ -8,6 +8,7 @@ import ("net/http""plandex-server/model""plandex-server/model/prompts"+ "plandex-server/notify""plandex-server/types""plandex-server/utils""strings"@@ -162,6 +163,8 @@ func (state *activeTellStreamState) execStatusShouldContinue(currentMessage strisubtaskFinished = subtaskFinishedStr == "true"if reasoning == "" || subtaskFinishedStr == "" {+ go notify.NotifyErr(notify.SeverityError, fmt.Errorf("execStatusShouldContinue: missing required XML tags in response"))+return execStatusShouldContinueResult{}, &shared.ApiError{Type: shared.ApiErrorTypeOther,Status: http.StatusInternalServerError,diff --git a/app/server/model/plan/tell_build_pending.go b/app/server/model/plan/tell_build_pending.goindex a6d91697..e8037ce7 100644--- a/app/server/model/plan/tell_build_pending.go+++ b/app/server/model/plan/tell_build_pending.go@@ -1,8 +1,10 @@package planimport (+ "fmt""log""net/http"+ "plandex-server/notify"shared "plandex-shared")@@ -26,6 +28,8 @@ func (state *activeTellStreamState) queuePendingBuilds() {if err != nil {log.Printf("Error getting pending builds by path: %v\n", err)+ go notify.NotifyErr(notify.SeverityError, fmt.Errorf("error getting pending builds by path: %v", err))+active.StreamDoneCh <- &shared.ApiError{Type: shared.ApiErrorTypeOther,Status: http.StatusInternalServerError,diff --git a/app/server/model/plan/tell_exec.go b/app/server/model/plan/tell_exec.goindex 52560702..8460b470 100644--- a/app/server/model/plan/tell_exec.go+++ b/app/server/model/plan/tell_exec.go@@ -10,6 +10,7 @@ import ("plandex-server/db""plandex-server/hooks""plandex-server/model"+ "plandex-server/notify""plandex-server/types"shared "plandex-shared"@@ -90,6 +91,9 @@ func execTellPlan(params execTellPlanParams) {defer func() {if r := recover(); r != nil {log.Printf("execTellPlan: Panic: %v\n%s\n", r, string(debug.Stack()))++ go notify.NotifyErr(notify.SeverityError, fmt.Errorf("execTellPlan: Panic: %v\n%s", r, string(debug.Stack())))+active.StreamDoneCh <- &shared.ApiError{Type: shared.ApiErrorTypeOther,Status: http.StatusInternalServerError,@@ -117,6 +121,8 @@ func execTellPlan(params execTellPlanParams) {err := db.SetPlanStatus(planId, branch, shared.PlanStatusReplying, "")if err != nil {log.Printf("Error setting plan %s status to replying: %v\n", planId, err)+ go notify.NotifyErr(notify.SeverityError, fmt.Errorf("error setting plan %s status to replying: %v", planId, err))+active.StreamDoneCh <- &shared.ApiError{Type: shared.ApiErrorTypeOther,Status: http.StatusInternalServerError,@@ -168,6 +174,8 @@ func execTellPlan(params execTellPlanParams) {tentativeMaxTokens = tentativeModelConfig.GetFinalLargeContextFallback().BaseModelConfig.MaxTokens} else {log.Printf("Tell plan - execTellPlan - unknown tell stage: %s\n", state.currentStage.TellStage)+ go notify.NotifyErr(notify.SeverityError, fmt.Errorf("execTellPlan: unknown tell stage: %s", state.currentStage.TellStage))+active.StreamDoneCh <- &shared.ApiError{Type: shared.ApiErrorTypeOther,Status: http.StatusInternalServerError,@@ -218,6 +226,8 @@ func execTellPlan(params execTellPlanParams) {if tokensRemaining < 0 {log.Println("tokensRemaining is negative")+ go notify.NotifyErr(notify.SeverityError, fmt.Errorf("tokensRemaining is negative"))+active.StreamDoneCh <- &shared.ApiError{Type: shared.ApiErrorTypeOther,Status: http.StatusInternalServerError,@@ -259,6 +269,8 @@ func execTellPlan(params execTellPlanParams) {sysParts, err := state.getTellSysPrompt(getTellSysPromptParams)if err != nil {log.Printf("Error getting tell sys prompt: %v\n", err)+ go notify.NotifyErr(notify.SeverityError, fmt.Errorf("error getting tell sys prompt: %v", err))+active.StreamDoneCh <- &shared.ApiError{Type: shared.ApiErrorTypeOther,Status: http.StatusInternalServerError,@@ -299,6 +311,8 @@ func execTellPlan(params execTellPlanParams) {// token limit already exceeded before adding conversationerr := fmt.Errorf("token limit exceeded before adding conversation")log.Printf("Error: %v\n", err)+ go notify.NotifyErr(notify.SeverityError, fmt.Errorf("token limit exceeded before adding conversation"))+active.StreamDoneCh <- &shared.ApiError{Type: shared.ApiErrorTypeOther,Status: http.StatusInternalServerError,@@ -316,6 +330,8 @@ func execTellPlan(params execTellPlanParams) {state.messages = append(state.messages, *promptMessage)} else {log.Println("promptMessage is nil")+ go notify.NotifyErr(notify.SeverityError, fmt.Errorf("promptMessage is nil"))+active.StreamDoneCh <- &shared.ApiError{Type: shared.ApiErrorTypeOther,Status: http.StatusInternalServerError,@@ -446,7 +462,7 @@ func execTellPlan(params execTellPlanParams) {stream, err := model.CreateChatCompletionStream(clients, &modelConfig, active.ModelStreamCtx, modelReq)if err != nil {log.Printf("Error starting reply stream: %v\n", err)-+ go notify.NotifyErr(notify.SeverityError, fmt.Errorf("error starting reply stream: %v", err))active.StreamDoneCh <- &shared.ApiError{Type: shared.ApiErrorTypeOther,Status: http.StatusInternalServerError,@@ -508,6 +524,9 @@ func (state *activeTellStreamState) dryRunCalculateTokensWithoutContext(tentativmsg := "Error getting tell sys prompt for dry run token calculation"if err.Error() == AllTasksCompletedMsg {msg = "There's no current task to implement. Try a prompt instead of the 'continue' command."+ go notify.NotifyErr(notify.SeverityInfo, msg)+ } else {+ go notify.NotifyErr(notify.SeverityError, fmt.Errorf("error getting tell sys prompt for dry run token calculation: %v", err))}state.activePlan.StreamDoneCh <- &shared.ApiError{@@ -538,6 +557,8 @@ func (state *activeTellStreamState) dryRunCalculateTokensWithoutContext(tentativif clone.tokensBeforeConvo > clone.settings.GetPlannerEffectiveMaxTokens() {log.Println("tokensBeforeConvo exceeds max tokens during dry run")+ go notify.NotifyErr(notify.SeverityError, fmt.Errorf("tokensBeforeConvo exceeds max tokens during dry run"))+state.activePlan.StreamDoneCh <- &shared.ApiError{Type: shared.ApiErrorTypeOther,Status: http.StatusInternalServerError,diff --git a/app/server/model/plan/tell_load.go b/app/server/model/plan/tell_load.goindex a530d7bc..28d50101 100644--- a/app/server/model/plan/tell_load.go+++ b/app/server/model/plan/tell_load.go@@ -6,6 +6,7 @@ import ("net/http""plandex-server/db""plandex-server/model"+ "plandex-server/notify""plandex-server/types"shared "plandex-shared"@@ -248,6 +249,8 @@ func (state *activeTellStreamState) loadTellPlan() error {for i := 0; i < 4; i++ {err = <-errChif err != nil {+ go notify.NotifyErr(notify.SeverityError, fmt.Errorf("error loading plan: %v", err))+active.StreamDoneCh <- &shared.ApiError{Type: shared.ApiErrorTypeOther,Status: http.StatusInternalServerError,@@ -274,6 +277,8 @@ func (state *activeTellStreamState) loadTellPlan() error {if err != nil {log.Printf("execTellPlan: error loading tell plan: %v\n", err)+ go notify.NotifyErr(notify.SeverityError, fmt.Errorf("error loading tell plan: %v", err))+active.StreamDoneCh <- &shared.ApiError{Type: shared.ApiErrorTypeOther,Status: http.StatusInternalServerError,diff --git a/app/server/model/plan/tell_stream_error.go b/app/server/model/plan/tell_stream_error.goindex cf5387ea..281cedb3 100644--- a/app/server/model/plan/tell_stream_error.go+++ b/app/server/model/plan/tell_stream_error.go@@ -6,6 +6,7 @@ import ("log""net/http""plandex-server/db"+ "plandex-server/notify""plandex-server/shutdown""strconv""time"@@ -170,6 +171,8 @@ func (state *activeTellStreamState) onError(params onErrorParams) onErrorResultmsg += " | Failed after " + strconv.Itoa(numRetries) + " retries."}+ go notify.NotifyErr(notify.SeverityInfo, fmt.Sprintf("tellStream stream error after %d retries: %v", numRetries, streamErr))+active.StreamDoneCh <- &shared.ApiError{Type: shared.ApiErrorTypeOther,Status: http.StatusInternalServerError,diff --git a/app/server/model/plan/tell_stream_finish.go b/app/server/model/plan/tell_stream_finish.goindex e53ba13b..6654fa35 100644--- a/app/server/model/plan/tell_stream_finish.go+++ b/app/server/model/plan/tell_stream_finish.go@@ -5,6 +5,7 @@ import ("log""net/http""plandex-server/db"+ "plandex-server/notify""plandex-server/types""time"@@ -153,7 +154,7 @@ func (state *activeTellStreamState) handleStreamFinished() handleStreamFinishedRselect {case <-active.Ctx.Done():log.Println("Context cancelled while waiting for auto load context")- state.execHookOnStop(true)+ state.execHookOnStop(false)return handleStreamFinishedResult{shouldContinueMainLoop: false,shouldReturn: true,@@ -221,11 +222,14 @@ func (state *activeTellStreamState) handleStreamFinished() handleStreamFinishedRerr := db.SetPlanStatus(planId, branch, shared.PlanStatusBuilding, "")if err != nil {log.Printf("Error setting plan status to building: %v\n", err)+ go notify.NotifyErr(notify.SeverityError, fmt.Errorf("error setting plan status to building: %v", err))+active.StreamDoneCh <- &shared.ApiError{Type: shared.ApiErrorTypeOther,Status: http.StatusInternalServerError,Msg: "Error setting plan status to building",}+return handleStreamFinishedResult{shouldContinueMainLoop: true,shouldReturn: false,diff --git a/app/server/model/plan/tell_stream_main.go b/app/server/model/plan/tell_stream_main.goindex 7dd3adcf..a97d61a5 100644--- a/app/server/model/plan/tell_stream_main.go+++ b/app/server/model/plan/tell_stream_main.go@@ -5,6 +5,7 @@ import ("log""net/http""plandex-server/model"+ "plandex-server/notify""runtime/debug""time"@@ -30,6 +31,9 @@ func (state *activeTellStreamState) listenStream(stream *model.ExtendedChatCompldefer func() {if r := recover(); r != nil {log.Printf("listenStream: Panic: %v\n%s\n", r, string(debug.Stack()))++ go notify.NotifyErr(notify.SeverityError, fmt.Errorf("listenStream: Panic: %v\n%s", r, string(debug.Stack())))+active.StreamDoneCh <- &shared.ApiError{Type: shared.ApiErrorTypeOther,Status: http.StatusInternalServerError,@@ -67,14 +71,15 @@ mainLoop:log.Println("\nTell: stream timeout due to inactivity")if streamFinished {log.Println("Tell stream finished—timed out waiting for usage chunk")- state.execHookOnStop(true)+ state.execHookOnStop(false)return} else {res := state.onError(onErrorParams{- streamErr: fmt.Errorf("stream timeout due to inactivity | The model is not responding."),+ streamErr: fmt.Errorf("stream timeout due to inactivity: The underlying LLM is not responding"),storeDesc: true,- canRetry: true,+ canRetry: active.CurrentReplyContent == "", // if there was no output yet, we can retry})+if res.shouldReturn {return}@@ -102,10 +107,16 @@ mainLoop:log.Printf("Tell: error receiving stream chunk: %v\n", err)state.execHookOnStop(true)+ var msg string+ if active.CurrentReplyContent == "" {+ msg = "The AI model didn't respond: %v"+ } else {+ msg = "The AI model stopped responding: %v"+ }state.onError(onErrorParams{- streamErr: fmt.Errorf("error receiving stream chunk: %v", err),+ streamErr: fmt.Errorf(msg, err),storeDesc: true,- canRetry: true,+ canRetry: active.CurrentReplyContent == "", // if there was no output yet, we can retry})// here we want to return no matter what -- state.onError will decide whether to retry or notreturn@@ -175,7 +186,7 @@ mainLoop:if choice.FinishReason == "error" {res := state.onError(onErrorParams{- streamErr: fmt.Errorf("model stopped with error status | The model is not responding."),+ streamErr: fmt.Errorf("the underlying LLM stopped with an error status | This means the LLM is not responding."),storeDesc: true,canRetry: true,})diff --git a/app/server/model/plan/tell_stream_processor.go b/app/server/model/plan/tell_stream_processor.goindex 50b511ce..14794d8d 100644--- a/app/server/model/plan/tell_stream_processor.go+++ b/app/server/model/plan/tell_stream_processor.go@@ -5,6 +5,7 @@ import ("log""net/http""plandex-server/db"+ "plandex-server/notify""plandex-server/types""regexp""runtime/debug"@@ -43,6 +44,8 @@ func (state *activeTellStreamState) processChunk(choice types.ExtendedChatCompleif r := recover(); r != nil {log.Printf("processChunk: Panic: %v\n%s\n", r, string(debug.Stack()))+ go notify.NotifyErr(notify.SeverityError, fmt.Errorf("processChunk: Panic: %v\n%s", r, string(debug.Stack())))+active.StreamDoneCh <- &shared.ApiError{Type: shared.ApiErrorTypeOther,Status: http.StatusInternalServerError,@@ -543,6 +546,8 @@ func (state *activeTellStreamState) handleMissingFile(content, currentFile, blocif err != nil {log.Printf("Error setting plan %s status to prompting: %v\n", planId, err)+ go notify.NotifyErr(notify.SeverityError, fmt.Errorf("error setting plan %s status to prompting: %v", planId, err))+active.StreamDoneCh <- &shared.ApiError{Type: shared.ApiErrorTypeOther,Status: http.StatusInternalServerError,@@ -608,7 +613,7 @@ func (state *activeTellStreamState) handleMissingFile(content, currentFile, blocselect {case <-active.Ctx.Done():log.Println("Context cancelled while waiting for missing file response")- state.execHookOnStop(true)+ state.execHookOnStop(false)return processChunkResult{shouldReturn: true}case <-time.After(30 * time.Minute): // long timeout here since we're waiting for user inputdiff --git a/app/server/model/plan/tell_stream_store.go b/app/server/model/plan/tell_stream_store.goindex 46911246..850ef406 100644--- a/app/server/model/plan/tell_stream_store.go+++ b/app/server/model/plan/tell_stream_store.go@@ -5,6 +5,7 @@ import ("log""net/http""plandex-server/db"+ "plandex-server/notify""plandex-server/types"shared "plandex-shared"@@ -213,6 +214,8 @@ func (state *activeTellStreamState) storeOnFinished(params storeOnFinishedParamsif err != nil {log.Printf("Error storing on finished: %v\n", err)+ go notify.NotifyErr(notify.SeverityError, fmt.Errorf("error storing on finished: %v", err))+active.StreamDoneCh <- &shared.ApiError{Type: shared.ApiErrorTypeOther,Status: http.StatusInternalServerError,diff --git a/app/server/model/plan/tell_summary.go b/app/server/model/plan/tell_summary.goindex 4aaf5bef..5e425d07 100644--- a/app/server/model/plan/tell_summary.go+++ b/app/server/model/plan/tell_summary.go@@ -9,6 +9,7 @@ import ("plandex-server/db""plandex-server/model""plandex-server/model/prompts"+ "plandex-server/notify""plandex-server/types""time"@@ -86,6 +87,8 @@ func (state *activeTellStreamState) addConversationMessages() bool {log.Println("tokensUpToTimestamp:")log.Println(spew.Sdump(tokensUpToTimestamp))+ go notify.NotifyErr(notify.SeverityError, fmt.Errorf("conversation summary timestamp not found in conversation"))+active.StreamDoneCh <- &shared.ApiError{Type: shared.ApiErrorTypeOther,Status: http.StatusInternalServerError,@@ -113,6 +116,8 @@ func (state *activeTellStreamState) addConversationMessages() bool {if summary == nil && tokensBeforeConvo+conversationTokens > state.settings.GetPlannerEffectiveMaxTokens() {err := errors.New("couldn't get under token limit with conversation summary")log.Printf("Error: %v\n", err)+ go notify.NotifyErr(notify.SeverityInfo, fmt.Errorf("couldn't get under token limit with conversation summary"))+active.StreamDoneCh <- &shared.ApiError{Type: shared.ApiErrorTypeOther,Status: http.StatusInternalServerError,@@ -159,6 +164,8 @@ func (state *activeTellStreamState) addConversationMessages() bool {}} else {if (tokensBeforeConvo + conversationTokens) > state.settings.GetPlannerEffectiveMaxTokens() {+ go notify.NotifyErr(notify.SeverityError, fmt.Errorf("token limit still exceeded after summarizing conversation"))+active.StreamDoneCh <- &shared.ApiError{Type: shared.ApiErrorTypeOther,Status: http.StatusInternalServerError,@@ -242,6 +249,7 @@ func summarizeConvo(clients map[string]model.ClientInfo, config shared.ModelRoleif active == nil {log.Printf("Active plan not found for plan ID %s and branch %s\n", planId, branch)+return &shared.ApiError{Type: shared.ApiErrorTypeOther,Status: http.StatusInternalServerError,diff --git a/app/server/model/prompts/apply_exec.go b/app/server/model/prompts/apply_exec.goindex 112df2c7..953684ab 100644--- a/app/server/model/prompts/apply_exec.go+++ b/app/server/model/prompts/apply_exec.go@@ -37,10 +37,12 @@ Avoid user prompts. Make reasonable default choices rather than prompting the us#### Keep It Lightweight And Simple-The _apply.sh script should be lightweight and shouldn't do too much work. *Offload to separate files* in the plan if a lot of scripting is needed. _apply.sh doesn't get written to the user's project, so anything that might be valuable to save, reuse, and version control should be in a separate file. You can chmod and execute those separate files from _apply.sh. _apply.sh is for 'throwaway' commands that only need to be run once after the plan is applied to the user's project, like installing dependencies, running tests, or starting servers. It shouldn't be complex.+The _apply.sh script should be lightweight and shouldn't do too much work. *Offload to separate files* in the plan if a lot of scripting is needed. _apply.sh doesn't get written to the user's project, so anything that might be valuable to save, reuse, and version control should be in a separate file. You can chmod and execute those separate files from _apply.sh. _apply.sh is for 'throwaway' commands that only need to be run once after the plan is applied to the user's project, like installing dependencies, running tests, or runing a start command. It shouldn't be complex.Do not use fancy bash constructs that can be difficult to debug or cause portability problems. Keep it very straightforward so there's a 0% chance of bugs in the _apply.sh script.++#### Command Preservation RulesThe _apply.sh script accumulates commands during the plan:@@ -113,19 +115,24 @@ Running programs:* When starting a web server that needs a browser launched:* CRITICAL: ALWAYS run the server in the background using & or the script will block and never reach the browser launch* Add a brief sleep to allow the server to start (use your judgment based on the server type and the complexity of the server startup process how long is reasonable)- * Use the appropriate browser launch command for the OS (provided in context—DO NOT include commands for other operating systems, just the one that is appropriate for the user's OS):- - macOS: open http://localhost:$PORT- - Linux: xdg-open http://localhost:$PORT- - Windows: start http://localhost:$PORT+ * ALWAYS use the special command 'plandex browser [urls...]' to launch the browser with one or more URLs. This command is provided by Plandex and is available on all operating systems. Substitute the actual URL or URLs you want to open in place of [urls...]. This special command *blocks* and streams the browser output to the console. So if you need to run other commands *after* the browser is launched, you must background the browser command and correclty handle cleanup like other background processes. If the browser command exits with an error, kill any other background processes and exit the entire script with a non-zero exit code.Example:# INCORRECT - will block and never launch browser:npm start- open http://localhost:$PORT+ plandex browser http://localhost:$PORT# CORRECT - runs in background, waits, then launches browser:npm start &+ SERVER_PID=$!sleep 3- open http://localhost:$PORT # Using appropriate command based on OS in context+ plandex browser http://localhost:$PORT || {+ kill $SERVER_PID+ exit 1+ }+ wait $SERVER_PID++ NOTE: when running anything in the background, you must handle the possibility that the process might fail so that no orphaned processes remain.+`const ApplyScriptPlanningPrompt = ApplyScriptSharedPrompt + `@@ -337,15 +344,84 @@ done# Build and start in backgroundnpm run buildnpm start &+SERVER_PID=$!# Wait briefly for server to be readysleep 3# Launch browser-open http://localhost:$PORT+plandex browser http://localhost:$PORT || {+ kill $SERVER_PID+ exit 1+}+wait $SERVER_PID</PlandexBlock>Note the usage of & to run the server in the background. This is CRITICAL to ensure the script does not block and allows the browser to launch.++* If you run multiple processes in parallel with &, you ABSOLUTELY MUST handle partial failure by immediately exiting the script if any process returns a non-zero code.+ * For example, store process PIDs, wait on all processes, check $?, kill all processes if a failure is detected, and exit with that code.+EXAMPLE:++- _apply.sh:+<PlandexBlock lang="bash" path="_apply.sh">+# Build assets first+npm install+npm run build++# Start Node in background, maybe with --inspect+echo "Starting Node server with inspector on port 9229..."+node --inspect=0.0.0.0:9229 server.js &+pidNode=$!++# Start Python app in background+echo "Starting Python service..."+python main.py &+pidPy=$!++# Wait for the *first* process to exit (success or failure)+echo "Waiting for either Node or Python to exit..."+wait $pidNode $pidPy+exit_code=$?++if [ $exit_code -ne 0 ]; then+ echo "⚠️ One process exited with an error. Stopping everything..."+ kill $pidNode $pidPy 2>/dev/null+ exit $exit_code+fi++# If we get here, the first process that ended did so with success code+# We still need to wait on the other process+echo "First process ended successfully, waiting for the second to exit..."+wait $pidNode+wait $pidPy+</PlandexBlock>++Note on example: notice there's no advanced job control (e.g. setsid, disown, etc.) is needed because the wrapper script handles cleanup. The processes remain in the same process group and are killed when the wrapper script exits. And notice that if either job fails, the wrapper script kills all the jobs and exits with the correct output and error code.++If you only run one background job or run them sequentially, you do not need partial-failure logic. Only include logic for handling partial failures if it's really necessary—otherwise, keep it simple: you can just run the commands and let the wrapper script handle cleanup. For example:++- _apply.sh:+<PlandexBlock lang="bash" path="_apply.sh">+# Run the server in the background+npm start &++# Run the tests in the foreground+npm test+</PlandexBlock>++In this case, the wrapper script will handle cleanup automatically.++- Plandex automatically wraps ` + "`_apply.sh`" + ` in a script that enables job control and kills all processes if the user interrupts. Do NOT add ` + "`trap`" + `, ` + "`setsid`" + `, ` + "`nohup`" + `, or ` + "`disown`" + ` commands.+- If you run multiple processes (e.g., ` + "`node server.js &`" + ` plus ` + "`python main.py &`" + `), you must handle partial failures by checking their exit codes. For example:+ - ` + "`pidA=$!`" + ` after launching the first process+ - Launch the second, ` + "`pidB=$!`" + `+ - Use ` + "`wait $pidA $pidB`" + ` or check each PID. If one fails (` + "`exit_code != 0`" + `), kill the other.+- If you only have a single process to run, you may simply do ` + "`command &`" + ` and then ` + "`wait`" + `. The wrapper script ensures no leftover processes remain if the user presses Ctrl+C.+- Don't run commands that may daemonize themselves or change their process group unless absolutely necessary since it complicates the cleanup process. The wrapper script cannot reliably handle processes that daemonize themselves or change their process group, so if you really must run such commands, you MUST ALWAYS include code to ensure they are cleaned up properly and reliably before exiting.++* You will be provided with the user's OS in the prompt. DO NOT include commands for other operating systems, just the user's specified OS.+* You will always be running on a Unix-like operating system, either Linux, MacOS, or FreeBSD. You'll never be running on Windows.` + ExitCodePrompt + ApplyScriptResetUpdateImplementationPromptconst ApplyScriptResetUpdateSharedPrompt = `@@ -453,7 +529,7 @@ Remember, after successful execution, _apply.sh ALWAYS resets to empty.You MUST ALWAYS consider adding build/run commands again after ANY source changes.If the _apply.sh script previously had a build/run command, and then it was reset to empty after being successfully executed, and then you make ANY subsequent code changes, you MUST add a new build/run command to the _apply.sh file.-CRITICAL: If you have run the project previously with the _apply.sh script *and* the _apply.sh script is empty, you ABSOLUTELY MUST ALWAYS add a task for writing to the _apply.sh file. DO NOT OMIT THIS STEP.+CRITICAL: If you have run the project previously with the _apply.sh script *and* the _apply.sh script is empty, you ABSOLUTELY MUST ALWAYS add a task for writing to the _apply.sh file. DO NOT OMIT THIS STEP. **THAT SAID** you must *evaluate* the current state of the _apply.sh file and *only* update it if necessary. Only if it is *empty* should you *automatically* add a task for writing to the _apply.sh file. Otherwise, consider the current state of the _apply.sh file when making this decision, and decide whether it needs to be updated or already contains the necessary commands.INCORRECT FOLLOW UP:### Tasks@@ -685,7 +761,9 @@ Good Practices:- Group related file changes with their commands- Keep it lightweight and simple- Offload to separate files if a lot of scripting is needed+- Offload to separate startup script/Makefile/package.json script/etc. for startup logic that is useful to have in the project- Use basic scripting that is easy to understand and debug+- Use portable bash that will work across a wide range of shell versions and Unix-like operating systemsBad Practices to Avoid:- Don't write same command multiple times@@ -695,7 +773,9 @@ Bad Practices to Avoid:- Don't hide command output- Don't prompt the user for input- Don't use fancy bash constructs that can be difficult to understand and debug-- Don't do too much work in _apply.sh. If it's getting complex, offload to separate files.+- Don't use bash constructs that require a recent version of bash—make them portable and 'just work' across a wide range of Unix-like operating systems and shell versions+- Don't do too much work in _apply.sh. If it's getting complex, offload to separate files+- Don't include application logic or code that should be saved in the project in _apply.sh. Write it in normal files in the plan instead.Remember:- Include _apply.sh in 'Uses:' list when modifying it@@ -755,6 +835,12 @@ Updating Script:- Update existing commands rather than duplicate- Maintain command grouping and organization+Browser Commands:+- Use the special command 'plandex browser [urls...]' to launch the browser with one or more URLs.+- This special command *blocks* and streams the browser output to the console.+- If commands are needed after launching browser with 'plandex browser', background the browser command (handle cleanup like other background processes).+- If the browser command exits with an error, kill any other background processes and exit the entire script with a non-zero exit code.+Error Handling:- Check for required tools- Exit with clear error messages@@ -779,6 +865,16 @@ Always:- Check tool prerequisites- Use clear error messages+**Process Management & Partial Failures**+- If you run multiple background processes, handle partial failures by capturing PIDs and using ` + "`wait $pidA $pidB`" + ` or similar. If any process fails, kill the rest.+- Do not add ` + "`setsid`" + `, ` + "`disown`" + `, or ` + "`nohup`" + `. The wrapper script already ensures group-wide kills on interrupt.+- Do not use 'wait -n'. Use 'wait $pidA $pidB' instead.+- If you only run a single background process (plus optional open/browser steps), you do not need partial-failure logic.++User OS:+- You will be provided with the user's operating system. Do NOT include multiple commands for different operating systems. Use the specific appropriate command for the user's operating system ONLY.+- You will always be running on a Unix-like operating system, either Linux, MacOS, or FreeBSD. You'll never be running on Windows.+---` + ExitCodePrompt + ApplyScriptResetUpdateImplementationSummary + ApplyScriptExecutionSummary@@ -816,7 +912,7 @@ Task Organization:- Plan for command reuse after reset- Account for the full change lifecycle-CRITICAL: If you have run the project previously with the _apply.sh script *and* the _apply.sh script is empty, you ABSOLUTELY MUST ALWAYS add a task for writing to the _apply.sh file. DO NOT OMIT THIS STEP.+CRITICAL: If you have run the project previously with the _apply.sh script *and* the _apply.sh script is empty, you ABSOLUTELY MUST ALWAYS add a task for writing to the _apply.sh file. DO NOT OMIT THIS STEP. **THAT SAID** you must *evaluate* the current state of the _apply.sh file and *only* update it if necessary. Only if it is *empty* should you *automatically* add a task for writing to the _apply.sh file. Otherwise, consider the current state of the _apply.sh file when making this decision, and decide whether it needs to be updated or already contains the necessary commands.`const ApplyScriptResetUpdateImplementationSummary = `@@ -852,7 +948,8 @@ CRITICAL: The script must handle both program execution and security carefully:1. Program Execution- ALWAYS include commands to run the actual program after building/installing- - If there's a clear way to run the project, users should never need to run programs manually—always include commands to run the project in _apply.sh+ - If there's a clear way to run the project, users should never need to run programs manually—always include commands to run the project (or call a startup script/Makefile/package.json script/etc.) in _apply.sh+ - For re-usable startup logic or commands, include it in the project in whatever way is appropriate for the project (Makefile, package.json, etc.)—then call it from _apply.sh- Include ALL necessary startup steps (build → install → run)- For web applications and web servers:* ALWAYS include commands to launch a browser to the appropriate localhost URL—use the appropriate command for the *user's operating system* (do NOT include commands for other operating systems)@@ -892,6 +989,9 @@ CRITICAL: The script must handle both program execution and security carefully:7. Keep It Lightweight And Simple- The _apply.sh script should be lightweight and shouldn't do too much work. *Offload to separate files* in the plan if a lot of scripting is needed.- Do not use fancy bash constructs that can be difficult to debug or cause portability problems.+ - Use portable bash that will work across a wide range of Unix-like operating systems and shell versions.+ - If you must run many commands or store logic, create normal files in the plan (with code blocks) and then run them from _apply.sh.+ - Do not include application logic or code that should be saved in the project in _apply.sh. Write it in normal files in the plan instead. _apply.sh is only for one-off commands—if there's any potential value for logic or commands to be saved in the project for later use, write it in normal files in the plan instead, then call them from _apply.sh.Remember:- Do NOT tell the user to run _apply.sh. It will be run automatically when the plan is applied.diff --git a/app/server/notify/errors.go b/app/server/notify/errors.gonew file mode 100644index 00000000..dfd7fadf--- /dev/null+++ b/app/server/notify/errors.go@@ -0,0 +1,23 @@+package notify++// this allows Plandex Cloud to inject error monitoring+// all non-streaming handlers are already wrapped with different logic, so this is only needed for errors in streaming handlers++type Severity int++const (+ SeverityInfo Severity = iota+ SeverityError+)++var NotifyErrFn func(severity Severity, data ...interface{})++func RegisterNotifyErrFn(fn func(severity Severity, data ...interface{})) {+ NotifyErrFn = fn+}++func NotifyErr(severity Severity, data ...interface{}) {+ if NotifyErrFn != nil {+ NotifyErrFn(severity, data...)+ }+}diff --git a/app/server/routes/routes.go b/app/server/routes/routes.goindex fda65a24..38573611 100644--- a/app/server/routes/routes.go+++ b/app/server/routes/routes.go@@ -12,8 +12,25 @@ import ("github.com/gorilla/mux")+type PlandexHandler func(w http.ResponseWriter, r *http.Request)+type HandlePlandex func(router *mux.Router, path string, isStreaming bool, handler PlandexHandler) *mux.Route++var HandlePlandexFn HandlePlandex++func RegisterHandlePlandex(fn HandlePlandex) {+ HandlePlandexFn = fn+}++func EnsureHandlePlandex() {+ if HandlePlandexFn == nil {+ panic("handlePlandexFn is not set")+ }+}+func AddHealthRoutes(r *mux.Router) {- r.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {+ EnsureHandlePlandex()++ HandlePlandexFn(r, "/health", false, func(w http.ResponseWriter, r *http.Request) {_, apiErr := hooks.ExecHook(hooks.HealthCheck, hooks.HookParams{})if apiErr != nil {log.Printf("Error in health check hook: %v\n", apiErr)@@ -23,7 +40,7 @@ func AddHealthRoutes(r *mux.Router) {fmt.Fprint(w, "OK")})- r.HandleFunc("/version", func(w http.ResponseWriter, r *http.Request) {+ HandlePlandexFn(r, "/version", false, func(w http.ResponseWriter, r *http.Request) {// Log the hosthost := r.Hostlog.Printf("Host header: %s", host)@@ -70,107 +87,112 @@ func AddProxyableApiRoutesWithPrefix(r *mux.Router, prefix string) {}func addApiRoutes(r *mux.Router, prefix string) {- r.HandleFunc(prefix+"/accounts/email_verifications", handlers.CreateEmailVerificationHandler).Methods("POST")- r.HandleFunc(prefix+"/accounts/email_verifications/check_pin", handlers.CheckEmailPinHandler).Methods("POST")- r.HandleFunc(prefix+"/accounts/sign_in_codes", handlers.CreateSignInCodeHandler).Methods("POST")- r.HandleFunc(prefix+"/accounts/sign_in", handlers.SignInHandler).Methods("POST")- r.HandleFunc(prefix+"/accounts/sign_out", handlers.SignOutHandler).Methods("POST")- r.HandleFunc(prefix+"/accounts", handlers.CreateAccountHandler).Methods("POST")+ EnsureHandlePlandex()- r.HandleFunc(prefix+"/orgs/session", handlers.GetOrgSessionHandler).Methods("GET")- r.HandleFunc(prefix+"/orgs", handlers.ListOrgsHandler).Methods("GET")- r.HandleFunc(prefix+"/orgs", handlers.CreateOrgHandler).Methods("POST")+ HandlePlandexFn(r, prefix+"/accounts/email_verifications", false, handlers.CreateEmailVerificationHandler).Methods("POST")+ HandlePlandexFn(r, prefix+"/accounts/email_verifications/check_pin", false, handlers.CheckEmailPinHandler).Methods("POST")+ HandlePlandexFn(r, prefix+"/accounts/sign_in_codes", false, handlers.CreateSignInCodeHandler).Methods("POST")+ HandlePlandexFn(r, prefix+"/accounts/sign_in", false, handlers.SignInHandler).Methods("POST")+ HandlePlandexFn(r, prefix+"/accounts/sign_out", false, handlers.SignOutHandler).Methods("POST")+ HandlePlandexFn(r, prefix+"/accounts", false, handlers.CreateAccountHandler).Methods("POST")- r.HandleFunc(prefix+"/users", handlers.ListUsersHandler).Methods("GET")- r.HandleFunc(prefix+"/orgs/users/{userId}", handlers.DeleteOrgUserHandler).Methods("DELETE")- r.HandleFunc(prefix+"/orgs/roles", handlers.ListOrgRolesHandler).Methods("GET")+ HandlePlandexFn(r, prefix+"/orgs/session", false, handlers.GetOrgSessionHandler).Methods("GET")+ HandlePlandexFn(r, prefix+"/orgs", false, handlers.ListOrgsHandler).Methods("GET")+ HandlePlandexFn(r, prefix+"/orgs", false, handlers.CreateOrgHandler).Methods("POST")- r.HandleFunc(prefix+"/invites", handlers.InviteUserHandler).Methods("POST")- r.HandleFunc(prefix+"/invites/pending", handlers.ListPendingInvitesHandler).Methods("GET")- r.HandleFunc(prefix+"/invites/accepted", handlers.ListAcceptedInvitesHandler).Methods("GET")- r.HandleFunc(prefix+"/invites/all", handlers.ListAllInvitesHandler).Methods("GET")- r.HandleFunc(prefix+"/invites/{inviteId}", handlers.DeleteInviteHandler).Methods("DELETE")+ HandlePlandexFn(r, prefix+"/users", false, handlers.ListUsersHandler).Methods("GET")+ HandlePlandexFn(r, prefix+"/orgs/users/{userId}", false, handlers.DeleteOrgUserHandler).Methods("DELETE")+ HandlePlandexFn(r, prefix+"/orgs/roles", false, handlers.ListOrgRolesHandler).Methods("GET")- r.HandleFunc(prefix+"/projects", handlers.CreateProjectHandler).Methods("POST")- r.HandleFunc(prefix+"/projects", handlers.ListProjectsHandler).Methods("GET")- r.HandleFunc(prefix+"/projects/{projectId}/set_plan", handlers.ProjectSetPlanHandler).Methods("PUT")- r.HandleFunc(prefix+"/projects/{projectId}/rename", handlers.RenameProjectHandler).Methods("PUT")+ HandlePlandexFn(r, prefix+"/invites", false, handlers.InviteUserHandler).Methods("POST")+ HandlePlandexFn(r, prefix+"/invites/pending", false, handlers.ListPendingInvitesHandler).Methods("GET")+ HandlePlandexFn(r, prefix+"/invites/accepted", false, handlers.ListAcceptedInvitesHandler).Methods("GET")+ HandlePlandexFn(r, prefix+"/invites/all", false, handlers.ListAllInvitesHandler).Methods("GET")+ HandlePlandexFn(r, prefix+"/invites/{inviteId}", false, handlers.DeleteInviteHandler).Methods("DELETE")- r.HandleFunc(prefix+"/projects/{projectId}/plans/current_branches", handlers.GetCurrentBranchByPlanIdHandler).Methods("POST")+ HandlePlandexFn(r, prefix+"/projects", false, handlers.CreateProjectHandler).Methods("POST")+ HandlePlandexFn(r, prefix+"/projects", false, handlers.ListProjectsHandler).Methods("GET")+ HandlePlandexFn(r, prefix+"/projects/{projectId}/set_plan", false, handlers.ProjectSetPlanHandler).Methods("PUT")+ HandlePlandexFn(r, prefix+"/projects/{projectId}/rename", false, handlers.RenameProjectHandler).Methods("PUT")- r.HandleFunc(prefix+"/plans", handlers.ListPlansHandler).Methods("GET")- r.HandleFunc(prefix+"/plans/archive", handlers.ListArchivedPlansHandler).Methods("GET")- r.HandleFunc(prefix+"/plans/ps", handlers.ListPlansRunningHandler).Methods("GET")+ HandlePlandexFn(r, prefix+"/projects/{projectId}/plans/current_branches", false, handlers.GetCurrentBranchByPlanIdHandler).Methods("POST")- r.HandleFunc(prefix+"/projects/{projectId}/plans", handlers.CreatePlanHandler).Methods("POST")+ HandlePlandexFn(r, prefix+"/plans", false, handlers.ListPlansHandler).Methods("GET")+ HandlePlandexFn(r, prefix+"/plans/archive", false, handlers.ListArchivedPlansHandler).Methods("GET")+ HandlePlandexFn(r, prefix+"/plans/ps", false, handlers.ListPlansRunningHandler).Methods("GET")- r.HandleFunc(prefix+"/projects/{projectId}/plans", handlers.CreatePlanHandler).Methods("DELETE")+ HandlePlandexFn(r, prefix+"/projects/{projectId}/plans", false, handlers.CreatePlanHandler).Methods("POST")- r.HandleFunc(prefix+"/plans/{planId}", handlers.GetPlanHandler).Methods("GET")- r.HandleFunc(prefix+"/plans/{planId}", handlers.DeletePlanHandler).Methods("DELETE")+ HandlePlandexFn(r, prefix+"/projects/{projectId}/plans", false, handlers.CreatePlanHandler).Methods("DELETE")- r.HandleFunc(prefix+"/plans/{planId}/current_plan/{sha}", handlers.CurrentPlanHandler).Methods("GET")- r.HandleFunc(prefix+"/plans/{planId}/{branch}/current_plan", handlers.CurrentPlanHandler).Methods("GET")- r.HandleFunc(prefix+"/plans/{planId}/{branch}/apply", handlers.ApplyPlanHandler).Methods("PATCH")- r.HandleFunc(prefix+"/plans/{planId}/archive", handlers.ArchivePlanHandler).Methods("PATCH")- r.HandleFunc(prefix+"/plans/{planId}/unarchive", handlers.UnarchivePlanHandler).Methods("PATCH")+ HandlePlandexFn(r, prefix+"/plans/{planId}", false, handlers.GetPlanHandler).Methods("GET")+ HandlePlandexFn(r, prefix+"/plans/{planId}", false, handlers.DeletePlanHandler).Methods("DELETE")- r.HandleFunc(prefix+"/plans/{planId}/rename", handlers.RenamePlanHandler).Methods("PATCH")- r.HandleFunc(prefix+"/plans/{planId}/{branch}/reject_all", handlers.RejectAllChangesHandler).Methods("PATCH")- r.HandleFunc(prefix+"/plans/{planId}/{branch}/reject_file", handlers.RejectFileHandler).Methods("PATCH")- r.HandleFunc(prefix+"/plans/{planId}/{branch}/reject_files", handlers.RejectFilesHandler).Methods("PATCH")- r.HandleFunc(prefix+"/plans/{planId}/{branch}/diffs", handlers.GetPlanDiffsHandler).Methods("GET")+ HandlePlandexFn(r, prefix+"/plans/{planId}/current_plan/{sha}", false, handlers.CurrentPlanHandler).Methods("GET")+ HandlePlandexFn(r, prefix+"/plans/{planId}/{branch}/current_plan", false, handlers.CurrentPlanHandler).Methods("GET")+ HandlePlandexFn(r, prefix+"/plans/{planId}/{branch}/apply", false, handlers.ApplyPlanHandler).Methods("PATCH")+ HandlePlandexFn(r, prefix+"/plans/{planId}/archive", false, handlers.ArchivePlanHandler).Methods("PATCH")+ HandlePlandexFn(r, prefix+"/plans/{planId}/unarchive", false, handlers.UnarchivePlanHandler).Methods("PATCH")- r.HandleFunc(prefix+"/plans/{planId}/{branch}/context", handlers.ListContextHandler).Methods("GET")- r.HandleFunc(prefix+"/plans/{planId}/{branch}/context", handlers.LoadContextHandler).Methods("POST")- r.HandleFunc(prefix+"/plans/{planId}/{branch}/context/{contextId}/body", handlers.GetContextBodyHandler).Methods("GET")- r.HandleFunc(prefix+"/plans/{planId}/{branch}/context", handlers.UpdateContextHandler).Methods("PUT")- r.HandleFunc(prefix+"/plans/{planId}/{branch}/context", handlers.DeleteContextHandler).Methods("DELETE")+ HandlePlandexFn(r, prefix+"/plans/{planId}/rename", false, handlers.RenamePlanHandler).Methods("PATCH")+ HandlePlandexFn(r, prefix+"/plans/{planId}/{branch}/reject_all", false, handlers.RejectAllChangesHandler).Methods("PATCH")+ HandlePlandexFn(r, prefix+"/plans/{planId}/{branch}/reject_file", false, handlers.RejectFileHandler).Methods("PATCH")+ HandlePlandexFn(r, prefix+"/plans/{planId}/{branch}/reject_files", false, handlers.RejectFilesHandler).Methods("PATCH")+ HandlePlandexFn(r, prefix+"/plans/{planId}/{branch}/diffs", false, handlers.GetPlanDiffsHandler).Methods("GET")- r.HandleFunc(prefix+"/plans/{planId}/{branch}/convo", handlers.ListConvoHandler).Methods("GET")- r.HandleFunc(prefix+"/plans/{planId}/{branch}/rewind", handlers.RewindPlanHandler).Methods("PATCH")- r.HandleFunc(prefix+"/plans/{planId}/{branch}/logs", handlers.ListLogsHandler).Methods("GET")+ HandlePlandexFn(r, prefix+"/plans/{planId}/{branch}/context", false, handlers.ListContextHandler).Methods("GET")+ HandlePlandexFn(r, prefix+"/plans/{planId}/{branch}/context", false, handlers.LoadContextHandler).Methods("POST")+ HandlePlandexFn(r, prefix+"/plans/{planId}/{branch}/context/{contextId}/body", false, handlers.GetContextBodyHandler).Methods("GET")+ HandlePlandexFn(r, prefix+"/plans/{planId}/{branch}/context", false, handlers.UpdateContextHandler).Methods("PUT")+ HandlePlandexFn(r, prefix+"/plans/{planId}/{branch}/context", false, handlers.DeleteContextHandler).Methods("DELETE")- r.HandleFunc(prefix+"/plans/{planId}/branches", handlers.ListBranchesHandler).Methods("GET")- r.HandleFunc(prefix+"/plans/{planId}/branches/{branch}", handlers.DeleteBranchHandler).Methods("DELETE")- r.HandleFunc(prefix+"/plans/{planId}/{branch}/branches", handlers.CreateBranchHandler).Methods("POST")+ HandlePlandexFn(r, prefix+"/plans/{planId}/{branch}/convo", false, handlers.ListConvoHandler).Methods("GET")+ HandlePlandexFn(r, prefix+"/plans/{planId}/{branch}/rewind", false, handlers.RewindPlanHandler).Methods("PATCH")+ HandlePlandexFn(r, prefix+"/plans/{planId}/{branch}/logs", false, handlers.ListLogsHandler).Methods("GET")- r.HandleFunc(prefix+"/plans/{planId}/{branch}/settings", handlers.GetSettingsHandler).Methods("GET")- r.HandleFunc(prefix+"/plans/{planId}/{branch}/settings", handlers.UpdateSettingsHandler).Methods("PUT")+ HandlePlandexFn(r, prefix+"/plans/{planId}/branches", false, handlers.ListBranchesHandler).Methods("GET")+ HandlePlandexFn(r, prefix+"/plans/{planId}/branches/{branch}", false, handlers.DeleteBranchHandler).Methods("DELETE")+ HandlePlandexFn(r, prefix+"/plans/{planId}/{branch}/branches", false, handlers.CreateBranchHandler).Methods("POST")- r.HandleFunc(prefix+"/plans/{planId}/{branch}/status", handlers.GetPlanStatusHandler).Methods("GET")+ HandlePlandexFn(r, prefix+"/plans/{planId}/{branch}/settings", false, handlers.GetSettingsHandler).Methods("GET")+ HandlePlandexFn(r, prefix+"/plans/{planId}/{branch}/settings", false, handlers.UpdateSettingsHandler).Methods("PUT")- r.HandleFunc(prefix+"/plans/{planId}/{branch}/tell", handlers.TellPlanHandler).Methods("POST")- r.HandleFunc(prefix+"/plans/{planId}/{branch}/build", handlers.BuildPlanHandler).Methods("PATCH")+ HandlePlandexFn(r, prefix+"/plans/{planId}/{branch}/status", false, handlers.GetPlanStatusHandler).Methods("GET")- r.HandleFunc(prefix+"/custom_models", handlers.ListCustomModelsHandler).Methods("GET")- r.HandleFunc(prefix+"/custom_models", handlers.CreateCustomModelHandler).Methods("POST")- r.HandleFunc(prefix+"/custom_models/{modelId}", handlers.DeleteAvailableModelHandler).Methods("DELETE")+ HandlePlandexFn(r, prefix+"/plans/{planId}/{branch}/tell", true, handlers.TellPlanHandler).Methods("POST")+ HandlePlandexFn(r, prefix+"/plans/{planId}/{branch}/build", true, handlers.BuildPlanHandler).Methods("PATCH")- r.HandleFunc(prefix+"/model_sets", handlers.ListModelPacksHandler).Methods("GET")- r.HandleFunc(prefix+"/model_sets", handlers.CreateModelPackHandler).Methods("POST")- r.HandleFunc(prefix+"/model_sets/{setId}", handlers.DeleteModelPackHandler).Methods("DELETE")+ 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.DeleteAvailableModelHandler).Methods("DELETE")+ HandlePlandexFn(r, prefix+"/custom_models/{modelId}", false, handlers.UpdateCustomModelHandler).Methods("PUT")- r.HandleFunc(prefix+"/default_settings", handlers.GetDefaultSettingsHandler).Methods("GET")- r.HandleFunc(prefix+"/default_settings", handlers.UpdateDefaultSettingsHandler).Methods("PUT")+ HandlePlandexFn(r, prefix+"/model_sets", false, handlers.ListModelPacksHandler).Methods("GET")+ HandlePlandexFn(r, prefix+"/model_sets", false, handlers.CreateModelPackHandler).Methods("POST")+ HandlePlandexFn(r, prefix+"/model_sets/{setId}", false, handlers.DeleteModelPackHandler).Methods("DELETE")+ HandlePlandexFn(r, prefix+"/model_sets/{setId}", false, handlers.UpdateModelPackHandler).Methods("PUT")+ HandlePlandexFn(r, prefix+"/default_settings", false, handlers.GetDefaultSettingsHandler).Methods("GET")+ HandlePlandexFn(r, prefix+"/default_settings", false, handlers.UpdateDefaultSettingsHandler).Methods("PUT")- r.HandleFunc(prefix+"/file_map", handlers.GetFileMapHandler).Methods("POST")- r.HandleFunc(prefix+"/plans/{planId}/{branch}/load_cached_file_map", handlers.LoadCachedFileMapHandler).Methods("POST")+ HandlePlandexFn(r, prefix+"/file_map", false, handlers.GetFileMapHandler).Methods("POST")+ HandlePlandexFn(r, prefix+"/plans/{planId}/{branch}/load_cached_file_map", false, handlers.LoadCachedFileMapHandler).Methods("POST")- r.HandleFunc(prefix+"/plans/{planId}/config", handlers.GetPlanConfigHandler).Methods("GET")- r.HandleFunc(prefix+"/plans/{planId}/config", handlers.UpdatePlanConfigHandler).Methods("PUT")+ HandlePlandexFn(r, prefix+"/plans/{planId}/config", false, handlers.GetPlanConfigHandler).Methods("GET")+ HandlePlandexFn(r, prefix+"/plans/{planId}/config", false, handlers.UpdatePlanConfigHandler).Methods("PUT")- r.HandleFunc(prefix+"/default_plan_config", handlers.GetDefaultPlanConfigHandler).Methods("GET")- r.HandleFunc(prefix+"/default_plan_config", handlers.UpdateDefaultPlanConfigHandler).Methods("PUT")+ HandlePlandexFn(r, prefix+"/default_plan_config", false, handlers.GetDefaultPlanConfigHandler).Methods("GET")+ HandlePlandexFn(r, prefix+"/default_plan_config", false, handlers.UpdateDefaultPlanConfigHandler).Methods("PUT")}func addProxyableApiRoutes(r *mux.Router, prefix string) {- r.HandleFunc(prefix+"/plans/{planId}/{branch}/connect", handlers.ConnectPlanHandler).Methods("PATCH")- r.HandleFunc(prefix+"/plans/{planId}/{branch}/stop", handlers.StopPlanHandler).Methods("DELETE")+ EnsureHandlePlandex()++ HandlePlandexFn(r, prefix+"/plans/{planId}/{branch}/connect", true, handlers.ConnectPlanHandler).Methods("PATCH")+ HandlePlandexFn(r, prefix+"/plans/{planId}/{branch}/stop", false, handlers.StopPlanHandler).Methods("DELETE")- r.HandleFunc(prefix+"/plans/{planId}/{branch}/respond_missing_file", handlers.RespondMissingFileHandler).Methods("POST")+ HandlePlandexFn(r, prefix+"/plans/{planId}/{branch}/respond_missing_file", false, handlers.RespondMissingFileHandler).Methods("POST")- r.HandleFunc(prefix+"/plans/{planId}/{branch}/auto_load_context", handlers.AutoLoadContextHandler).Methods("POST")+ HandlePlandexFn(r, prefix+"/plans/{planId}/{branch}/auto_load_context", false, handlers.AutoLoadContextHandler).Methods("POST")- r.HandleFunc(prefix+"/plans/{planId}/{branch}/build_status", handlers.GetBuildStatusHandler).Methods("GET")+ HandlePlandexFn(r, prefix+"/plans/{planId}/{branch}/build_status", false, handlers.GetBuildStatusHandler).Methods("GET")}diff --git a/app/server/types/active_plan.go b/app/server/types/active_plan.goindex d279a207..215fbba6 100644--- a/app/server/types/active_plan.go+++ b/app/server/types/active_plan.go@@ -3,9 +3,11 @@ package typesimport ("context""encoding/json"+ "fmt""log""net/http""plandex-server/db"+ "plandex-server/notify""plandex-server/shutdown""sync""time"@@ -240,6 +242,8 @@ func (ap *ActivePlan) Stream(msg shared.StreamMessage) {msgJson, err := json.Marshal(msg)if err != nil {ap.streamMu.Unlock()+ go notify.NotifyErr(notify.SeverityError, fmt.Errorf("error marshalling stream message: %v", err))+ap.StreamDoneCh <- &shared.ApiError{Type: shared.ApiErrorTypeOther,Status: http.StatusInternalServerError,diff --git a/app/server/utils/error.go b/app/server/utils/error.gonew file mode 100644index 00000000..d4b585bf--- /dev/null+++ b/app/server/utils/error.go@@ -0,0 +1 @@+package utils