Skip to content

Open source AI coding agent. Designed for large projects and real world tasks.

cloud-specific binary setup, dependency injection, basis for stripe

Dane Schneider7eff596bd8ce
diff --git a/README.md b/README.md
index 1f6b9724..4dc40047 100644
--- a/README.md
+++ b/README.md
@@ -1,14 +1,14 @@
## ๐ŸŒŸ Build large features and entire projects with AI.
-๐Ÿ”ฎ Plandex is an open source, terminal-based **AI programming engine** with long-running agents, automatic file updates, versioning, branches, and diff review.
+๐Ÿ”ฎ Plandex is an open source, terminal-based AI programming engine with long-running agents, automatic file updates, versioning, branches, and diff review.
-๐Ÿ”„ Enables a **tight feedback loop** between programmer and AI.
+๐Ÿ”„ It enables a tight feedback loop between programmer and AI.
-๐Ÿ‹๏ธ Helps you churn through your backlog, work with unfamiliar technologies, get unstuck, and spend less time on tedious tasks. **Makes programming more fun.**
+๐Ÿ’ช It helps you churn through your backlog, work with unfamiliar technologies, get unstuck, and spend less time on tedious tasks.
-๐Ÿง  Relies on the **OpenAI API** and requires an `OPENAI_API_KEY` environment variable. Support for Open Source models, Google Gemini, and Anthropic Claude is coming soon.
+๐Ÿง  Plandex relies on the OpenAI API and requires an `OPENAI_API_KEY` environment variable. Support for Open Source models, Google Gemini, and Anthropic Claude is coming soon.
-โœ… **Supports Mac, Linux, and Windows** (Windows supported via [Git bash](https://gitforwindows.org) or [WSL](https://learn.microsoft.com/en-us/windows/wsl/about)). Runs from a single binary with no dependencies. Small, fast, and efficient. Works with any programming language, framework, or technology.
+โœ… Plandex supports Mac, Linux, and Windows (Windows supported via [Git bash](https://gitforwindows.org) or [WSL](https://learn.microsoft.com/en-us/windows/wsl/about)). It runs from a single binary with no dependencies.
## Install ๐Ÿ“ฅ
@@ -29,13 +29,13 @@ pdx new
After any plandex command is run, additional commands that could make sense to run next will be suggested.
-To see all available commands, run:
+To see all available commands:
```
plandex help
```
-For help on any command, run:
+For help on any command:
```
plandex [command] --help
@@ -43,15 +43,15 @@ plandex [command] --help
## Why Plandex? ๐Ÿค”
-- ๐Ÿ—๏ธ Go beyond autocomplete to build complex functionality with AI
-- ๐Ÿšซ Stop the mouse-centered, copy-pasting-back-and-forth madness of coding with ChatGPT
-- ๐Ÿ“‘ Manage context efficiently in the terminalโ€”load or remove entire directories recursively or multiple files with glob patterns
-- โšก๏ธ Ensure AI models always have the latest versions of files in context
-- ๐Ÿšง Experiment, revise, and review in a protected sandbox before applying changes
-- โช Rewind and retry as needed with baked-in version control
-- ๐ŸŒฑ Explore multiple approaches with branches
-- ๐ŸŽ๏ธ Run tasks in the background or work on multiple tasks in parallel
-- ๐ŸŒก๏ธ Try different models and model settings
+- ๐Ÿ—๏ธ Go beyond autocomplete to build complex functionality with AI.
+- ๐Ÿšซ Stop the mouse-centered, copy-pasting madness of coding with ChatGPT.
+- ๐Ÿ“‘ Manage context efficiently in the terminalโ€”load entire directories recursively or multiple files with glob patterns.
+- โšก๏ธ Ensure AI models always have the latest versions of files in context.
+- ๐Ÿšง Experiment, revise, and review in a protected sandbox before applying changes.
+- โช Rewind and retry as needed with baked-in version control.
+- ๐ŸŒฑ Explore multiple approaches with branches.
+- ๐ŸŽ๏ธ Run tasks in the background or work on multiple tasks in parallel.
+- ๐ŸŒก๏ธ Try different models and model settings.
## License ๐Ÿ“œ
@@ -59,7 +59,7 @@ Plandex is open source under the MIT License.
## Plandex Cloud โ˜๏ธ
-Plandex Cloud is the easiest and most reliable way to use Plandex. You'll be prompted to start an anonymous trial (no email required) when you create your first plan with `plandex new`. Trial accounts are limited to 10 plans and 10 replies per plan. You can upgrade to a full account at any time with your name and email.
+Plandex Cloud is the easiest and most reliable way to use Plandex. You'll be prompted to start an anonymous trial (no email required) when you create your first plan with `plandex new`. Trial accounts are limited to 10 plans and 10 replies per plan. You can upgrade to a full account with your name and email.
Plandex Cloud accounts are free for now. In the future, there will be a monthly fee comparable to other popular AI tools.
@@ -115,7 +115,7 @@ Please star โญ, fork โ‘‚, explore ๐Ÿ”, and contribute ๐Ÿค
## About the developer ๐Ÿ‘‹
-Hi, I'm Dane. I've been building and launching software products for 17 years. I went through YCombinator in winter 2018 with my devops security company, EnvKey, which I continue to run today. I'm fascinated by LLMs and their potential to transform the practice of software development.
+Hi, I'm Dane. I've been building and launching software products for 17 years. I went through YCombinator in winter 2018 with my devops security company, [EnvKey](https://envkey.com), which I continue to run today. I'm fascinated by LLMs and their potential to transform the practice of software development.
I live with my wife and 4 year old daughter on the SF peninsula in California. I grew up in the Finger Lakes region of upstate New York. I like reading fiction, listening to podcasts, fitness, and surfing. I started Brazilian Jiu-Jitsu recently and am pretty absorbed with that these days as well.
diff --git a/app/server/.gitignore b/app/server/.gitignore
new file mode 100644
index 00000000..a703ae48
--- /dev/null
+++ b/app/server/.gitignore
@@ -0,0 +1 @@
+cloud/
\ No newline at end of file
diff --git a/app/Dockerfile.server b/app/server/Dockerfile
similarity index 100%
rename from app/Dockerfile.server
rename to app/server/Dockerfile
diff --git a/app/server/db/db.go b/app/server/db/db.go
index d2f585b8..c5d63969 100644
--- a/app/server/db/db.go
+++ b/app/server/db/db.go
@@ -53,6 +53,14 @@ func Connect() error {
}
func MigrationsUp() error {
+ return migrationsUp("migrations")
+}
+
+func MigrationsUpWithDir(dir string) error {
+ return migrationsUp(dir)
+}
+
+func migrationsUp(dir string) error {
if Conn == nil {
return errors.New("db not initialized")
}
@@ -64,7 +72,7 @@ func MigrationsUp() error {
}
m, err := migrate.NewWithDatabaseInstance(
- "file://migrations",
+ "file://"+dir,
"postgres", driver)
if err != nil {
diff --git a/app/server/handlers/accounts.go b/app/server/handlers/accounts.go
index 06ab3d39..1839a6aa 100644
--- a/app/server/handlers/accounts.go
+++ b/app/server/handlers/accounts.go
@@ -2,130 +2,16 @@ package handlers
import (
"encoding/json"
- "fmt"
"io"
"log"
"net/http"
"plandex-server/db"
+ "plandex-server/hooks"
"strings"
"github.com/plandex/plandex/shared"
)
-func StartTrialHandler(w http.ResponseWriter, r *http.Request) {
- log.Println("Received request for StartTrialHandler")
-
- // start a transaction
- tx, err := db.Conn.Begin()
- if err != nil {
- log.Printf("Error starting transaction: %v\n", err)
- http.Error(w, "Error starting transaction: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- // Ensure that rollback is attempted in case of failure
- defer func() {
- if err != nil {
- if rbErr := tx.Rollback(); rbErr != nil {
- log.Printf("transaction rollback error: %v\n", rbErr)
- } else {
- log.Println("transaction rolled back")
- }
- }
- }()
-
- b, err := shared.GetRandomAlphanumeric(6)
- if err != nil {
- log.Printf("Error generating random tag: %v\n", err)
- http.Error(w, "Error generating random tag: "+err.Error(), http.StatusInternalServerError)
- return
- }
- tag := fmt.Sprintf("%x", b)
- tag = strings.ToLower(tag)
-
- user := &db.User{
- Name: "Trial User " + tag,
- Email: tag + "@trial.plandex.ai",
- Domain: "trial.plandex.ai",
- IsTrial: true,
- }
- err = db.CreateUser(user, tx)
-
- if err != nil {
- log.Printf("Error creating user: %v\n", err)
- http.Error(w, "Error creating user: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- userId := user.Id
-
- // create a new org
- var orgId string
- orgName := "Trial Org " + tag
- err = tx.QueryRow("INSERT INTO orgs (name, owner_id, is_trial) VALUES ($1, $2, true) RETURNING id", orgName, userId).Scan(&orgId)
-
- if err != nil {
- log.Printf("Error creating org: %v\n", err)
- http.Error(w, "Error creating org: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- // get org owner role id
- orgOwnerRoleId, err := db.GetOrgOwnerRoleId()
-
- if err != nil {
- log.Printf("Error getting org owner role: %v\n", err)
- http.Error(w, "Error getting org owner role: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- // insert org user
- err = db.CreateOrgUser(orgId, userId, orgOwnerRoleId, tx)
- if err != nil {
- log.Printf("Error inserting org user: %v\n", err)
- http.Error(w, "Error inserting org user: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- // create auth token
- token, _, err := db.CreateAuthToken(userId, true, tx)
-
- if err != nil {
- log.Printf("Error creating auth token: %v\n", err)
- http.Error(w, "Error creating auth token: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- // commit transaction
- err = tx.Commit()
- if err != nil {
- log.Printf("Error committing transaction: %v\n", err)
- http.Error(w, "Error committing transaction: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- resp := shared.StartTrialResponse{
- UserId: userId,
- OrgId: orgId,
- Token: token,
- UserName: user.Name,
- OrgName: orgName,
- Email: user.Email,
- }
-
- bytes, err := json.Marshal(resp)
-
- if err != nil {
- log.Printf("Error marshalling response: %v\n", err)
- http.Error(w, "Error marshalling response: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- log.Println("Successfully started trial")
-
- w.Write(bytes)
-}
-
func CreateAccountHandler(w http.ResponseWriter, r *http.Request) {
log.Println("Received request for CreateAccountHandler")
@@ -249,167 +135,12 @@ func CreateAccountHandler(w http.ResponseWriter, r *http.Request) {
}
}
- // commit transaction
- err = tx.Commit()
+ err = hooks.ExecHook("create_account", hooks.HookParams{
+ W: w,
+ User: &user,
+ OrgId: org.Id,
+ })
if err != nil {
- log.Printf("Error committing transaction: %v\n", err)
- http.Error(w, "Error committing transaction: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- // get orgs
- orgs, err := db.GetAccessibleOrgsForUser(&user)
-
- if err != nil {
- log.Printf("Error getting orgs for user: %v\n", err)
- http.Error(w, "Error getting orgs for user: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- var apiOrgs []*shared.Org
- for _, org := range orgs {
- apiOrgs = append(apiOrgs, org.ToApi())
- }
-
- resp := shared.SessionResponse{
- UserId: userId,
- Token: token,
- Email: req.Email,
- UserName: req.UserName,
- Orgs: apiOrgs,
- }
-
- bytes, err := json.Marshal(resp)
-
- if err != nil {
- log.Printf("Error marshalling response: %v\n", err)
- http.Error(w, "Error marshalling response: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- log.Println("Successfully created account")
-
- w.Write(bytes)
-}
-
-func ConvertTrialHandler(w http.ResponseWriter, r *http.Request) {
- log.Println("Received request for ConvertTrialHandler")
-
- auth := authenticate(w, r, true)
- if auth == nil {
- return
- }
-
- if !auth.User.IsTrial {
- log.Println("Trial isn't active")
- http.Error(w, "Trial isn't active", http.StatusBadRequest)
- return
- }
-
- var req shared.ConvertTrialRequest
- err := json.NewDecoder(r.Body).Decode(&req)
- if err != nil {
- log.Printf("Error unmarshalling request: %v\n", err)
- http.Error(w, "Error unmarshalling request: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- emailVerificationId, err := db.ValidateEmailVerification(req.Email, req.Pin)
-
- if err != nil {
- log.Printf("Error validating email verification: %v\n", err)
- http.Error(w, "Error validating email verification: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- emailSplit := strings.Split(req.Email, "@")
- if len(emailSplit) != 2 {
- log.Printf("Invalid email: %v\n", req.Email)
- http.Error(w, "Invalid email: "+req.Email, http.StatusBadRequest)
- return
- }
- userDomain := emailSplit[1]
- var domain *string
- if req.OrgAutoAddDomainUsers {
- if shared.IsEmailServiceDomain(userDomain) {
- log.Printf("Invalid domain: %v\n", userDomain)
- http.Error(w, "Invalid domain: "+userDomain, http.StatusBadRequest)
- return
- }
-
- domain = &userDomain
- }
-
- // start a transaction
- tx, err := db.Conn.Begin()
- if err != nil {
- log.Printf("Error starting transaction: %v\n", err)
- http.Error(w, "Error starting transaction: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- // Ensure that rollback is attempted in case of failure
- defer func() {
- if err != nil {
- if rbErr := tx.Rollback(); rbErr != nil {
- log.Printf("transaction rollback error: %v\n", rbErr)
- } else {
- log.Println("transaction rolled back")
- }
- }
- }()
-
- // clear current auth token
- _, err = db.Conn.Exec("UPDATE auth_tokens SET deleted_at = NOW() WHERE token_hash = $1", auth.AuthToken.TokenHash)
-
- if err != nil {
- log.Printf("Error deleting auth token: %v\n", err)
- http.Error(w, "Error deleting auth token: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- _, err = tx.Exec("UPDATE users SET name = $1, email = $2, domain = $3, is_trial = false WHERE id = $4", req.UserName, req.Email, userDomain, auth.User.Id)
-
- if err != nil {
- if db.IsNonUniqueErr(err) {
- log.Printf("User already exists for email: %v\n", req.Email)
- http.Error(w, "User already exists for email: "+req.Email, http.StatusConflict)
- return
- }
- log.Printf("Error updating user: %v\n", err)
- http.Error(w, "Error updating user: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- // create auth token
- token, authTokenId, err := db.CreateAuthToken(auth.User.Id, false, tx)
-
- if err != nil {
- log.Printf("Error creating auth token: %v\n", err)
- http.Error(w, "Error creating auth token: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- // update email verification with user and auth token ids
- _, err = tx.Exec("UPDATE email_verifications SET user_id = $1, auth_token_id = $2 WHERE id = $3", auth.User.Id, authTokenId, emailVerificationId)
-
- if err != nil {
- log.Printf("Error updating email verification: %v\n", err)
- http.Error(w, "Error updating email verification: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- // update org
- _, err = tx.Exec("UPDATE orgs SET name = $1, domain = $2, auto_add_domain_users = $3, is_trial = false WHERE id = $4", req.OrgName, domain, req.OrgAutoAddDomainUsers, auth.OrgId)
-
- if err != nil {
- if db.IsNonUniqueErr(err) {
- log.Printf("Org already exists for domain: %v\n", userDomain)
- http.Error(w, "Org already exists for domain: "+userDomain, http.StatusConflict)
- return
- }
- log.Printf("Error updating org: %v\n", err)
- http.Error(w, "Error updating org: "+err.Error(), http.StatusInternalServerError)
return
}
@@ -422,7 +153,7 @@ func ConvertTrialHandler(w http.ResponseWriter, r *http.Request) {
}
// get orgs
- orgs, err := db.GetAccessibleOrgsForUser(auth.User)
+ orgs, err := db.GetAccessibleOrgsForUser(&user)
if err != nil {
log.Printf("Error getting orgs for user: %v\n", err)
@@ -436,7 +167,7 @@ func ConvertTrialHandler(w http.ResponseWriter, r *http.Request) {
}
resp := shared.SessionResponse{
- UserId: auth.User.Id,
+ UserId: userId,
Token: token,
Email: req.Email,
UserName: req.UserName,
@@ -451,7 +182,7 @@ func ConvertTrialHandler(w http.ResponseWriter, r *http.Request) {
return
}
- log.Println("Successfully converted trial")
+ log.Println("Successfully created account")
w.Write(bytes)
}
diff --git a/app/server/handlers/auth_helpers.go b/app/server/handlers/auth_helpers.go
index 4dc34401..6f76959b 100644
--- a/app/server/handlers/auth_helpers.go
+++ b/app/server/handlers/auth_helpers.go
@@ -12,7 +12,7 @@ import (
"github.com/plandex/plandex/shared"
)
-func authenticate(w http.ResponseWriter, r *http.Request, requireOrg bool) *types.ServerAuth {
+func Authenticate(w http.ResponseWriter, r *http.Request, requireOrg bool) *types.ServerAuth {
log.Println("authenticating request")
authHeader := r.Header.Get("Authorization")
@@ -57,7 +57,7 @@ func authenticate(w http.ResponseWriter, r *http.Request, requireOrg bool) *type
if err != nil {
log.Printf("error validating auth token: %v\n", err)
- writeApiError(w, shared.ApiError{
+ WriteApiError(w, shared.ApiError{
Type: shared.ApiErrorTypeInvalidToken,
Status: http.StatusUnauthorized,
Msg: "Invalid auth token",
diff --git a/app/server/handlers/branches.go b/app/server/handlers/branches.go
index 34b39e1f..6975c7f1 100644
--- a/app/server/handlers/branches.go
+++ b/app/server/handlers/branches.go
@@ -15,7 +15,7 @@ import (
func ListBranchesHandler(w http.ResponseWriter, r *http.Request) {
log.Println("Received request for ListBranchesHandler")
- auth := authenticate(w, r, true)
+ auth := Authenticate(w, r, true)
if auth == nil {
return
}
@@ -63,7 +63,7 @@ func ListBranchesHandler(w http.ResponseWriter, r *http.Request) {
func CreateBranchHandler(w http.ResponseWriter, r *http.Request) {
log.Println("Received request for CreateBranchHandler")
- auth := authenticate(w, r, true)
+ auth := Authenticate(w, r, true)
if auth == nil {
return
}
@@ -152,7 +152,7 @@ func CreateBranchHandler(w http.ResponseWriter, r *http.Request) {
func DeleteBranchHandler(w http.ResponseWriter, r *http.Request) {
log.Println("Received request for DeleteBranchHandler")
- auth := authenticate(w, r, true)
+ auth := Authenticate(w, r, true)
if auth == nil {
return
}
diff --git a/app/server/handlers/err_helper.go b/app/server/handlers/err_helper.go
index 276b6157..8f8b18d8 100644
--- a/app/server/handlers/err_helper.go
+++ b/app/server/handlers/err_helper.go
@@ -8,7 +8,7 @@ import (
"github.com/plandex/plandex/shared"
)
-func writeApiError(w http.ResponseWriter, apiErr shared.ApiError) {
+func WriteApiError(w http.ResponseWriter, apiErr shared.ApiError) {
bytes, err := json.Marshal(apiErr)
if err != nil {
log.Printf("Error marshalling response: %v\n", err)
diff --git a/app/server/handlers/invites.go b/app/server/handlers/invites.go
index e34883f0..a4c2132a 100644
--- a/app/server/handlers/invites.go
+++ b/app/server/handlers/invites.go
@@ -14,13 +14,13 @@ import (
func InviteUserHandler(w http.ResponseWriter, r *http.Request) {
log.Println("Received a request for InviteUserHandler")
- auth := authenticate(w, r, true)
+ auth := Authenticate(w, r, true)
if auth == nil {
return
}
if auth.User.IsTrial {
- writeApiError(w, shared.ApiError{
+ WriteApiError(w, shared.ApiError{
Type: shared.ApiErrorTypeTrialActionNotAllowed,
Status: http.StatusForbidden,
Msg: "Anonymous trial user can't invite other users",
@@ -129,13 +129,13 @@ func InviteUserHandler(w http.ResponseWriter, r *http.Request) {
func ListPendingInvitesHandler(w http.ResponseWriter, r *http.Request) {
log.Println("Received a request for ListInvitesHandler")
- auth := authenticate(w, r, true)
+ auth := Authenticate(w, r, true)
if auth == nil {
return
}
if auth.User.IsTrial {
- writeApiError(w, shared.ApiError{
+ WriteApiError(w, shared.ApiError{
Type: shared.ApiErrorTypeTrialActionNotAllowed,
Status: http.StatusForbidden,
Msg: "Anonymous trial user can't list invites",
@@ -170,13 +170,13 @@ func ListPendingInvitesHandler(w http.ResponseWriter, r *http.Request) {
func ListAcceptedInvitesHandler(w http.ResponseWriter, r *http.Request) {
log.Println("Received a request for ListAcceptedInvitesHandler")
- auth := authenticate(w, r, true)
+ auth := Authenticate(w, r, true)
if auth == nil {
return
}
if auth.User.IsTrial {
- writeApiError(w, shared.ApiError{
+ WriteApiError(w, shared.ApiError{
Type: shared.ApiErrorTypeTrialActionNotAllowed,
Status: http.StatusForbidden,
Msg: "Anonymous trial user can't list invites",
@@ -211,13 +211,13 @@ func ListAcceptedInvitesHandler(w http.ResponseWriter, r *http.Request) {
func ListAllInvitesHandler(w http.ResponseWriter, r *http.Request) {
log.Println("Received a request for ListAllInvitesHandler")
- auth := authenticate(w, r, true)
+ auth := Authenticate(w, r, true)
if auth == nil {
return
}
if auth.User.IsTrial {
- writeApiError(w, shared.ApiError{
+ WriteApiError(w, shared.ApiError{
Type: shared.ApiErrorTypeTrialActionNotAllowed,
Status: http.StatusForbidden,
Msg: "Anonymous trial user can't list invites",
@@ -252,13 +252,13 @@ func ListAllInvitesHandler(w http.ResponseWriter, r *http.Request) {
func DeleteInviteHandler(w http.ResponseWriter, r *http.Request) {
log.Println("Received a request for DeleteInviteHandler")
- auth := authenticate(w, r, true)
+ auth := Authenticate(w, r, true)
if auth == nil {
return
}
if auth.User.IsTrial {
- writeApiError(w, shared.ApiError{
+ WriteApiError(w, shared.ApiError{
Type: shared.ApiErrorTypeTrialActionNotAllowed,
Status: http.StatusForbidden,
Msg: "Anonymous trial user can't delete invites",
diff --git a/app/server/handlers/orgs.go b/app/server/handlers/orgs.go
index 28021fcf..ec1ab07d 100644
--- a/app/server/handlers/orgs.go
+++ b/app/server/handlers/orgs.go
@@ -14,7 +14,7 @@ import (
func ListOrgsHandler(w http.ResponseWriter, r *http.Request) {
log.Println("Received request for ListOrgsHandler")
- auth := authenticate(w, r, false)
+ auth := Authenticate(w, r, false)
if auth == nil {
return
}
@@ -48,13 +48,13 @@ func ListOrgsHandler(w http.ResponseWriter, r *http.Request) {
func CreateOrgHandler(w http.ResponseWriter, r *http.Request) {
log.Println("Received request for CreateOrgHandler")
- auth := authenticate(w, r, false)
+ auth := Authenticate(w, r, false)
if auth == nil {
return
}
if auth.User.IsTrial {
- writeApiError(w, shared.ApiError{
+ WriteApiError(w, shared.ApiError{
Type: shared.ApiErrorTypeTrialActionNotAllowed,
Status: http.StatusForbidden,
Msg: "Anonymous trial user can't create org",
@@ -155,13 +155,13 @@ func CreateOrgHandler(w http.ResponseWriter, r *http.Request) {
func ListOrgRolesHandler(w http.ResponseWriter, r *http.Request) {
log.Println("Received request for ListOrgRolesHandler")
- auth := authenticate(w, r, true)
+ auth := Authenticate(w, r, true)
if auth == nil {
return
}
if auth.User.IsTrial {
- writeApiError(w, shared.ApiError{
+ WriteApiError(w, shared.ApiError{
Type: shared.ApiErrorTypeTrialActionNotAllowed,
Status: http.StatusForbidden,
Msg: "Anonymous trial user can't list org roles",
diff --git a/app/server/handlers/plans_changes.go b/app/server/handlers/plans_changes.go
index c056ea1d..c183a8aa 100644
--- a/app/server/handlers/plans_changes.go
+++ b/app/server/handlers/plans_changes.go
@@ -14,7 +14,7 @@ import (
func CurrentPlanHandler(w http.ResponseWriter, r *http.Request) {
log.Println("Received request for CurrentPlanHandler")
- auth := authenticate(w, r, true)
+ auth := Authenticate(w, r, true)
if auth == nil {
return
}
@@ -65,7 +65,7 @@ func CurrentPlanHandler(w http.ResponseWriter, r *http.Request) {
func ApplyPlanHandler(w http.ResponseWriter, r *http.Request) {
log.Println("Received request for ApplyPlanHandler")
- auth := authenticate(w, r, true)
+ auth := Authenticate(w, r, true)
if auth == nil {
return
}
@@ -103,7 +103,7 @@ func ApplyPlanHandler(w http.ResponseWriter, r *http.Request) {
func RejectAllChangesHandler(w http.ResponseWriter, r *http.Request) {
log.Println("Received request for RejectAllChangesHandler")
- auth := authenticate(w, r, true)
+ auth := Authenticate(w, r, true)
if auth == nil {
return
}
@@ -139,7 +139,7 @@ func RejectAllChangesHandler(w http.ResponseWriter, r *http.Request) {
func RejectResultHandler(w http.ResponseWriter, r *http.Request) {
log.Println("Received request for RejectResultHandler")
- auth := authenticate(w, r, true)
+ auth := Authenticate(w, r, true)
if auth == nil {
return
}
@@ -177,7 +177,7 @@ func RejectResultHandler(w http.ResponseWriter, r *http.Request) {
func RejectReplacementHandler(w http.ResponseWriter, r *http.Request) {
log.Println("Received request for RejectReplacementHandler")
- auth := authenticate(w, r, true)
+ auth := Authenticate(w, r, true)
if auth == nil {
return
}
@@ -214,7 +214,7 @@ func RejectReplacementHandler(w http.ResponseWriter, r *http.Request) {
}
func ArchivePlanHandler(w http.ResponseWriter, r *http.Request) {
- auth := authenticate(w, r, true)
+ auth := Authenticate(w, r, true)
if auth == nil {
return
}
diff --git a/app/server/handlers/plans_context.go b/app/server/handlers/plans_context.go
index ac3bab5a..0085613c 100644
--- a/app/server/handlers/plans_context.go
+++ b/app/server/handlers/plans_context.go
@@ -15,7 +15,7 @@ import (
func ListContextHandler(w http.ResponseWriter, r *http.Request) {
log.Println("Received request for ListContextHandler")
- auth := authenticate(w, r, true)
+ auth := Authenticate(w, r, true)
if auth == nil {
return
}
@@ -65,7 +65,7 @@ func ListContextHandler(w http.ResponseWriter, r *http.Request) {
func LoadContextHandler(w http.ResponseWriter, r *http.Request) {
log.Println("Received request for LoadContextHandler")
- auth := authenticate(w, r, true)
+ auth := Authenticate(w, r, true)
if auth == nil {
return
}
@@ -118,7 +118,7 @@ func LoadContextHandler(w http.ResponseWriter, r *http.Request) {
func UpdateContextHandler(w http.ResponseWriter, r *http.Request) {
log.Println("Received request for UpdateContextHandler")
- auth := authenticate(w, r, true)
+ auth := Authenticate(w, r, true)
if auth == nil {
return
}
@@ -208,7 +208,7 @@ func UpdateContextHandler(w http.ResponseWriter, r *http.Request) {
func DeleteContextHandler(w http.ResponseWriter, r *http.Request) {
log.Println("Received request for DeleteContextHandler")
- auth := authenticate(w, r, true)
+ auth := Authenticate(w, r, true)
if auth == nil {
return
}
diff --git a/app/server/handlers/plans_convo.go b/app/server/handlers/plans_convo.go
index 68b51c0a..e6a3c43b 100644
--- a/app/server/handlers/plans_convo.go
+++ b/app/server/handlers/plans_convo.go
@@ -12,7 +12,7 @@ import (
func ListConvoHandler(w http.ResponseWriter, r *http.Request) {
log.Println("Received a request for ListConvoHandler")
- auth := authenticate(w, r, true)
+ auth := Authenticate(w, r, true)
if auth == nil {
return
}
diff --git a/app/server/handlers/plans_crud.go b/app/server/handlers/plans_crud.go
index b2762997..88c9157a 100644
--- a/app/server/handlers/plans_crud.go
+++ b/app/server/handlers/plans_crud.go
@@ -6,8 +6,8 @@ import (
"io"
"log"
"net/http"
- "os"
"plandex-server/db"
+ "plandex-server/hooks"
"plandex-server/types"
"sort"
"strings"
@@ -20,7 +20,7 @@ import (
func CreatePlanHandler(w http.ResponseWriter, r *http.Request) {
log.Println("Received request for CreatePlanHandler")
- auth := authenticate(w, r, true)
+ auth := Authenticate(w, r, true)
if auth == nil {
return
}
@@ -40,28 +40,9 @@ func CreatePlanHandler(w http.ResponseWriter, r *http.Request) {
return
}
- if os.Getenv("IS_CLOUD") != "" {
- user, err := db.GetUser(auth.User.Id)
-
- if err != nil {
- log.Printf("Error getting user: %v\n", err)
- http.Error(w, "Error getting user: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- if user.IsTrial {
- if user.NumNonDraftPlans >= types.TrialMaxPlans {
- writeApiError(w, shared.ApiError{
- Type: shared.ApiErrorTypeTrialPlansExceeded,
- Status: http.StatusForbidden,
- Msg: "User has reached max number of anonymous trial plans",
- TrialPlansExceededError: &shared.TrialPlansExceededError{
- MaxPlans: types.TrialMaxPlans,
- },
- })
- return
- }
- }
+ err := hooks.ExecHook("will_create_plan", hooks.HookParams{W: w, User: auth.User})
+ if err != nil {
+ return
}
// read the request body
@@ -145,7 +126,7 @@ func CreatePlanHandler(w http.ResponseWriter, r *http.Request) {
func GetPlanHandler(w http.ResponseWriter, r *http.Request) {
log.Println("Received request for GetPlanHandler")
- auth := authenticate(w, r, true)
+ auth := Authenticate(w, r, true)
if auth == nil {
return
}
@@ -175,7 +156,7 @@ func GetPlanHandler(w http.ResponseWriter, r *http.Request) {
func DeletePlanHandler(w http.ResponseWriter, r *http.Request) {
log.Println("Received request for DeletePlanHandler")
- auth := authenticate(w, r, true)
+ auth := Authenticate(w, r, true)
if auth == nil {
return
}
@@ -232,7 +213,7 @@ func DeletePlanHandler(w http.ResponseWriter, r *http.Request) {
func DeleteAllPlansHandler(w http.ResponseWriter, r *http.Request) {
log.Println("Received request for DeleteAllPlansHandler")
- auth := authenticate(w, r, true)
+ auth := Authenticate(w, r, true)
if auth == nil {
return
}
@@ -260,7 +241,7 @@ func DeleteAllPlansHandler(w http.ResponseWriter, r *http.Request) {
func ListPlansHandler(w http.ResponseWriter, r *http.Request) {
log.Println("Received request for ListPlans")
- auth := authenticate(w, r, true)
+ auth := Authenticate(w, r, true)
if auth == nil {
return
}
@@ -307,7 +288,7 @@ func ListPlansHandler(w http.ResponseWriter, r *http.Request) {
func ListArchivedPlansHandler(w http.ResponseWriter, r *http.Request) {
log.Println("Received request for ListArchivedPlansHandler")
- auth := authenticate(w, r, true)
+ auth := Authenticate(w, r, true)
if auth == nil {
return
}
@@ -355,7 +336,7 @@ func ListArchivedPlansHandler(w http.ResponseWriter, r *http.Request) {
func ListPlansRunningHandler(w http.ResponseWriter, r *http.Request) {
log.Println("Received request for ListPlansRunningHandler")
- auth := authenticate(w, r, true)
+ auth := Authenticate(w, r, true)
if auth == nil {
return
}
@@ -513,7 +494,7 @@ func ListPlansRunningHandler(w http.ResponseWriter, r *http.Request) {
func GetCurrentBranchByPlanIdHandler(w http.ResponseWriter, r *http.Request) {
log.Println("Received request for CurrentBranchByPlanIdHandler")
- auth := authenticate(w, r, true)
+ auth := Authenticate(w, r, true)
if auth == nil {
return
}
diff --git a/app/server/handlers/plans_exec.go b/app/server/handlers/plans_exec.go
index 05b335d5..d02b74b3 100644
--- a/app/server/handlers/plans_exec.go
+++ b/app/server/handlers/plans_exec.go
@@ -6,8 +6,8 @@ import (
"io"
"log"
"net/http"
- "os"
"plandex-server/db"
+ "plandex-server/hooks"
"plandex-server/model"
modelPlan "plandex-server/model/plan"
"plandex-server/types"
@@ -22,7 +22,7 @@ const TrialMaxReplies = 10
func TellPlanHandler(w http.ResponseWriter, r *http.Request) {
log.Println("Received request for TellPlanHandler")
- auth := authenticate(w, r, true)
+ auth := Authenticate(w, r, true)
if auth == nil {
return
}
@@ -62,28 +62,13 @@ func TellPlanHandler(w http.ResponseWriter, r *http.Request) {
return
}
- if os.Getenv("IS_CLOUD") != "" {
- user, err := db.GetUser(auth.User.Id)
-
- if err != nil {
- log.Printf("Error getting user: %v\n", err)
- http.Error(w, "Error getting user: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- if user.IsTrial {
- if plan.TotalReplies >= types.TrialMaxReplies {
- writeApiError(w, shared.ApiError{
- Type: shared.ApiErrorTypeTrialMessagesExceeded,
- Status: http.StatusForbidden,
- Msg: "Anonymous trial message limit exceeded",
- TrialMessagesExceededError: &shared.TrialMessagesExceededError{
- MaxReplies: types.TrialMaxReplies,
- },
- })
- return
- }
- }
+ err = hooks.ExecHook("will_tell_plan", hooks.HookParams{
+ W: w,
+ User: auth.User,
+ Plan: plan,
+ })
+ if err != nil {
+ return
}
client := model.NewClient(requestBody.ApiKey)
@@ -104,7 +89,7 @@ func TellPlanHandler(w http.ResponseWriter, r *http.Request) {
func BuildPlanHandler(w http.ResponseWriter, r *http.Request) {
log.Println("Received request for BuildPlanHandler")
- auth := authenticate(w, r, true)
+ auth := Authenticate(w, r, true)
if auth == nil {
return
}
@@ -189,7 +174,7 @@ func ConnectPlanHandler(w http.ResponseWriter, r *http.Request) {
return
}
- auth := authenticate(w, r, true)
+ auth := Authenticate(w, r, true)
if auth == nil {
log.Println("No auth")
return
@@ -227,7 +212,7 @@ func StopPlanHandler(w http.ResponseWriter, r *http.Request) {
return
}
- auth := authenticate(w, r, true)
+ auth := Authenticate(w, r, true)
if auth == nil {
return
}
@@ -289,7 +274,7 @@ func RespondMissingFileHandler(w http.ResponseWriter, r *http.Request) {
return
}
- auth := authenticate(w, r, true)
+ auth := Authenticate(w, r, true)
if auth == nil {
return
}
diff --git a/app/server/handlers/plans_versions.go b/app/server/handlers/plans_versions.go
index 23d7ae3f..e4b585f5 100644
--- a/app/server/handlers/plans_versions.go
+++ b/app/server/handlers/plans_versions.go
@@ -15,7 +15,7 @@ import (
func ListLogsHandler(w http.ResponseWriter, r *http.Request) {
log.Println("Received request for ListLogsHandler")
- auth := authenticate(w, r, true)
+ auth := Authenticate(w, r, true)
if auth == nil {
return
}
@@ -68,7 +68,7 @@ func ListLogsHandler(w http.ResponseWriter, r *http.Request) {
func RewindPlanHandler(w http.ResponseWriter, r *http.Request) {
log.Println("Received request for RewindPlanHandler")
- auth := authenticate(w, r, true)
+ auth := Authenticate(w, r, true)
if auth == nil {
return
}
diff --git a/app/server/handlers/projects.go b/app/server/handlers/projects.go
index 146ef823..0004b0d0 100644
--- a/app/server/handlers/projects.go
+++ b/app/server/handlers/projects.go
@@ -14,7 +14,7 @@ import (
func CreateProjectHandler(w http.ResponseWriter, r *http.Request) {
log.Println("Received request for CreateProjectHandler")
- auth := authenticate(w, r, true)
+ auth := Authenticate(w, r, true)
if auth == nil {
return
}
@@ -104,7 +104,7 @@ func CreateProjectHandler(w http.ResponseWriter, r *http.Request) {
func ListProjectsHandler(w http.ResponseWriter, r *http.Request) {
log.Println("Received request for ListProjectsHandler")
- auth := authenticate(w, r, true)
+ auth := Authenticate(w, r, true)
if auth == nil {
return
}
@@ -142,7 +142,7 @@ func ListProjectsHandler(w http.ResponseWriter, r *http.Request) {
func ProjectSetPlanHandler(w http.ResponseWriter, r *http.Request) {
log.Println("Received request for UpdateProjectSetPlanHandler")
- auth := authenticate(w, r, true)
+ auth := Authenticate(w, r, true)
if auth == nil {
return
}
@@ -191,7 +191,7 @@ func ProjectSetPlanHandler(w http.ResponseWriter, r *http.Request) {
func RenameProjectHandler(w http.ResponseWriter, r *http.Request) {
log.Println("Received request for RenameProjectHandler")
- auth := authenticate(w, r, true)
+ auth := Authenticate(w, r, true)
if auth == nil {
return
}
diff --git a/app/server/handlers/sessions.go b/app/server/handlers/sessions.go
index 20c2233a..38579b3b 100644
--- a/app/server/handlers/sessions.go
+++ b/app/server/handlers/sessions.go
@@ -226,7 +226,7 @@ func SignInHandler(w http.ResponseWriter, r *http.Request) {
func SignOutHandler(w http.ResponseWriter, r *http.Request) {
log.Println("Received request for SignOutHandler")
- auth := authenticate(w, r, false)
+ auth := Authenticate(w, r, false)
if auth == nil {
return
}
diff --git a/app/server/handlers/settings.go b/app/server/handlers/settings.go
index 5af56969..731f0f87 100644
--- a/app/server/handlers/settings.go
+++ b/app/server/handlers/settings.go
@@ -18,7 +18,7 @@ import (
func GetSettingsHandler(w http.ResponseWriter, r *http.Request) {
log.Println("Received request for GetSettingsHandler")
- auth := authenticate(w, r, true)
+ auth := Authenticate(w, r, true)
if auth == nil {
return
}
@@ -67,7 +67,7 @@ func GetSettingsHandler(w http.ResponseWriter, r *http.Request) {
func UpdateSettingsHandler(w http.ResponseWriter, r *http.Request) {
log.Println("Received request for UpdateSettingsHandler")
- auth := authenticate(w, r, true)
+ auth := Authenticate(w, r, true)
if auth == nil {
return
}
diff --git a/app/server/handlers/users.go b/app/server/handlers/users.go
index 25466e5b..4bf6256d 100644
--- a/app/server/handlers/users.go
+++ b/app/server/handlers/users.go
@@ -14,13 +14,13 @@ import (
func ListUsersHandler(w http.ResponseWriter, r *http.Request) {
log.Println("Received a request for ListUsersHandler")
- auth := authenticate(w, r, true)
+ auth := Authenticate(w, r, true)
if auth == nil {
return
}
if auth.User.IsTrial {
- writeApiError(w, shared.ApiError{
+ WriteApiError(w, shared.ApiError{
Type: shared.ApiErrorTypeTrialActionNotAllowed,
Status: http.StatusForbidden,
Msg: "Anonymous trial user can't list users",
@@ -49,13 +49,13 @@ func ListUsersHandler(w http.ResponseWriter, r *http.Request) {
func DeleteOrgUserHandler(w http.ResponseWriter, r *http.Request) {
log.Println("Received a request for DeleteOrgUserHandler")
- auth := authenticate(w, r, true)
+ auth := Authenticate(w, r, true)
if auth == nil {
return
}
if auth.User.IsTrial {
- writeApiError(w, shared.ApiError{
+ WriteApiError(w, shared.ApiError{
Type: shared.ApiErrorTypeTrialActionNotAllowed,
Status: http.StatusForbidden,
Msg: "Anonymous trial user can't delete users",
diff --git a/app/server/hooks/hooks.go b/app/server/hooks/hooks.go
new file mode 100644
index 00000000..07c471c5
--- /dev/null
+++ b/app/server/hooks/hooks.go
@@ -0,0 +1,32 @@
+package hooks
+
+import (
+ "net/http"
+ "plandex-server/db"
+
+ "github.com/plandex/plandex/shared"
+)
+
+type HookParams struct {
+ W http.ResponseWriter
+ User *db.User
+ OrgId string
+ Plan *db.Plan
+ StreamDoneCh chan *shared.ApiError
+}
+
+type Hook func(params HookParams) error
+
+var hooks = make(map[string]Hook)
+
+func RegisterHook(name string, hook Hook) {
+ hooks[name] = hook
+}
+
+func ExecHook(name string, params HookParams) error {
+ hook, ok := hooks[name]
+ if !ok {
+ return nil
+ }
+ return hook(params)
+}
diff --git a/app/server/main.go b/app/server/main.go
index 34708e18..cbe4085f 100644
--- a/app/server/main.go
+++ b/app/server/main.go
@@ -1,69 +1,14 @@
package main
import (
- "fmt"
- "log"
- "net/http"
- "os"
- "os/signal"
- "plandex-server/db"
- "plandex-server/host"
- "plandex-server/model/plan"
- "syscall"
- "time"
+ "plandex-server/setup"
"github.com/gorilla/mux"
)
func main() {
- err := host.LoadIp()
- if err != nil {
- log.Fatal("Error loading IP: ", err)
- }
-
- err = db.Connect()
- if err != nil {
- log.Fatal("Error initializing database: ", err)
- }
-
- err = db.MigrationsUp()
- if err != nil {
- log.Fatal("Error running migrations: ", err)
- }
-
- // Get externalPort from the environment variable or default to 8088
- externalPort := os.Getenv("PORT")
- if externalPort == "" {
- externalPort = "8088"
- }
-
- go startServer(externalPort, routes())
- log.Println("Started server on port " + externalPort)
-
- sigTermChan := make(chan os.Signal, 1)
- signal.Notify(sigTermChan, syscall.SIGTERM)
-
- go func() {
- <-sigTermChan
-
- for {
- l := plan.NumActivePlans()
- if l == 0 {
- break
- }
- log.Printf("Waiting for %d active plans to finish...\n", l)
- time.Sleep(1 * time.Second)
- }
-
- os.Exit(0)
- }()
-
- select {}
-}
-
-func startServer(port string, routes *mux.Router) {
- err := http.ListenAndServe(fmt.Sprintf(":%s", port), routes)
- if err != nil {
- log.Fatalf("Failed to start server on port %s: %v", port, err)
- }
+ r := mux.NewRouter()
+ setup.MustLoadIp()
+ setup.MustInitDb()
+ setup.StartServer(r)
}
diff --git a/app/server/model/plan/tell_exec.go b/app/server/model/plan/tell_exec.go
index 7263a030..15b6a8f5 100644
--- a/app/server/model/plan/tell_exec.go
+++ b/app/server/model/plan/tell_exec.go
@@ -4,9 +4,9 @@ import (
"fmt"
"log"
"net/http"
- "os"
"plandex-server/db"
+ "plandex-server/hooks"
"plandex-server/model"
"plandex-server/model/lib"
"plandex-server/model/prompts"
@@ -58,21 +58,15 @@ func execTellPlan(
active := GetActivePlan(plan.Id, branch)
- if os.Getenv("IS_CLOUD") != "" &&
- missingFileResponse == "" {
- log.Println("execTellPlan: IS_CLOUD environment variable is set")
- if auth.User.IsTrial {
- if plan.TotalReplies >= types.TrialMaxReplies {
- active.StreamDoneCh <- &shared.ApiError{
- Type: shared.ApiErrorTypeTrialMessagesExceeded,
- Status: http.StatusForbidden,
- Msg: "Anonymous trial message limit exceeded",
- TrialMessagesExceededError: &shared.TrialMessagesExceededError{
- MaxReplies: types.TrialMaxReplies,
- },
- }
- return
- }
+ if missingFileResponse == "" {
+ err := hooks.ExecHook("will_exec_plan", hooks.HookParams{
+ User: auth.User,
+ Plan: plan,
+ StreamDoneCh: active.StreamDoneCh,
+ })
+
+ if err != nil {
+ return
}
}
diff --git a/app/server/routes.go b/app/server/routes.go
index b8fc7845..e1746700 100644
--- a/app/server/routes.go
+++ b/app/server/routes.go
@@ -15,12 +15,10 @@ func routes() *mux.Router {
fmt.Fprintf(w, "OK")
})
- r.HandleFunc("/accounts/start_trial", handlers.StartTrialHandler).Methods("POST")
r.HandleFunc("/accounts/email_verifications", handlers.CreateEmailVerificationHandler).Methods("POST")
r.HandleFunc("/accounts/sign_in", handlers.SignInHandler).Methods("POST")
r.HandleFunc("/accounts/sign_out", handlers.SignOutHandler).Methods("POST")
r.HandleFunc("/accounts", handlers.CreateAccountHandler).Methods("POST")
- r.HandleFunc("/accounts/convert_trial", handlers.ConvertTrialHandler).Methods("POST")
r.HandleFunc("/orgs", handlers.ListOrgsHandler).Methods("GET")
r.HandleFunc("/orgs", handlers.CreateOrgHandler).Methods("POST")
diff --git a/app/server/routes/routes.go b/app/server/routes/routes.go
new file mode 100644
index 00000000..a035af4c
--- /dev/null
+++ b/app/server/routes/routes.go
@@ -0,0 +1,82 @@
+package routes
+
+import (
+ "fmt"
+ "net/http"
+ "plandex-server/handlers"
+
+ "github.com/gorilla/mux"
+)
+
+func AddRoutes(r *mux.Router) {
+ r.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
+ fmt.Fprintf(w, "OK")
+ })
+
+ r.HandleFunc("/accounts/email_verifications", handlers.CreateEmailVerificationHandler).Methods("POST")
+ r.HandleFunc("/accounts/sign_in", handlers.SignInHandler).Methods("POST")
+ r.HandleFunc("/accounts/sign_out", handlers.SignOutHandler).Methods("POST")
+ r.HandleFunc("/accounts", handlers.CreateAccountHandler).Methods("POST")
+
+ r.HandleFunc("/orgs", handlers.ListOrgsHandler).Methods("GET")
+ r.HandleFunc("/orgs", handlers.CreateOrgHandler).Methods("POST")
+
+ r.HandleFunc("/users", handlers.ListUsersHandler).Methods("GET")
+ r.HandleFunc("/orgs/users/{userId}", handlers.DeleteOrgUserHandler).Methods("DELETE")
+ r.HandleFunc("/orgs/roles", handlers.ListOrgRolesHandler).Methods("GET")
+
+ r.HandleFunc("/invites", handlers.InviteUserHandler).Methods("POST")
+ r.HandleFunc("/invites/pending", handlers.ListPendingInvitesHandler).Methods("GET")
+ r.HandleFunc("/invites/accepted", handlers.ListAcceptedInvitesHandler).Methods("GET")
+ r.HandleFunc("/invites/all", handlers.ListAllInvitesHandler).Methods("GET")
+ r.HandleFunc("/invites/{inviteId}", handlers.DeleteInviteHandler).Methods("DELETE")
+
+ r.HandleFunc("/projects", handlers.CreateProjectHandler).Methods("POST")
+ r.HandleFunc("/projects", handlers.ListProjectsHandler).Methods("GET")
+ r.HandleFunc("/projects/{projectId}/set_plan", handlers.ProjectSetPlanHandler).Methods("PUT")
+ r.HandleFunc("/projects/{projectId}/rename", handlers.RenameProjectHandler).Methods("PUT")
+
+ r.HandleFunc("/projects/{projectId}/plans/current_branches", handlers.GetCurrentBranchByPlanIdHandler).Methods("POST")
+
+ r.HandleFunc("/plans", handlers.ListPlansHandler).Methods("GET")
+ r.HandleFunc("/plans/archive", handlers.ListArchivedPlansHandler).Methods("GET")
+ r.HandleFunc("/plans/ps", handlers.ListPlansRunningHandler).Methods("GET")
+
+ r.HandleFunc("/projects/{projectId}/plans", handlers.CreatePlanHandler).Methods("POST")
+
+ r.HandleFunc("/projects/{projectId}/plans", handlers.CreatePlanHandler).Methods("DELETE")
+
+ r.HandleFunc("/plans/{planId}", handlers.GetPlanHandler).Methods("GET")
+ r.HandleFunc("/plans/{planId}", handlers.DeletePlanHandler).Methods("DELETE")
+
+ r.HandleFunc("/plans/{planId}/{branch}/tell", handlers.TellPlanHandler).Methods("POST")
+
+ r.HandleFunc("/plans/{planId}/{branch}/respond_missing_file", handlers.RespondMissingFileHandler).Methods("POST")
+
+ r.HandleFunc("/plans/{planId}/{branch}/build", handlers.BuildPlanHandler).Methods("PATCH")
+ r.HandleFunc("/plans/{planId}/{branch}/connect", handlers.ConnectPlanHandler).Methods("PATCH")
+ r.HandleFunc("/plans/{planId}/{branch}/stop", handlers.StopPlanHandler).Methods("DELETE")
+
+ r.HandleFunc("/plans/{planId}/{branch}/current_plan", handlers.CurrentPlanHandler).Methods("GET")
+ r.HandleFunc("/plans/{planId}/{branch}/apply", handlers.ApplyPlanHandler).Methods("PATCH")
+ r.HandleFunc("/plans/{planId}/{branch}/archive", handlers.ArchivePlanHandler).Methods("PATCH")
+ r.HandleFunc("/plans/{planId}/{branch}/reject_all", handlers.RejectAllChangesHandler).Methods("PATCH")
+ r.HandleFunc("/plans/{planId}/{branch}/results/{resultId}/reject", handlers.RejectResultHandler).Methods("PATCH")
+ r.HandleFunc("/plans/{planId}/{branch}/results/{resultId}/replacements/{replacementId}/reject", handlers.RejectReplacementHandler).Methods("PATCH")
+
+ r.HandleFunc("/plans/{planId}/{branch}/context", handlers.ListContextHandler).Methods("GET")
+ r.HandleFunc("/plans/{planId}/{branch}/context", handlers.LoadContextHandler).Methods("POST")
+ r.HandleFunc("/plans/{planId}/{branch}/context", handlers.UpdateContextHandler).Methods("PUT")
+ r.HandleFunc("/plans/{planId}/{branch}/context", handlers.DeleteContextHandler).Methods("DELETE")
+
+ r.HandleFunc("/plans/{planId}/{branch}/convo", handlers.ListConvoHandler).Methods("GET")
+ r.HandleFunc("/plans/{planId}/{branch}/rewind", handlers.RewindPlanHandler).Methods("PATCH")
+ r.HandleFunc("/plans/{planId}/{branch}/logs", handlers.ListLogsHandler).Methods("GET")
+
+ r.HandleFunc("/plans/{planId}/branches", handlers.ListBranchesHandler).Methods("GET")
+ r.HandleFunc("/plans/{planId}/branches/{branch}", handlers.DeleteBranchHandler).Methods("DELETE")
+ r.HandleFunc("/plans/{planId}/{branch}/branches", handlers.CreateBranchHandler).Methods("POST")
+
+ r.HandleFunc("/plans/{planId}/{branch}/settings", handlers.GetSettingsHandler).Methods("GET")
+ r.HandleFunc("/plans/{planId}/{branch}/settings", handlers.UpdateSettingsHandler).Methods("PUT")
+}
diff --git a/app/server/setup/setup.go b/app/server/setup/setup.go
new file mode 100644
index 00000000..239b7aa8
--- /dev/null
+++ b/app/server/setup/setup.go
@@ -0,0 +1,75 @@
+package setup
+
+import (
+ "fmt"
+ "log"
+ "net/http"
+ "os"
+ "os/signal"
+ "plandex-server/db"
+ "plandex-server/host"
+ "plandex-server/model/plan"
+ "plandex-server/routes"
+ "syscall"
+ "time"
+
+ "github.com/gorilla/mux"
+)
+
+func MustLoadIp() {
+ err := host.LoadIp()
+ if err != nil {
+ log.Fatal("Error loading IP: ", err)
+ }
+}
+
+func MustInitDb() {
+ err := db.Connect()
+ if err != nil {
+ log.Fatal("Error initializing database: ", err)
+ }
+
+ err = db.MigrationsUp()
+ if err != nil {
+ log.Fatal("Error running migrations: ", err)
+ }
+}
+
+func StartServer(r *mux.Router) {
+ // Get externalPort from the environment variable or default to 8088
+ externalPort := os.Getenv("PORT")
+ if externalPort == "" {
+ externalPort = "8088"
+ }
+
+ routes.AddRoutes(r)
+ go startServer(externalPort, r)
+ log.Println("Started server on port " + externalPort)
+
+ sigTermChan := make(chan os.Signal, 1)
+ signal.Notify(sigTermChan, syscall.SIGTERM)
+
+ go func() {
+ <-sigTermChan
+
+ for {
+ l := plan.NumActivePlans()
+ if l == 0 {
+ break
+ }
+ log.Printf("Waiting for %d active plans to finish...\n", l)
+ time.Sleep(1 * time.Second)
+ }
+
+ os.Exit(0)
+ }()
+
+ select {}
+}
+
+func startServer(port string, routes *mux.Router) {
+ err := http.ListenAndServe(fmt.Sprintf(":%s", port), routes)
+ if err != nil {
+ log.Fatalf("Failed to start server on port %s: %v", port, err)
+ }
+}
diff --git a/infra/deploy.sh b/infra/deploy.sh
index afc57541..75d187d0 100755
--- a/infra/deploy.sh
+++ b/infra/deploy.sh
@@ -74,6 +74,11 @@ else
generate_and_save_stack_tag
fi
+# If DOCKERFILE_PATH is not set, set it to the default value
+if [ -z "$DOCKERFILE_PATH" ]; then
+ export DOCKERFILE_PATH="server/Dockerfile"
+fi
+
# Function to ensure the ECR repository exists
ensure_ecr_repository_exists() {
# Check if the ECR repository exists
@@ -122,7 +127,7 @@ build_and_push_image() {
# Build the Docker image
cd ../app
- docker build -t plandex-server:$IMAGE_TAG -f Dockerfile.server .
+ docker build -t plandex-server:$IMAGE_TAG -f $DOCKERFILE_PATH .
cd -
# Tag the image for the ECR repository