Skip to content

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

moving cli/server/shared to app, working on long tasks and more robust builds

Dane Schneiderf5f50d7c2c06
diff --git a/cli/api/clients.go b/app/cli/api/clients.go
similarity index 100%
rename from cli/api/clients.go
rename to app/cli/api/clients.go
diff --git a/cli/api/errors.go b/app/cli/api/errors.go
similarity index 100%
rename from cli/api/errors.go
rename to app/cli/api/errors.go
diff --git a/cli/api/methods.go b/app/cli/api/methods.go
similarity index 99%
rename from cli/api/methods.go
rename to app/cli/api/methods.go
index a33728f8..65fb4a95 100644
--- a/cli/api/methods.go
+++ b/app/cli/api/methods.go
@@ -874,7 +874,11 @@ func (a *Api) RewindPlan(planId string, req shared.RewindPlanRequest) (*shared.R
}
func (a *Api) SignIn(req shared.SignInRequest, customHost string) (*shared.SessionResponse, *shared.ApiError) {
- serverUrl := customHost + "/accounts/sign_in"
+ host := customHost
+ if host == "" {
+ host = cloudApiHost
+ }
+ serverUrl := host + "/accounts/sign_in"
reqBytes, err := json.Marshal(req)
if err != nil {
return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error marshalling request: %v", err)}
@@ -902,7 +906,11 @@ func (a *Api) SignIn(req shared.SignInRequest, customHost string) (*shared.Sessi
}
func (a *Api) CreateAccount(req shared.CreateAccountRequest, customHost string) (*shared.SessionResponse, *shared.ApiError) {
- serverUrl := customHost + "/accounts"
+ host := customHost
+ if host == "" {
+ host = cloudApiHost
+ }
+ serverUrl := host + "/accounts"
reqBytes, err := json.Marshal(req)
if err != nil {
return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error marshalling request: %v", err)}
@@ -1206,7 +1214,11 @@ func (a *Api) DeleteInvite(inviteId string) *shared.ApiError {
}
func (a *Api) CreateEmailVerification(email, customHost, userId string) (*shared.CreateEmailVerificationResponse, *shared.ApiError) {
- serverUrl := customHost + "/accounts/email_verifications"
+ host := customHost
+ if host == "" {
+ host = cloudApiHost
+ }
+ serverUrl := host + "/accounts/email_verifications"
req := shared.CreateEmailVerificationRequest{Email: email, UserId: userId}
reqBytes, err := json.Marshal(req)
if err != nil {
diff --git a/cli/api/stream.go b/app/cli/api/stream.go
similarity index 100%
rename from cli/api/stream.go
rename to app/cli/api/stream.go
diff --git a/cli/auth/account.go b/app/cli/auth/account.go
similarity index 97%
rename from cli/auth/account.go
rename to app/cli/auth/account.go
index aedff51e..2afd11cf 100644
--- a/cli/auth/account.go
+++ b/app/cli/auth/account.go
@@ -170,7 +170,9 @@ func verifyEmail(email, host string) (bool, string, error) {
return false, "", fmt.Errorf("error creating email verification: %v", apiErr.Msg)
}
- pin, err := term.GetUserStringInput("You'll now receive a 6 character pin by email. Please enter it here:")
+ fmt.Println("✉️ You'll now receive a 6 character pin by email")
+
+ pin, err := term.GetUserPasswordInput("Please enter it here:")
if err != nil {
return false, "", fmt.Errorf("error prompting pin: %v", err)
diff --git a/cli/auth/api.go b/app/cli/auth/api.go
similarity index 100%
rename from cli/auth/api.go
rename to app/cli/auth/api.go
diff --git a/cli/auth/auth.go b/app/cli/auth/auth.go
similarity index 100%
rename from cli/auth/auth.go
rename to app/cli/auth/auth.go
diff --git a/cli/auth/org.go b/app/cli/auth/org.go
similarity index 90%
rename from cli/auth/org.go
rename to app/cli/auth/org.go
index 8206ddd0..ea59c427 100644
--- a/cli/auth/org.go
+++ b/app/cli/auth/org.go
@@ -83,11 +83,12 @@ func createOrg() (*shared.Org, error) {
}
func promptAutoAddUsersIfValid(email string) (bool, error) {
- userDomain := strings.Split(Current.Email, "@")[1]
+ userDomain := strings.Split(email, "@")[1]
var autoAddDomainUsers bool
var err error
if !shared.IsEmailServiceDomain(userDomain) {
- autoAddDomainUsers, err = term.ConfirmYesNo(fmt.Sprintf("Do you want to allow any user with an email ending in @%s to auto-join this org?", userDomain))
+ fmt.Println("With domain auto-join, you can allow any user with an email ending in @", userDomain, "to auto-join this org")
+ autoAddDomainUsers, err = term.ConfirmYesNo(fmt.Sprintf("Enable auto-join for %s?", userDomain))
if err != nil {
return false, err
diff --git a/cli/auth/state.go b/app/cli/auth/state.go
similarity index 100%
rename from cli/auth/state.go
rename to app/cli/auth/state.go
diff --git a/cli/auth/trial.go b/app/cli/auth/trial.go
similarity index 100%
rename from cli/auth/trial.go
rename to app/cli/auth/trial.go
diff --git a/cli/changes_tui/actions.go b/app/cli/changes_tui/actions.go
similarity index 80%
rename from cli/changes_tui/actions.go
rename to app/cli/changes_tui/actions.go
index aaa03da3..a678d12f 100644
--- a/cli/changes_tui/actions.go
+++ b/app/cli/changes_tui/actions.go
@@ -65,10 +65,11 @@ func (m *changesUIModel) right() {
func (m *changesUIModel) up() {
if m.selectedReplacementIndex > 0 {
+ // log.Println("up")
m.selectedReplacementIndex--
+ m.setSelectionInfo()
+ m.updateMainView(true)
}
- m.setSelectionInfo()
- m.updateMainView(true)
}
func (m *changesUIModel) down() {
@@ -84,10 +85,11 @@ func (m *changesUIModel) down() {
}
if m.selectedReplacementIndex < max {
+ // log.Println("down")
m.selectedReplacementIndex++
+ m.setSelectionInfo()
+ m.updateMainView(true)
}
- m.setSelectionInfo()
- m.updateMainView(true)
}
func (m *changesUIModel) scrollUp() {
@@ -148,27 +150,41 @@ func (m *changesUIModel) windowResized(w, h int) {
}
func (m *changesUIModel) updateMainView(scrollReplacement bool) {
+ // log.Println("updateMainView")
+
+ // var updateMsg types.ChangesUIViewportsUpdate
+
if m.selectedFullFile() {
+ context := m.currentPlan.ContextsByPath[m.selectionInfo.currentPath]
+ var originalFile string
+ if context != nil {
+ originalFile = context.Body
+ }
+
updatedFile := m.currentPlan.CurrentPlanFiles.Files[m.selectionInfo.currentPath]
wrapWidth := m.fileViewport.Width - 2
-
- replacements := m.selectionInfo.currentReplacements
fileSegments := []string{}
replacementSegments := map[int]bool{}
- lastReplacementIdx := 0
- for _, rep := range replacements {
- idx := strings.Index(updatedFile, rep.New)
- if idx == -1 || idx < lastReplacementIdx {
- continue
- }
- fileSegments = append(fileSegments, updatedFile[lastReplacementIdx:idx])
- fileSegments = append(fileSegments, rep.New)
- replacementSegments[len(fileSegments)-1] = true
- lastReplacementIdx = idx + len(rep.New)
+ if context == nil {
+ // the file is new, so all lines are new and should be highlighted
+ fileSegments = append(fileSegments, updatedFile)
+ replacementSegments[0] = true
+ } else {
+ lastFoundIdx := 0
+ updatedLines := strings.Split(updatedFile, "\n")
+ for i, line := range updatedLines {
+ fileSegments = append(fileSegments, line+"\n")
+ originalIdx := strings.Index(originalFile, line)
+ if originalIdx == -1 || originalIdx < lastFoundIdx {
+ replacementSegments[i] = true
+ } else {
+ lastFoundIdx = originalIdx + len(line)
+ replacementSegments[i] = false
+ }
+ }
}
- fileSegments = append(fileSegments, updatedFile[lastReplacementIdx:])
for i, segment := range fileSegments {
wrapped := wrap.String(segment, wrapWidth)
@@ -184,18 +200,19 @@ func (m *changesUIModel) updateMainView(scrollReplacement bool) {
}
m.fileViewport.SetContent(strings.Join(fileSegments, ""))
- m.updateViewportSizes()
} else {
oldRes := m.getReplacementOldDisplay()
m.changeOldViewport.SetContent(oldRes.oldDisplay)
+ // log.Println("set old content")
newContent, newContentDisplay := m.getReplacementNewDisplay(oldRes.prependContent, oldRes.appendContent)
m.changeNewViewport.SetContent(newContentDisplay)
-
- m.updateViewportSizes()
+ // log.Println("set new content")
if scrollReplacement {
m.scrollReplacementIntoView(oldRes.old, newContent, oldRes.numLinesPrepended)
}
}
+
+ m.updateViewportSizes()
}
diff --git a/cli/changes_tui/main_viewport.go b/app/cli/changes_tui/main_viewport.go
similarity index 94%
rename from cli/changes_tui/main_viewport.go
rename to app/cli/changes_tui/main_viewport.go
index 0489164f..1409c8af 100644
--- a/cli/changes_tui/main_viewport.go
+++ b/app/cli/changes_tui/main_viewport.go
@@ -7,6 +7,9 @@ import (
)
func (m changesUIModel) renderMainView() string {
+ // log.Println()
+ // log.Println("renderMainView")
+
mainViewHeader := m.renderMainViewHeader()
if m.selectedFullFile() {
@@ -31,9 +34,9 @@ func (m changesUIModel) renderMainView() string {
oldViews := []string{oldView}
newViews := []string{newView}
- if m.oldScrollable() && m.selectedViewport == 0 {
+ if m.oldScrollable() && (m.selectedViewport == 0 || !m.newScrollable()) {
oldViews = append(oldViews, m.renderScrollFooter())
- } else if m.newScrollable() {
+ } else if m.newScrollable() && (m.selectedViewport == 1 || !m.oldScrollable()) {
newViews = append(newViews, m.renderScrollFooter())
}
diff --git a/cli/changes_tui/model.go b/app/cli/changes_tui/model.go
similarity index 100%
rename from cli/changes_tui/model.go
rename to app/cli/changes_tui/model.go
diff --git a/cli/changes_tui/path_tabs.go b/app/cli/changes_tui/path_tabs.go
similarity index 96%
rename from cli/changes_tui/path_tabs.go
rename to app/cli/changes_tui/path_tabs.go
index 42fdf6e4..7d0d457d 100644
--- a/cli/changes_tui/path_tabs.go
+++ b/app/cli/changes_tui/path_tabs.go
@@ -78,6 +78,6 @@ func (m changesUIModel) renderPathTabs() string {
}
style := lipgloss.NewStyle().BorderStyle(lipgloss.NormalBorder()).BorderBottom(true).BorderForeground(lipgloss.Color(borderColor)).Width(m.width)
-
- return style.Render(strings.Join(resRows, "\n"))
+ tabs := strings.Join(resRows, "\n")
+ return style.Render(tabs)
}
diff --git a/cli/changes_tui/replace.go b/app/cli/changes_tui/replace.go
similarity index 100%
rename from cli/changes_tui/replace.go
rename to app/cli/changes_tui/replace.go
diff --git a/cli/changes_tui/run.go b/app/cli/changes_tui/run.go
similarity index 100%
rename from cli/changes_tui/run.go
rename to app/cli/changes_tui/run.go
diff --git a/cli/changes_tui/selection.go b/app/cli/changes_tui/selection.go
similarity index 86%
rename from cli/changes_tui/selection.go
rename to app/cli/changes_tui/selection.go
index aa5b0856..29492ab8 100644
--- a/cli/changes_tui/selection.go
+++ b/app/cli/changes_tui/selection.go
@@ -26,15 +26,18 @@ func (m *changesUIModel) setSelectionInfo() {
var pathReplacements []*shared.Replacement
- for i, res := range results {
- for j, rep := range res.Replacements {
- pathReplacements = append(pathReplacements, rep)
+ for _, res := range results {
+ pathReplacements = append(pathReplacements, res.Replacements...)
+ }
- flatIndex := i*len(res.Replacements) + j
- if flatIndex == m.selectedReplacementIndex {
+ i := 0
+ for _, res := range results {
+ for _, rep := range res.Replacements {
+ if i == m.selectedReplacementIndex {
currentRes = res
currentRep = rep
}
+ i++
}
}
diff --git a/cli/changes_tui/sidebar.go b/app/cli/changes_tui/sidebar.go
similarity index 55%
rename from cli/changes_tui/sidebar.go
rename to app/cli/changes_tui/sidebar.go
index 80f335e8..9a27f076 100644
--- a/cli/changes_tui/sidebar.go
+++ b/app/cli/changes_tui/sidebar.go
@@ -5,6 +5,7 @@ import (
"github.com/charmbracelet/lipgloss"
"github.com/fatih/color"
+ "github.com/plandex/plandex/shared"
)
func (m changesUIModel) renderSidebar() string {
@@ -22,48 +23,51 @@ func (m changesUIModel) renderSidebar() string {
anyApplied := false
anyReplacements := false
+ var replacements []*shared.Replacement
+
+ for _, result := range results {
+ replacements = append(replacements, result.Replacements...)
+ }
+
// Change entries
- for i, result := range results {
- for j, rep := range result.Replacements {
- anyReplacements = true
- flatIndex := i*len(result.Replacements) + j
- selected := currentRep != nil && rep.Id == currentRep.Id
- s := ""
-
- fgColor := color.FgHiGreen
- bgColor := color.BgGreen
- if rep.Failed {
- fgColor = color.FgHiRed
- bgColor = color.BgRed
- anyFailed = true
- } else if rep.RejectedAt != nil {
- fgColor = color.FgWhite
- bgColor = color.BgBlack
- }
-
- var icon string
- if rep.RejectedAt != nil {
- icon = "👎"
- } else if rep.Failed {
- icon = "🚫"
- } else {
- icon = "📝"
- }
-
- if !rep.Failed && rep.RejectedAt == nil {
- anyApplied = true
- }
-
- if selected {
- s += color.New(color.Bold, bgColor, color.FgHiWhite).Sprintf(" > %s %d ", icon, flatIndex+1)
- } else {
- s += color.New(fgColor).Sprintf(" - %s %d ", icon, flatIndex+1)
- }
-
- s += "\n"
-
- sb.WriteString(s)
+ for i, rep := range replacements {
+ anyReplacements = true
+ selected := currentRep != nil && rep.Id == currentRep.Id
+ s := ""
+
+ fgColor := color.FgHiGreen
+ bgColor := color.BgGreen
+ if rep.Failed {
+ fgColor = color.FgHiRed
+ bgColor = color.BgRed
+ anyFailed = true
+ } else if rep.RejectedAt != nil {
+ fgColor = color.FgWhite
+ bgColor = color.BgBlack
+ }
+
+ var icon string
+ if rep.RejectedAt != nil {
+ icon = "👎"
+ } else if rep.Failed {
+ icon = "🚫"
+ } else {
+ icon = "📝"
}
+
+ if !rep.Failed && rep.RejectedAt == nil {
+ anyApplied = true
+ }
+
+ if selected {
+ s += color.New(color.Bold, bgColor, color.FgHiWhite).Sprintf(" > %s %d ", icon, i+1)
+ } else {
+ s += color.New(fgColor).Sprintf(" - %s %d ", icon, i+1)
+ }
+
+ s += "\n"
+
+ sb.WriteString(s)
}
if !anyReplacements {
diff --git a/cli/changes_tui/update.go b/app/cli/changes_tui/update.go
similarity index 90%
rename from cli/changes_tui/update.go
rename to app/cli/changes_tui/update.go
index a2bb85d8..5a6ac545 100644
--- a/cli/changes_tui/update.go
+++ b/app/cli/changes_tui/update.go
@@ -1,6 +1,7 @@
package changes_tui
import (
+ "plandex/types"
"time"
bubbleKey "github.com/charmbracelet/bubbles/key"
@@ -19,6 +20,12 @@ func (m changesUIModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
case tea.WindowSizeMsg:
m.windowResized(msg.Width, msg.Height)
+ case types.ChangesUIViewportsUpdate:
+ m.updateViewportSizes()
+ if msg.ScrollReplacement != nil {
+ m.scrollReplacementIntoView(msg.ScrollReplacement.OldContent, msg.ScrollReplacement.NewContent, msg.ScrollReplacement.NumLinesPrepended)
+ }
+
case tea.KeyMsg:
switch {
diff --git a/cli/changes_tui/view.go b/app/cli/changes_tui/view.go
similarity index 76%
rename from cli/changes_tui/view.go
rename to app/cli/changes_tui/view.go
index dd025ae4..468d4555 100644
--- a/cli/changes_tui/view.go
+++ b/app/cli/changes_tui/view.go
@@ -25,11 +25,13 @@ func (m changesUIModel) View() string {
layout := lipgloss.JoinHorizontal(lipgloss.Top, sidebar, mainView)
- return lipgloss.JoinVertical(lipgloss.Left,
+ view := lipgloss.JoinVertical(lipgloss.Left,
tabs,
layout,
help,
)
+
+ return view
}
func (m changesUIModel) getMainViewDims() (int, int) {
@@ -62,6 +64,10 @@ func (m *changesUIModel) initViewports() {
}
func (m *changesUIModel) updateViewportSizes() {
+ // log.Println()
+ // log.Println()
+ // log.Println("updateViewportSizes")
+
mainViewWidth, mainViewHeight := m.getMainViewDims()
if m.selectedFullFile() {
@@ -76,27 +82,48 @@ func (m *changesUIModel) updateViewportSizes() {
m.fileViewport.Height = fileViewHeight
} else {
+ // log.Println("mainViewHeight", mainViewHeight)
+
+ mainViewHeight := mainViewHeight
oldViewHeight := mainViewHeight
+ newViewHeight := mainViewHeight
+ // set widths and reset heights
+ // log.Println("resetting widths and heights")
+ m.resetViewportDims()
+
+ // log.Println("oldScrollable", m.oldScrollable())
+ // log.Println("newScrollable", m.newScrollable())
+ // log.Println("selectedViewport", m.selectedViewport)
if m.oldScrollable() && (m.selectedViewport == 0 || !m.newScrollable()) {
footerHeight := lipgloss.Height(m.renderScrollFooter())
oldViewHeight -= footerHeight
- }
-
- newViewHeight := mainViewHeight
-
- if m.newScrollable() && (m.selectedViewport == 1 || !m.oldScrollable()) {
+ } else if m.newScrollable() && (m.selectedViewport == 1 || !m.oldScrollable()) {
footerHeight := lipgloss.Height(m.renderScrollFooter())
newViewHeight -= footerHeight
}
- m.changeOldViewport.Width = mainViewWidth / 2
+ // log.Println("oldViewHeight", oldViewHeight)
+ // log.Println("newViewHeight", newViewHeight)
+
+ // set updated heights
m.changeOldViewport.Height = oldViewHeight
- m.changeNewViewport.Width = mainViewWidth / 2
m.changeNewViewport.Height = newViewHeight
+
+ // log.Println("updated heights")
}
}
+func (m *changesUIModel) resetViewportDims() {
+ mainViewWidth, mainViewHeight := m.getMainViewDims()
+ m.fileViewport.Width = mainViewWidth
+ m.fileViewport.Height = mainViewHeight
+ m.changeOldViewport.Width = mainViewWidth / 2
+ m.changeOldViewport.Height = mainViewHeight
+ m.changeNewViewport.Width = mainViewWidth / 2
+ m.changeNewViewport.Height = mainViewHeight
+}
+
func (m changesUIModel) renderHelp() string {
help := " "
@@ -114,10 +141,18 @@ func (m changesUIModel) renderHelp() string {
}
func (m changesUIModel) oldScrollable() bool {
+ // log.Println("oldScrollable")
+ // log.Println("TotalLineCount", m.changeOldViewport.TotalLineCount())
+ // log.Println("VisibleLineCount", m.changeOldViewport.VisibleLineCount())
+
return m.changeOldViewport.TotalLineCount() > m.changeOldViewport.VisibleLineCount()
}
func (m changesUIModel) newScrollable() bool {
+ // log.Println("newScrollable")
+ // log.Println("TotalLineCount", m.changeNewViewport.TotalLineCount())
+ // log.Println("VisibleLineCount", m.changeNewViewport.VisibleLineCount())
+
return m.changeNewViewport.TotalLineCount() > m.changeNewViewport.VisibleLineCount()
}
diff --git a/cli/cmd/apply.go b/app/cli/cmd/apply.go
similarity index 100%
rename from cli/cmd/apply.go
rename to app/cli/cmd/apply.go
diff --git a/cli/cmd/cd.go b/app/cli/cmd/cd.go
similarity index 100%
rename from cli/cmd/cd.go
rename to app/cli/cmd/cd.go
diff --git a/cli/cmd/changes.go b/app/cli/cmd/changes.go
similarity index 100%
rename from cli/cmd/changes.go
rename to app/cli/cmd/changes.go
diff --git a/cli/cmd/clear.go b/app/cli/cmd/clear.go
similarity index 100%
rename from cli/cmd/clear.go
rename to app/cli/cmd/clear.go
diff --git a/cli/cmd/continue.go b/app/cli/cmd/continue.go
similarity index 50%
rename from cli/cmd/continue.go
rename to app/cli/cmd/continue.go
index ba5dbcc5..bbb46a2e 100644
--- a/cli/cmd/continue.go
+++ b/app/cli/cmd/continue.go
@@ -37,33 +37,44 @@ func next(cmd *cobra.Command, args []string) {
lib.MustResolveProject()
lib.MustCheckOutdatedContextWithOutput()
- apiErr := api.Client.TellPlan(lib.CurrentPlanId, shared.TellPlanRequest{
- Prompt: continuePrompt,
- ConnectStream: !continueBg,
- }, lib.OnStreamPlan)
- if apiErr != nil {
- if apiErr.Type == shared.ApiErrorTypeTrialMessagesExceeded {
- fmt.Fprintf(os.Stderr, "🚨 You've reached the free trial limit of %d messages per plan\n", apiErr.TrialMessagesExceededError.MaxMessages)
-
- res, err := term.ConfirmYesNo("Upgrade now?")
-
- if err != nil {
- fmt.Fprintln(os.Stderr, "Error prompting upgrade trial:", err)
- return
- }
+ var fn func() bool
+ fn = func() bool {
+ apiErr := api.Client.TellPlan(lib.CurrentPlanId, shared.TellPlanRequest{
+ Prompt: continuePrompt,
+ ConnectStream: !continueBg,
+ }, lib.OnStreamPlan)
+ if apiErr != nil {
+ if apiErr.Type == shared.ApiErrorTypeTrialMessagesExceeded {
+ fmt.Fprintf(os.Stderr, "🚨 You've reached the free trial limit of %d messages per plan\n", apiErr.TrialMessagesExceededError.MaxMessages)
+
+ res, err := term.ConfirmYesNo("Upgrade now?")
- if res {
- err := auth.ConvertTrial()
if err != nil {
- fmt.Fprintln(os.Stderr, "Error converting trial:", err)
- return
+ fmt.Fprintln(os.Stderr, "Error prompting upgrade trial:", err)
+ return false
+ }
+
+ if res {
+ err := auth.ConvertTrial()
+ if err != nil {
+ fmt.Fprintln(os.Stderr, "Error converting trial:", err)
+ return false
+ }
+ // retry action after converting trial
+ return fn()
}
+
+ return false
}
- return
+ fmt.Fprintln(os.Stderr, "Prompt error:", apiErr.Msg)
+ return false
}
+ return true
+ }
- fmt.Fprintln(os.Stderr, "Prompt error:", apiErr.Msg)
+ shouldContinue := fn()
+ if !shouldContinue {
return
}
diff --git a/cli/cmd/convo.go b/app/cli/cmd/convo.go
similarity index 88%
rename from cli/cmd/convo.go
rename to app/cli/cmd/convo.go
index 5e56eee9..d3a3e177 100644
--- a/cli/cmd/convo.go
+++ b/app/cli/cmd/convo.go
@@ -56,19 +56,19 @@ func convo(cmd *cobra.Command, args []string) {
}
// format as above but start with day of week
- formattedTs := msg.CreatedAt.Local().Format("Mon Jan 2, 2006 | 3:04:05pm MST")
+ formattedTs := msg.CreatedAt.Local().Format("Mon Jan 2, 2006 | 3:04pm MST")
// if it's today then use 'Today' instead of the date
if msg.CreatedAt.Day() == time.Now().Day() {
- formattedTs = msg.CreatedAt.Local().Format("Today | 3:04:05pm MST")
+ formattedTs = msg.CreatedAt.Local().Format("Today | 3:04pm MST")
}
// if it's yesterday then use 'Yesterday' instead of the date
if msg.CreatedAt.Day() == time.Now().AddDate(0, 0, -1).Day() {
- formattedTs = msg.CreatedAt.Local().Format("Yesterday | 3:04:05pm MST")
+ formattedTs = msg.CreatedAt.Local().Format("Yesterday | 3:04pm MST")
}
- header := fmt.Sprintf("#### %d | %s | %s | %d 🪙", i+1,
+ header := fmt.Sprintf("#### %d | %s | %s | %d 🪙 | ", i+1,
author, formattedTs, msg.Tokens)
convMarkdown = append(convMarkdown, header, msg.Message, "")
totalTokens += msg.Tokens
@@ -85,5 +85,5 @@ func convo(cmd *cobra.Command, args []string) {
term.GetDivisionLine() +
color.New(color.Bold, color.FgCyan).Sprint(" Conversation size →") + fmt.Sprintf(" %d 🪙", totalTokens) + "\n\n"
- term.PageOutputReverse(output)
+ term.PageOutput(output)
}
diff --git a/cli/cmd/current.go b/app/cli/cmd/current.go
similarity index 100%
rename from cli/cmd/current.go
rename to app/cli/cmd/current.go
diff --git a/cli/cmd/delete_plan.go b/app/cli/cmd/delete_plan.go
similarity index 100%
rename from cli/cmd/delete_plan.go
rename to app/cli/cmd/delete_plan.go
diff --git a/cli/cmd/load.go b/app/cli/cmd/load.go
similarity index 100%
rename from cli/cmd/load.go
rename to app/cli/cmd/load.go
diff --git a/cli/cmd/log.go b/app/cli/cmd/log.go
similarity index 100%
rename from cli/cmd/log.go
rename to app/cli/cmd/log.go
diff --git a/cli/cmd/ls.go b/app/cli/cmd/ls.go
similarity index 100%
rename from cli/cmd/ls.go
rename to app/cli/cmd/ls.go
diff --git a/cli/cmd/new.go b/app/cli/cmd/new.go
similarity index 100%
rename from cli/cmd/new.go
rename to app/cli/cmd/new.go
diff --git a/cli/cmd/plans.go b/app/cli/cmd/plans.go
similarity index 100%
rename from cli/cmd/plans.go
rename to app/cli/cmd/plans.go
diff --git a/cli/cmd/rewind.go b/app/cli/cmd/rewind.go
similarity index 86%
rename from cli/cmd/rewind.go
rename to app/cli/cmd/rewind.go
index 1a76a373..95f48d7c 100644
--- a/cli/cmd/rewind.go
+++ b/app/cli/cmd/rewind.go
@@ -26,14 +26,9 @@ var rewindCmd = &cobra.Command{
Run: rewind,
}
-var sha string
-
func init() {
// Add rewind command
RootCmd.AddCommand(rewindCmd)
-
- // Add sha flag
- rewindCmd.Flags().StringVar(&sha, "sha", "", "Specify a commit sha to rewind to")
}
func rewind(cmd *cobra.Command, args []string) {
@@ -45,11 +40,7 @@ func rewind(cmd *cobra.Command, args []string) {
return
}
- // Check if either steps or sha is provided and not both
- stepsOrSha := ""
- if len(args) > 1 {
- stepsOrSha = args[1]
- }
+ stepsOrSha := args[0]
logsRes, err := api.Client.ListLogs(lib.CurrentPlanId)
@@ -63,13 +54,15 @@ func rewind(cmd *cobra.Command, args []string) {
log.Println("shas:", logsRes.Shas)
if steps, err := strconv.Atoi(stepsOrSha); err == nil && steps > 0 {
- log.Println("steps:", steps)
+ // log.Println("steps:", steps)
// Rewind by the specified number of steps
targetSha = logsRes.Shas[steps]
} else if sha := stepsOrSha; sha != "" {
+ // log.Println("sha provided:", sha)
// Rewind to the specified Sha
targetSha = sha
} else if stepsOrSha == "" {
+ // log.Println("No steps or sha provided, rewinding by 1 step")
// Rewind by 1 step
targetSha = logsRes.Shas[1]
} else {
@@ -77,7 +70,7 @@ func rewind(cmd *cobra.Command, args []string) {
os.Exit(1)
}
- log.Println("Rewinding to", targetSha)
+ // log.Println("Rewinding to", targetSha)
// Rewind to the target sha
rwRes, err := api.Client.RewindPlan(lib.CurrentPlanId, shared.RewindPlanRequest{Sha: targetSha})
diff --git a/cli/cmd/rm.go b/app/cli/cmd/rm.go
similarity index 100%
rename from cli/cmd/rm.go
rename to app/cli/cmd/rm.go
diff --git a/cli/cmd/root.go b/app/cli/cmd/root.go
similarity index 100%
rename from cli/cmd/root.go
rename to app/cli/cmd/root.go
diff --git a/cli/cmd/sign_in.go b/app/cli/cmd/sign_in.go
similarity index 100%
rename from cli/cmd/sign_in.go
rename to app/cli/cmd/sign_in.go
diff --git a/cli/cmd/status.go b/app/cli/cmd/status.go
similarity index 100%
rename from cli/cmd/status.go
rename to app/cli/cmd/status.go
diff --git a/cli/cmd/tell.go b/app/cli/cmd/tell.go
similarity index 79%
rename from cli/cmd/tell.go
rename to app/cli/cmd/tell.go
index f81624a7..9166a7f0 100644
--- a/cli/cmd/tell.go
+++ b/app/cli/cmd/tell.go
@@ -135,33 +135,43 @@ func tell(cmd *cobra.Command, args []string) {
}()
}
- apiErr := api.Client.TellPlan(lib.CurrentPlanId, shared.TellPlanRequest{
- Prompt: prompt,
- ConnectStream: !tellBg,
- }, lib.OnStreamPlan)
- if apiErr != nil {
- if apiErr.Type == shared.ApiErrorTypeTrialMessagesExceeded {
- fmt.Fprintf(os.Stderr, "🚨 You've reached the free trial limit of %d messages per plan\n", apiErr.TrialMessagesExceededError.MaxMessages)
+ var fn func() bool
+ fn = func() bool {
+ apiErr := api.Client.TellPlan(lib.CurrentPlanId, shared.TellPlanRequest{
+ Prompt: prompt,
+ ConnectStream: !tellBg,
+ }, lib.OnStreamPlan)
+ if apiErr != nil {
+ if apiErr.Type == shared.ApiErrorTypeTrialMessagesExceeded {
+ fmt.Fprintf(os.Stderr, "\n🚨 You've reached the free trial limit of %d messages per plan\n", apiErr.TrialMessagesExceededError.MaxMessages)
+
+ res, err := term.ConfirmYesNo("Upgrade now?")
- res, err := term.ConfirmYesNo("Upgrade now?")
-
- if err != nil {
- fmt.Fprintln(os.Stderr, "Error prompting upgrade trial:", err)
- return
- }
-
- if res {
- err := auth.ConvertTrial()
if err != nil {
- fmt.Fprintln(os.Stderr, "Error converting trial:", err)
- return
+ fmt.Fprintln(os.Stderr, "Error prompting upgrade trial:", err)
+ return false
}
+
+ if res {
+ err := auth.ConvertTrial()
+ if err != nil {
+ fmt.Fprintln(os.Stderr, "Error converting trial:", err)
+ return false
+ }
+ // retry action after converting trial
+ return fn()
+ }
+ return false
}
- return
+ fmt.Fprintln(os.Stderr, "Prompt error:", apiErr.Msg)
+ return false
}
+ return true
+ }
- fmt.Fprintln(os.Stderr, "Prompt error:", apiErr.Msg)
+ shouldContinue := fn()
+ if !shouldContinue {
return
}
diff --git a/cli/cmd/update.go b/app/cli/cmd/update.go
similarity index 100%
rename from cli/cmd/update.go
rename to app/cli/cmd/update.go
diff --git a/cli/dev.sh b/app/cli/dev.sh
similarity index 100%
rename from cli/dev.sh
rename to app/cli/dev.sh
diff --git a/cli/format/file.go b/app/cli/format/file.go
similarity index 100%
rename from cli/format/file.go
rename to app/cli/format/file.go
diff --git a/cli/format/time.go b/app/cli/format/time.go
similarity index 100%
rename from cli/format/time.go
rename to app/cli/format/time.go
diff --git a/cli/fs/fs.go b/app/cli/fs/fs.go
similarity index 100%
rename from cli/fs/fs.go
rename to app/cli/fs/fs.go
diff --git a/cli/go.mod b/app/cli/go.mod
similarity index 96%
rename from cli/go.mod
rename to app/cli/go.mod
index 8089e318..59b09943 100644
--- a/cli/go.mod
+++ b/app/cli/go.mod
@@ -5,6 +5,7 @@ go 1.21.3
require (
github.com/atotto/clipboard v0.1.4
github.com/charmbracelet/lipgloss v0.9.1
+ github.com/davecgh/go-spew v1.1.1
github.com/fatih/color v1.16.0
github.com/looplab/fsm v1.0.1
github.com/muesli/reflow v0.3.0
@@ -62,4 +63,4 @@ require (
replace github.com/plandex/plandex/shared => ../shared
-replace github.com/plandex-ai/survey/v2 => ../../survey
+replace github.com/plandex-ai/survey/v2 => ../../../survey
diff --git a/cli/go.sum b/app/cli/go.sum
similarity index 100%
rename from cli/go.sum
rename to app/cli/go.sum
diff --git a/cli/install.sh b/app/cli/install.sh
similarity index 100%
rename from cli/install.sh
rename to app/cli/install.sh
diff --git a/cli/lib/apply.go b/app/cli/lib/apply.go
similarity index 100%
rename from cli/lib/apply.go
rename to app/cli/lib/apply.go
diff --git a/cli/lib/context_display.go b/app/cli/lib/context_display.go
similarity index 100%
rename from cli/lib/context_display.go
rename to app/cli/lib/context_display.go
diff --git a/cli/lib/context_load.go b/app/cli/lib/context_load.go
similarity index 100%
rename from cli/lib/context_load.go
rename to app/cli/lib/context_load.go
diff --git a/cli/lib/context_paths.go b/app/cli/lib/context_paths.go
similarity index 100%
rename from cli/lib/context_paths.go
rename to app/cli/lib/context_paths.go
diff --git a/cli/lib/context_update.go b/app/cli/lib/context_update.go
similarity index 100%
rename from cli/lib/context_update.go
rename to app/cli/lib/context_update.go
diff --git a/cli/lib/current.go b/app/cli/lib/current.go
similarity index 100%
rename from cli/lib/current.go
rename to app/cli/lib/current.go
diff --git a/cli/lib/git.go b/app/cli/lib/git.go
similarity index 100%
rename from cli/lib/git.go
rename to app/cli/lib/git.go
diff --git a/cli/lib/os.go b/app/cli/lib/os.go
similarity index 100%
rename from cli/lib/os.go
rename to app/cli/lib/os.go
diff --git a/cli/lib/plans.go b/app/cli/lib/plans.go
similarity index 100%
rename from cli/lib/plans.go
rename to app/cli/lib/plans.go
diff --git a/cli/lib/stream.go b/app/cli/lib/stream.go
similarity index 100%
rename from cli/lib/stream.go
rename to app/cli/lib/stream.go
diff --git a/cli/main.go b/app/cli/main.go
similarity index 100%
rename from cli/main.go
rename to app/cli/main.go
diff --git a/cli/plan.json b/app/cli/plan.json
similarity index 100%
rename from cli/plan.json
rename to app/cli/plan.json
diff --git a/cli/stream_tui/model.go b/app/cli/stream_tui/model.go
similarity index 100%
rename from cli/stream_tui/model.go
rename to app/cli/stream_tui/model.go
diff --git a/cli/stream_tui/run.go b/app/cli/stream_tui/run.go
similarity index 100%
rename from cli/stream_tui/run.go
rename to app/cli/stream_tui/run.go
diff --git a/cli/stream_tui/update.go b/app/cli/stream_tui/update.go
similarity index 100%
rename from cli/stream_tui/update.go
rename to app/cli/stream_tui/update.go
diff --git a/cli/stream_tui/view.go b/app/cli/stream_tui/view.go
similarity index 100%
rename from cli/stream_tui/view.go
rename to app/cli/stream_tui/view.go
diff --git a/cli/term/glow.go b/app/cli/term/glow.go
similarity index 100%
rename from cli/term/glow.go
rename to app/cli/term/glow.go
diff --git a/cli/term/select.go b/app/cli/term/select.go
similarity index 100%
rename from cli/term/select.go
rename to app/cli/term/select.go
diff --git a/cli/term/spinner.go b/app/cli/term/spinner.go
similarity index 100%
rename from cli/term/spinner.go
rename to app/cli/term/spinner.go
diff --git a/cli/term/term.go b/app/cli/term/term.go
similarity index 96%
rename from cli/term/term.go
rename to app/cli/term/term.go
index 5689a3ac..a503a4ee 100644
--- a/cli/term/term.go
+++ b/app/cli/term/term.go
@@ -11,6 +11,7 @@ import (
"golang.org/x/term"
"github.com/cqroot/prompt"
+ "github.com/cqroot/prompt/input"
)
var CmdDesc = map[string][2]string{
@@ -115,6 +116,10 @@ func GetUserStringInput(msg string) (string, error) {
return prompt.New().Ask(msg).Input("")
}
+func GetUserPasswordInput(msg string) (string, error) {
+ return prompt.New().Ask(msg).Input("", input.WithEchoMode(input.EchoPassword))
+}
+
func GetUserKeyInput() (rune, error) {
if err := keyboard.Open(); err != nil {
return 0, fmt.Errorf("failed to open keyboard: %s", err)
diff --git a/cli/types/api.go b/app/cli/types/api.go
similarity index 100%
rename from cli/types/api.go
rename to app/cli/types/api.go
diff --git a/cli/types/types.go b/app/cli/types/types.go
similarity index 86%
rename from cli/types/types.go
rename to app/cli/types/types.go
index 9af68cf5..a5d7129a 100644
--- a/cli/types/types.go
+++ b/app/cli/types/types.go
@@ -54,3 +54,13 @@ type StreamTUIUpdate struct {
Processing bool
PlanTokenCount *shared.PlanTokenCount
}
+
+type ChangesUIScrollReplacement struct {
+ OldContent string
+ NewContent string
+ NumLinesPrepended int
+}
+
+type ChangesUIViewportsUpdate struct {
+ ScrollReplacement *ChangesUIScrollReplacement
+}
diff --git a/cli/url/url.go b/app/cli/url/url.go
similarity index 100%
rename from cli/url/url.go
rename to app/cli/url/url.go
diff --git a/cli/utils/utils.go b/app/cli/utils/utils.go
similarity index 100%
rename from cli/utils/utils.go
rename to app/cli/utils/utils.go
diff --git a/app/server/model/finished.go b/app/server/model/finished.go
deleted file mode 100644
index f3d635fd..00000000
--- a/app/server/model/finished.go
+++ /dev/null
@@ -1,58 +0,0 @@
-package model
-
-import (
- "context"
- "encoding/json"
- "fmt"
- "plandex-server/model/prompts"
-
- "github.com/sashabaranov/go-openai"
-)
-
-type PlanFinishedParams struct {
- Conversation []openai.ChatCompletionMessage
-}
-
-type PlanFinishedRes struct {
- Reasoning string `json:"reasoning"`
- Finished bool `json:"finished"`
-}
-
-func PlanFinished(params PlanFinishedParams) (PlanFinishedRes, error) {
- messages := []openai.ChatCompletionMessage{
- {
- Role: openai.ChatMessageRoleSystem,
- Content: prompts.SysFinished,
- },
- }
-
- messages = append(messages, params.Conversation...)
-
- resp, err := Client.CreateChatCompletion(
- context.Background(),
- openai.ChatCompletionRequest{
- Model: PlanSummaryModel,
- Messages: messages,
- },
- )
-
- if err != nil {
- fmt.Println("PlanFinished err:", err)
- return PlanFinishedRes{}, err
- }
-
- if len(resp.Choices) == 0 {
- return PlanFinishedRes{}, fmt.Errorf("no response from GPT")
- }
-
- content := resp.Choices[0].Message.Content
-
- // Here, we assume that if the AI assistant says "finished", the plan is finished.
- // You might want to adjust this according to your needs.
- isFinished := content == "finished"
-
- return PlanFinishedRes{
- Reasoning: content,
- Finished: isFinished,
- }, nil
-}
diff --git a/app/server/model/openai_models.go b/app/server/model/openai_models.go
index ea9377ce..23ab4943 100644
--- a/app/server/model/openai_models.go
+++ b/app/server/model/openai_models.go
@@ -16,6 +16,7 @@ var BuilderModel = mediumModel
var ShortSummaryModel = weakModel
var NameModel = weakModel
var CommitMsgModel = weakModel
+var PlanExecStatusModel = mediumModel
func init() {
if os.Getenv("PLANNER_MODEL") != "" {
diff --git a/app/server/model/plan/describe.go b/app/server/model/plan/describe.go
index e2abc163..18df8619 100644
--- a/app/server/model/plan/describe.go
+++ b/app/server/model/plan/describe.go
@@ -33,14 +33,14 @@ func genPlanDescription(planId string, ctx context.Context) (*db.ConvoMessageDes
},
)
- var descStrRes string
- var desc shared.ConvoMessageDescription
-
if err != nil {
fmt.Printf("Error during plan description model call: %v\n", err)
return nil, err
}
+ var descStrRes string
+ var desc shared.ConvoMessageDescription
+
for _, choice := range descResp.Choices {
if choice.FinishReason == "function_call" &&
choice.Message.FunctionCall != nil &&
diff --git a/app/server/model/plan/exec_status.go b/app/server/model/plan/exec_status.go
new file mode 100644
index 00000000..0d939b71
--- /dev/null
+++ b/app/server/model/plan/exec_status.go
@@ -0,0 +1,153 @@
+package plan
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "plandex-server/model"
+ "plandex-server/model/prompts"
+
+ "github.com/sashabaranov/go-openai"
+)
+
+type PlanExecStatus struct {
+ NeedsInput bool `json:"needs_input"`
+ Finished bool `json:"finished"`
+}
+
+func ExecStatus(conversation []openai.ChatCompletionMessage, ctx context.Context) (*PlanExecStatus, error) {
+ var res PlanExecStatus
+
+ errCh := make(chan error, 2)
+
+ go func() {
+ needsInput, err := ExecStatusNeedsInput(conversation, ctx)
+ if err != nil {
+ errCh <- err
+ }
+ res.NeedsInput = needsInput
+ errCh <- nil
+ }()
+
+ go func() {
+ finished, err := ExecStatusIsFinished(conversation, ctx)
+ if err != nil {
+ errCh <- err
+ }
+ res.Finished = finished
+ errCh <- nil
+ }()
+
+ for i := 0; i < 2; i++ {
+ err := <-errCh
+ if err != nil {
+ return nil, err
+ }
+ }
+
+ return &res, nil
+}
+
+func ExecStatusIsFinished(conversation []openai.ChatCompletionMessage, ctx context.Context) (bool, error) {
+ messages := []openai.ChatCompletionMessage{
+ {
+ Role: openai.ChatMessageRoleSystem,
+ Content: prompts.GetExecStatusIsFinishedPrompt(conversation),
+ },
+ }
+
+ resp, err := model.Client.CreateChatCompletion(
+ ctx,
+ openai.ChatCompletionRequest{
+ Model: model.PlanExecStatusModel,
+ Functions: []openai.FunctionDefinition{prompts.PlanIsFinishedFn},
+ Messages: messages,
+ ResponseFormat: &openai.ChatCompletionResponseFormat{Type: "json_object"},
+ },
+ )
+
+ if err != nil {
+ fmt.Printf("Error during plan exec status check model call: %v\n", err)
+ return false, err
+ }
+
+ var strRes string
+ var res PlanExecStatus
+
+ for _, choice := range resp.Choices {
+ if choice.FinishReason == "function_call" &&
+ choice.Message.FunctionCall != nil &&
+ choice.Message.FunctionCall.Name == "planIsFinished" {
+ fnCall := choice.Message.FunctionCall
+ strRes = fnCall.Arguments
+ }
+ }
+
+ if strRes == "" {
+ fmt.Println("no planIsFinished function call found in response")
+ return false, err
+ }
+
+ byteRes := []byte(strRes)
+
+ err = json.Unmarshal(byteRes, &res)
+ if err != nil {
+ fmt.Printf("Error unmarshalling plan exec status response: %v\n", err)
+ return false, err
+ }
+
+ return res.Finished, nil
+}
+
+func ExecStatusNeedsInput(conversation []openai.ChatCompletionMessage, ctx context.Context) (bool, error) {
+ messages := []openai.ChatCompletionMessage{
+ {
+ Role: openai.ChatMessageRoleSystem,
+ Content: prompts.GetExecStatusNeedsInputPrompt(&conversation[len(conversation)-1]),
+ },
+ }
+
+ messages = append(messages, conversation...)
+
+ resp, err := model.Client.CreateChatCompletion(
+ ctx,
+ openai.ChatCompletionRequest{
+ Model: model.PlanExecStatusModel,
+ Functions: []openai.FunctionDefinition{prompts.PlanNeedsInputFn},
+ Messages: messages,
+ ResponseFormat: &openai.ChatCompletionResponseFormat{Type: "json_object"},
+ },
+ )
+
+ if err != nil {
+ fmt.Printf("Error during plan exec status check model call: %v\n", err)
+ return false, err
+ }
+
+ var strRes string
+ var res PlanExecStatus
+
+ for _, choice := range resp.Choices {
+ if choice.FinishReason == "function_call" &&
+ choice.Message.FunctionCall != nil &&
+ choice.Message.FunctionCall.Name == "planNeedsInput" {
+ fnCall := choice.Message.FunctionCall
+ strRes = fnCall.Arguments
+ }
+ }
+
+ if strRes == "" {
+ fmt.Println("no planNeedsInput function call found in response")
+ return false, err
+ }
+
+ byteRes := []byte(strRes)
+
+ err = json.Unmarshal(byteRes, &res)
+ if err != nil {
+ fmt.Printf("Error unmarshalling plan exec status response: %v\n", err)
+ return false, err
+ }
+
+ return res.NeedsInput, nil
+}
diff --git a/app/server/model/plan/tell.go b/app/server/model/plan/tell.go
index 23035830..cdfe1840 100644
--- a/app/server/model/plan/tell.go
+++ b/app/server/model/plan/tell.go
@@ -242,9 +242,6 @@ func execTellPlan(plan *db.Plan, auth *types.ServerAuth, req *shared.TellPlanReq
// token limit exceeded after adding conversation
// get summary for as much as the conversation as necessary to stay under the token limit
for _, s := range summaries {
- log.Printf("summary: ")
- spew.Dump(s)
-
timestamp := s.LatestConvoMessageCreatedAt.UnixNano() / int64(time.Millisecond)
tokens, ok := tokensUpToTimestamp[timestamp]
diff --git a/app/server/model/prompts/create.go b/app/server/model/prompts/create.go
index ad0fa149..335b5807 100644
--- a/app/server/model/prompts/create.go
+++ b/app/server/model/prompts/create.go
@@ -55,7 +55,7 @@ const SysCreate = Identity + ` A plan is a set of files with an attached context
**Don't ask the user to take an action that you are able to do.** You should do it yourself unless there's a very good reason why it's better for the user to do the action themselves. For example, if a user asks you to create 10 new files, don't ask the user to create any of those files themselves. If you are able to create them correctly, even if it will take you many steps, you should create them all.
- At the end of a plan, you can suggest additional iterations to make the plan better. You can also ask the user to load more files into context or give you more information if it would help you make a better plan.
+ At the end of your response, you can suggest additional iterations to make the plan better. You can also ask the user to load more files into context or give you more information if it would help you make a better plan. **If all tasks and subtasks have been completed, explicitly say "All tasks have been completed."**
Be aware that since the plan started, the context may have been updated. It may have been updated by the user implementing your suggestions, by the user implementing their own work, or by the user adding more files or information to context. Be sure to consider the current state of the context when continuing with the plan, and whether the plan needs to be updated to reflect the latest context. For example, if you are working on a plan that has been broken up into subtasks, and you've reached the point of implementing a particular subtask, first consider whether the subtask is still necessary looking at the files in context. If it has already been implemented or is no longer necessary, say so, revise the plan if needed, and move on. Otherwise, implement the subtask.
` +
diff --git a/app/server/model/prompts/exec_status.go b/app/server/model/prompts/exec_status.go
new file mode 100644
index 00000000..eb9e36fd
--- /dev/null
+++ b/app/server/model/prompts/exec_status.go
@@ -0,0 +1,60 @@
+package prompts
+
+import (
+ "github.com/sashabaranov/go-openai"
+ "github.com/sashabaranov/go-openai/jsonschema"
+)
+
+const SysExecStatusIsFinished = `You are an AI assistant that determines the execution status of a coding AI's plan for a programming task. Analyze the AI's latest message to determine whether the plan is finished.
+
+The plan is finished if all the plan's tasks and subtasks have been completed. When a plan is finished, the coding AI will say something like "All tasks have been completed." If the response is a list of tasks, then the plan is not finished. If the response is a list of tasks and a message saying that all tasks have been completed, then the plan is finished.
+
+Return a JSON object with the 'finished' key set to true or false. Only call the 'planIsFinished' function in your response. Don't call any other function.`
+
+func GetExecStatusIsFinishedPrompt(conversation []openai.ChatCompletionMessage) string {
+ s := ""
+ for _, m := range conversation {
+ s += m.Role + ":\n"
+ s += m.Content + "\n"
+ }
+
+ return SysExecStatusIsFinished + "\n\nConversation:\n" + s
+}
+
+var PlanIsFinishedFn = openai.FunctionDefinition{
+ Name: "planIsFinished",
+ Parameters: &jsonschema.Definition{
+ Type: jsonschema.Object,
+ Properties: map[string]jsonschema.Definition{
+ "finished": {
+ Type: jsonschema.Boolean,
+ Description: "Whether the plan is finished.",
+ },
+ },
+ Required: []string{"finished"},
+ },
+}
+
+const SysExecStatusNeedsInput = `You are an AI assistant that determines the execution status of a coding AI's plan for a programming task. Analyze the AI's latest message to determine whether the plan needs more input. The plan needs more input if the coding AI requires the user to add more context, provide information, or answer questions the AI has asked.
+
+When the coding AI needs more input, it will say something like "I need more information or context to make a plan for this task."
+
+If the coding AI says or implies that additional information would be helpful or useful, but that information isn't *required* to continue the plan, then the plan *does not* need more input. It only needs more input if the AI says or implies that more information is necessary and required to continue. Return a JSON object with the 'needs_input' key set to true or false. Only call the 'planNeedsInput' function in your response. Don't call any other function.`
+
+func GetExecStatusNeedsInputPrompt(message *openai.ChatCompletionMessage) string {
+ return SysExecStatusNeedsInput + "\nLatest message from coding AI:\n" + message.Content
+}
+
+var PlanNeedsInputFn = openai.FunctionDefinition{
+ Name: "planNeedsInput",
+ Parameters: &jsonschema.Definition{
+ Type: jsonschema.Object,
+ Properties: map[string]jsonschema.Definition{
+ "needs_input": {
+ Type: jsonschema.Boolean,
+ Description: "Whether the plan needs more input. If ambiguous or unclear, assume the plan does not need more input.",
+ },
+ },
+ Required: []string{"needs_input"},
+ },
+}
diff --git a/app/server/model/prompts/finished.go b/app/server/model/prompts/finished.go
deleted file mode 100644
index efd34ea1..00000000
--- a/app/server/model/prompts/finished.go
+++ /dev/null
@@ -1,7 +0,0 @@
-package prompts
-
-const SysFinished = "You are an AI assistant that determines whether a software development plan has been finished or not. Analyze the conversation and decide whether all tasks have been completed."
-
-func GetFinishedPrompt(conversation string) string {
- return SysFinished + "\n\nConversation:\n" + conversation
-}
diff --git a/app/server/types/active_plan.go b/app/server/types/active_plan.go
index 16b3eb4f..b635064f 100644
--- a/app/server/types/active_plan.go
+++ b/app/server/types/active_plan.go
@@ -7,39 +7,43 @@ import (
"github.com/google/uuid"
)
-type ActivePlan struct {
- Prompt string
- StreamCh chan string
- StreamDoneCh chan error
- Ctx context.Context
- CancelFn context.CancelFunc
- Contexts []*db.Context
- ContextsByPath map[string]*db.Context
- Content string
- NumTokens int
- PromptMessageNum int
+type ActiveBuild struct {
AssistantMessageId string
Files []string
BuildBuffers map[string]string
BuiltFiles map[string]bool
- subscriptions map[string]chan string
+ Error error
+ ErrorReason string
+}
+
+type ActivePlan struct {
+ Prompt string
+ StreamCh chan string
+ StreamDoneCh chan error
+ Ctx context.Context
+ CancelFn context.CancelFunc
+ Contexts []*db.Context
+ ContextsByPath map[string]*db.Context
+ Content string
+ NumTokens int
+ PromptMessageNum int
+ BuildQueuesByPath map[string]*[]ActiveBuild
+ subscriptions map[string]chan string
}
func NewActivePlan(prompt string) *ActivePlan {
ctx, cancel := context.WithCancel(context.Background())
active := ActivePlan{
- Prompt: prompt,
- StreamCh: make(chan string),
- StreamDoneCh: make(chan error),
- Ctx: ctx,
- CancelFn: cancel,
- Files: []string{},
- BuiltFiles: map[string]bool{},
- Contexts: []*db.Context{},
- ContextsByPath: map[string]*db.Context{},
- BuildBuffers: map[string]string{},
- subscriptions: map[string]chan string{},
+ Prompt: prompt,
+ StreamCh: make(chan string),
+ StreamDoneCh: make(chan error),
+ Ctx: ctx,
+ CancelFn: cancel,
+ BuildQueuesByPath: map[string]*[]ActiveBuild{},
+ Contexts: []*db.Context{},
+ ContextsByPath: map[string]*db.Context{},
+ subscriptions: map[string]chan string{},
}
go func() {
@@ -58,8 +62,8 @@ func NewActivePlan(prompt string) *ActivePlan {
return &active
}
-func (ap *ActivePlan) BuildFinished() bool {
- return len(ap.Files) == len(ap.BuiltFiles)
+func (b *ActiveBuild) BuildFinished() bool {
+ return len(b.Files) == len(b.BuiltFiles)
}
func (ap *ActivePlan) Subscribe() (string, chan string) {
diff --git a/shared/auth.go b/app/shared/auth.go
similarity index 100%
rename from shared/auth.go
rename to app/shared/auth.go
diff --git a/shared/context.go b/app/shared/context.go
similarity index 100%
rename from shared/context.go
rename to app/shared/context.go
diff --git a/shared/email.go b/app/shared/email.go
similarity index 100%
rename from shared/email.go
rename to app/shared/email.go
diff --git a/shared/go.mod b/app/shared/go.mod
similarity index 100%
rename from shared/go.mod
rename to app/shared/go.mod
diff --git a/shared/go.sum b/app/shared/go.sum
similarity index 100%
rename from shared/go.sum
rename to app/shared/go.sum
diff --git a/shared/models.go b/app/shared/models.go
similarity index 100%
rename from shared/models.go
rename to app/shared/models.go
diff --git a/shared/plan_result.go b/app/shared/plan_result.go
similarity index 97%
rename from shared/plan_result.go
rename to app/shared/plan_result.go
index 07ad4040..fced5d31 100644
--- a/shared/plan_result.go
+++ b/app/shared/plan_result.go
@@ -2,7 +2,6 @@ package shared
import (
"fmt"
- "log"
"sort"
"strings"
"time"
@@ -141,7 +140,7 @@ func (planState *CurrentPlanState) GetFilesBeforeReplacement(
_, hasPath := planRes.FileResultsByPath[contextPart.FilePath]
- log.Printf("hasPath: %v\n", hasPath)
+ // log.Printf("hasPath: %v\n", hasPath)
if hasPath {
files[contextPart.FilePath] = contextPart.Body
@@ -152,8 +151,8 @@ func (planState *CurrentPlanState) GetFilesBeforeReplacement(
for path, planResults := range planRes.FileResultsByPath {
updated := files[path]
- log.Printf("path: %s\n", path)
- log.Printf("updated: %s\n", updated)
+ // log.Printf("path: %s\n", path)
+ // log.Printf("updated: %s\n", updated)
PlanResLoop:
for _, planRes := range planResults {
@@ -161,8 +160,6 @@ func (planState *CurrentPlanState) GetFilesBeforeReplacement(
continue
}
- log.Println("planRes:", planRes)
-
if len(planRes.Replacements) == 0 {
if updated != "" {
return nil, fmt.Errorf("plan updates out of order: %s", path)
diff --git a/shared/req_res.go b/app/shared/req_res.go
similarity index 100%
rename from shared/req_res.go
rename to app/shared/req_res.go
diff --git a/shared/stream.go b/app/shared/stream.go
similarity index 92%
rename from shared/stream.go
rename to app/shared/stream.go
index ce2cc4ca..d2fe3888 100644
--- a/shared/stream.go
+++ b/app/shared/stream.go
@@ -12,7 +12,6 @@ const EVENT_DESCRIBE = "describe"
const EVENT_BUILD = "build"
const EVENT_FINISH = "finish"
const EVENT_ABORT = "abort"
-const EVENT_REVISE = "revise"
const EVENT_CANCEL = "cancel"
const EVENT_ERROR = "error"
@@ -34,7 +33,6 @@ func NewPlanStreamState() *fsm.FSM {
{Name: EVENT_FINISH, Src: []string{STATE_DESCRIBING, STATE_BUILDING}, Dst: STATE_FINISHED},
{Name: EVENT_ABORT, Src: []string{STATE_REPLYING, STATE_DESCRIBING, STATE_BUILDING},
Dst: STATE_ABORTED},
- {Name: EVENT_REVISE, Src: []string{STATE_ABORTED}, Dst: STATE_REPLYING},
{Name: EVENT_CANCEL, Src: []string{STATE_ABORTED}, Dst: STATE_CANCELED},
{Name: EVENT_ERROR, Src: []string{STATE_REPLYING, STATE_DESCRIBING, STATE_BUILDING}},
},
diff --git a/shared/tokens.go b/app/shared/tokens.go
similarity index 100%
rename from shared/tokens.go
rename to app/shared/tokens.go
diff --git a/shared/utils.go b/app/shared/utils.go
similarity index 100%
rename from shared/utils.go
rename to app/shared/utils.go
diff --git a/dev.sh b/dev.sh
index e68d041e..6e21caf3 100755
--- a/dev.sh
+++ b/dev.sh
@@ -8,6 +8,8 @@ terminate() {
trap terminate SIGTERM SIGINT
+cd app
+
(cd cli && ./dev.sh)
reflex -r '^(cli|shared)/.*\.(go|mod|sum)$' -- sh -c 'cd cli && ./dev.sh' &
diff --git a/server/db/auth_helpers.go b/server/db/auth_helpers.go
deleted file mode 100644
index e28ca5b7..00000000
--- a/server/db/auth_helpers.go
+++ /dev/null
@@ -1,135 +0,0 @@
-package db
-
-import (
- "crypto/sha256"
- "database/sql"
- "encoding/hex"
- "fmt"
- "time"
-
- "github.com/google/uuid"
- "github.com/pkg/errors"
-)
-
-const tokenExpirationDays = 90 // (free trial tokens don't expire)
-
-func CreateAuthToken(userId string, isTrial bool, tx *sql.Tx) (token, id string, err error) {
- uid := uuid.New()
- bytes := uid[:]
- hashBytes := sha256.Sum256(bytes)
- hash := hex.EncodeToString(hashBytes[:])
-
- err = tx.QueryRow("INSERT INTO auth_tokens (user_id, token_hash, is_trial) VALUES ($1, $2, $3) RETURNING id", userId, hash, isTrial).Scan(&id)
-
- if err != nil {
- return "", "", fmt.Errorf("error creating auth token: %v", err)
- }
-
- return uid.String(), id, nil
-}
-
-func ValidateAuthToken(token string) (*AuthToken, error) {
- uid, err := uuid.Parse(token)
-
- if err != nil {
- return nil, errors.New("invalid token")
- }
-
- bytes := uid[:]
- hashBytes := sha256.Sum256(bytes)
- tokenHash := hex.EncodeToString(hashBytes[:])
-
- var authToken AuthToken
- // free trial tokens don't expire
- err = Conn.Get(&authToken, "SELECT * FROM auth_tokens WHERE token_hash = $1 AND (created_at > $2 OR is_trial = TRUE) AND deleted_at IS NULL", tokenHash, time.Now().AddDate(0, 0, -tokenExpirationDays))
-
- if err != nil {
- if err == sql.ErrNoRows {
- return nil, errors.New("invalid token")
- }
-
- return nil, fmt.Errorf("error validating token: %v", err)
- }
-
- return &authToken, nil
-}
-
-func CreateEmailVerification(email string, userId, pinHash string) error {
- _, err := Conn.Exec("INSERT INTO email_verifications (email, pin_hash, user_id) VALUES ($1, $2, $3)", email, pinHash, userId)
-
- if err != nil {
- return fmt.Errorf("error creating email verification: %v", err)
- }
-
- return nil
-}
-
-// email verifications expire in 5 minutes
-const emailVerificationExpirationMinutes = 5
-
-func ValidateEmailVerification(email, pin string) (id string, err error) {
- pinHashBytes := sha256.Sum256([]byte(pin))
- pinHash := hex.EncodeToString(pinHashBytes[:])
-
- var authTokenId string
-
- query := `SELECT id, auth_token_id
- FROM email_verifications
- WHERE pin_hash = $1
- AND email = $2
- AND created_at > $3`
-
- err = Conn.QueryRow(query, pinHash, email, time.Now().Add(-emailVerificationExpirationMinutes*time.Minute)).Scan(&id, &authTokenId)
- if err != nil {
- if err == sql.ErrNoRows {
- return "", errors.New("invalid pin")
- }
- return "", fmt.Errorf("error validating email verification: %v", err)
- }
-
- if authTokenId != "" {
- return "", errors.New("pin already verified")
- }
-
- return id, nil
-}
-
-func GetUserPermissions(userId, orgId string) ([]string, error) {
- var permissions []string
-
- query := `
- SELECT p.name, p.resource_id
- FROM permissions p
- JOIN org_roles_permissions orp ON p.id = orp.permission_id
- JOIN orgs_users ou ON orp.org_role_id = ou.org_role_id
- WHERE ou.user_id = $1 AND ou.org_id = $2
- `
-
- rows, err := Conn.Query(query, userId, orgId)
- if err != nil {
- return nil, err
- }
- defer rows.Close()
-
- for rows.Next() {
- var permission string
- var resourceId sql.NullString
- if err := rows.Scan(&permission, &resourceId); err != nil {
- return nil, err
- }
-
- toAdd := permission
- if resourceId.Valid {
- toAdd = toAdd + "|" + resourceId.String
- }
-
- permissions = append(permissions, toAdd)
- }
-
- // Check for errors from iterating over rows.
- if err = rows.Err(); err != nil {
- return nil, err
- }
-
- return permissions, nil
-}
diff --git a/server/db/build_helpers.go b/server/db/build_helpers.go
deleted file mode 100644
index 06ef3a0d..00000000
--- a/server/db/build_helpers.go
+++ /dev/null
@@ -1,42 +0,0 @@
-package db
-
-import (
- "fmt"
- "time"
-)
-
-func StorePlanBuild(build *PlanBuild) error {
- query := `INSERT INTO plan_builds (org_id, plan_id, convo_message_id) VALUES (:org_id, :plan_id, :convo_message_id) RETURNING id, created_at, updated_at`
-
- row, err := Conn.NamedQuery(query, build)
-
- if err != nil {
- return fmt.Errorf("error storing plan build: %v", err)
- }
-
- defer row.Close()
-
- if row.Next() {
- var createdAt, updatedAt time.Time
- var id string
- if err := row.Scan(&id, &createdAt, &updatedAt); err != nil {
- return fmt.Errorf("error storing plan build: %v", err)
- }
-
- build.Id = id
- build.CreatedAt = createdAt
- build.UpdatedAt = updatedAt
- }
-
- return nil
-}
-
-func SetBuildError(build *PlanBuild) error {
- _, err := Conn.Exec("UPDATE plan_builds SET error = $1, error_path = $2 WHERE id = $3", build.Error, build.ErrorPath, build.Id)
-
- if err != nil {
- return fmt.Errorf("error setting build error: %v", err)
- }
-
- return nil
-}
diff --git a/server/db/context_helpers.go b/server/db/context_helpers.go
deleted file mode 100644
index 9deacbf6..00000000
--- a/server/db/context_helpers.go
+++ /dev/null
@@ -1,152 +0,0 @@
-package db
-
-import (
- "encoding/json"
- "fmt"
- "os"
- "path/filepath"
- "sort"
- "strings"
- "time"
-
- "github.com/google/uuid"
-)
-
-func GetPlanContexts(orgId, planId string, includeBody bool) ([]*Context, error) {
- var contexts []*Context
- contextDir := getPlanContextDir(orgId, planId)
-
- // get all context files
- files, err := os.ReadDir(contextDir)
- if err != nil {
- return nil, fmt.Errorf("error reading context dir: %v", err)
- }
-
- errCh := make(chan error, len(files)/2)
- contextCh := make(chan *Context, len(files)/2)
-
- // read each context file
- for _, file := range files {
- if strings.HasSuffix(file.Name(), ".meta") {
- go func(file os.DirEntry) {
- context, err := GetContext(orgId, planId, strings.TrimSuffix(file.Name(), ".meta"), includeBody)
-
- if err != nil {
- errCh <- fmt.Errorf("error reading context file: %v", err)
- return
- }
-
- contextCh <- context
- }(file)
- }
- }
-
- for i := 0; i < len(files)/2; i++ {
- select {
- case err := <-errCh:
- return nil, fmt.Errorf("error reading context files: %v", err)
- case context := <-contextCh:
- contexts = append(contexts, context)
- }
- }
-
- // sort contexts by CreatedAt
- sort.Slice(contexts, func(i, j int) bool {
- return contexts[i].CreatedAt.Before(contexts[j].CreatedAt)
- })
-
- return contexts, nil
-}
-
-func GetContext(orgId, planId, contextId string, includeBody bool) (*Context, error) {
- contextDir := getPlanContextDir(orgId, planId)
-
- // read the meta file
- metaPath := filepath.Join(contextDir, contextId+".meta")
-
- metaBytes, err := os.ReadFile(metaPath)
- if err != nil {
- return nil, fmt.Errorf("error reading context meta file: %v", err)
- }
-
- var context Context
- err = json.Unmarshal(metaBytes, &context)
- if err != nil {
- return nil, fmt.Errorf("error unmarshalling context meta file: %v", err)
- }
-
- if includeBody {
- // read the body file
- bodyPath := filepath.Join(contextDir, strings.TrimSuffix(contextId, ".meta")+".body")
- bodyBytes, err := os.ReadFile(bodyPath)
-
- if err != nil {
- return nil, fmt.Errorf("error reading context body file: %v", err)
- }
-
- context.Body = string(bodyBytes)
- }
-
- return &context, nil
-}
-
-func ContextRemove(contexts []*Context) error {
- // remove files
- numFiles := len(contexts) * 2
-
- errCh := make(chan error, numFiles)
- for _, context := range contexts {
- contextDir := getPlanContextDir(context.OrgId, context.PlanId)
- for _, ext := range []string{".meta", ".body"} {
- go func(context *Context, dir, ext string) {
- errCh <- os.Remove(filepath.Join(dir, context.Id+ext))
- }(context, contextDir, ext)
- }
- }
-
- for i := 0; i < numFiles; i++ {
- err := <-errCh
- if err != nil {
- return fmt.Errorf("error removing context file: %v", err)
- }
- }
-
- return nil
-}
-
-func StoreContext(context *Context) error {
- contextDir := getPlanContextDir(context.OrgId, context.PlanId)
-
- ts := time.Now().UTC()
- if context.Id == "" {
- context.Id = uuid.New().String()
- context.CreatedAt = ts
- }
- context.UpdatedAt = ts
-
- metaFilename := context.Id + ".meta"
- metaPath := filepath.Join(contextDir, metaFilename)
-
- bodyFilename := context.Id + ".body"
- bodyPath := filepath.Join(contextDir, bodyFilename)
- body := []byte(context.Body)
- context.Body = ""
-
- // Convert the ModelContextPart to JSON
- data, err := json.MarshalIndent(context, "", " ")
- if err != nil {
- return fmt.Errorf("failed to marshal context context: %v", err)
- }
-
- // Write the body to the file
- if err = os.WriteFile(bodyPath, body, 0644); err != nil {
- return fmt.Errorf("failed to write context body to file %s: %v", bodyPath, err)
- }
-
- // Write the meta data to the file
- if err = os.WriteFile(metaPath, data, 0644); err != nil {
- return fmt.Errorf("failed to write context meta to file %s: %v", metaPath, err)
- }
-
- return nil
-}
diff --git a/server/db/convo_helpers.go b/server/db/convo_helpers.go
deleted file mode 100644
index 720f18be..00000000
--- a/server/db/convo_helpers.go
+++ /dev/null
@@ -1,149 +0,0 @@
-package db
-
-import (
- "encoding/json"
- "fmt"
- "os"
- "path/filepath"
- "sort"
- "time"
-
- "github.com/google/uuid"
- "github.com/sashabaranov/go-openai"
-)
-
-func GetPlanConvo(orgId, planId string) ([]*ConvoMessage, error) {
- var convo []*ConvoMessage
- convoDir := getPlanConversationDir(orgId, planId)
-
- files, err := os.ReadDir(convoDir)
- if err != nil {
- return nil, fmt.Errorf("error reading convo dir: %v", err)
- }
-
- errCh := make(chan error, len(files))
- convoCh := make(chan *ConvoMessage, len(files))
-
- for _, file := range files {
- go func(file os.DirEntry) {
- bytes, err := os.ReadFile(filepath.Join(convoDir, file.Name()))
-
- if err != nil {
- errCh <- fmt.Errorf("error reading convo file: %v", err)
- return
- }
-
- var convoMessage ConvoMessage
- err = json.Unmarshal(bytes, &convoMessage)
-
- if err != nil {
- errCh <- fmt.Errorf("error unmarshalling convo file: %v", err)
- return
- }
-
- convoCh <- &convoMessage
-
- }(file)
- }
-
- for i := 0; i < len(files); i++ {
- select {
- case err := <-errCh:
- return nil, fmt.Errorf("error reading convo files: %v", err)
- case convoMessage := <-convoCh:
- convo = append(convo, convoMessage)
- }
- }
-
- sort.Slice(convo, func(i, j int) bool {
- return convo[i].CreatedAt.Before(convo[j].CreatedAt)
- })
-
- return convo, nil
-}
-
-func StoreConvoMessage(message *ConvoMessage, commit bool) (string, error) {
- convoDir := getPlanConversationDir(message.OrgId, message.PlanId)
-
- id := uuid.New().String()
- ts := time.Now().UTC()
-
- message.Id = id
- message.CreatedAt = ts
-
- bytes, err := json.Marshal(message)
-
- if err != nil {
- return "", fmt.Errorf("error marshalling convo message: %v", err)
- }
-
- err = os.WriteFile(filepath.Join(convoDir, message.Id+".json"), bytes, os.ModePerm)
-
- if err != nil {
- return "", fmt.Errorf("error writing convo message: %v", err)
- }
-
- err = AddPlanConvoMessage(message.PlanId, message.Tokens)
-
- if err != nil {
- return "", fmt.Errorf("error adding convo tokens: %v", err)
- }
-
- var desc string
- if message.Role == openai.ChatMessageRoleUser {
- desc = "💬 User prompt"
- // TODO: add user name
- } else {
- desc = "🤖 Plandex reply"
- if message.Stopped {
- desc += " | 🛑 stopped early"
- }
- }
-
- msg := fmt.Sprintf("Message #%d | %s | %d 🪙", message.Num, desc, message.Tokens)
-
- if commit {
- err = GitAddAndCommit(message.OrgId, message.PlanId, msg)
- if err != nil {
- return "", fmt.Errorf("error committing convo message: %v", err)
- }
- }
-
- return msg, nil
-}
-
-func GetPlanSummaries(planId string) ([]*ConvoSummary, error) {
- var summaries []*ConvoSummary
-
- err := Conn.Select(&summaries, "SELECT * FROM convo_summaries WHERE plan_id = $1 ORDER BY created_at", planId)
-
- if err != nil {
- return nil, fmt.Errorf("error getting plan summaries: %v", err)
- }
- return summaries, nil
-}
-
-func StoreSummary(summary *ConvoSummary) error {
- query := "INSERT INTO convo_summaries (org_id, plan_id, latest_convo_message_id, latest_convo_message_created_at, summary, tokens, num_messages, created_at) VALUES (:org_id, :plan_id, :latest_convo_message_id, :latest_convo_message_created_at, :summary, :tokens, :num_messages, :created_at) RETURNING id, created_at"
-
- row, err := Conn.NamedQuery(query, summary)
-
- if err != nil {
- return fmt.Errorf("error storing summary: %v", err)
- }
-
- defer row.Close()
-
- if row.Next() {
- var createdAt time.Time
- var id string
- if err := row.Scan(&id, &createdAt); err != nil {
- return fmt.Errorf("error storing summary: %v", err)
- }
-
- summary.Id = id
- summary.CreatedAt = createdAt
- }
-
- return nil
-}
diff --git a/server/db/db.go b/server/db/db.go
deleted file mode 100644
index 8e711f32..00000000
--- a/server/db/db.go
+++ /dev/null
@@ -1,85 +0,0 @@
-package db
-
-import (
- "errors"
- "fmt"
- "log"
- "os"
-
- "github.com/golang-migrate/migrate/v4"
- "github.com/golang-migrate/migrate/v4/database/postgres"
- _ "github.com/golang-migrate/migrate/v4/source/file"
- "github.com/jmoiron/sqlx"
- _ "github.com/lib/pq"
-)
-
-var Conn *sqlx.DB
-
-func Connect() error {
- var err error
-
- if os.Getenv("DATABASE_URL") == "" {
- return errors.New("DATABASE_URL not set")
- }
-
- Conn, err = sqlx.Connect("postgres", os.Getenv("DATABASE_URL"))
- if err != nil {
- return err
- }
- return nil
-}
-
-func MigrationsUp() error {
- if Conn == nil {
- return errors.New("db not initialized")
- }
-
- driver, err := postgres.WithInstance(Conn.DB, &postgres.Config{})
-
- if err != nil {
- return fmt.Errorf("error creating postgres driver: %v", err)
- }
-
- m, err := migrate.NewWithDatabaseInstance(
- "file://migrations",
- "postgres", driver)
-
- if err != nil {
- return fmt.Errorf("error creating migration instance: %v", err)
- }
-
- // Uncomment below to reset migration state to a specific version after a failure
- // if err := m.Force(2024011700); err != nil {
- // return fmt.Errorf("error forcing migration version: %v", err)
- // }
-
- // Uncomment below to run down migrations in development (resets database)
- // if os.Getenv("GOENV") == "development" {
- // err = m.Down()
- // if err != nil {
- // if err == migrate.ErrNoChange {
- // log.Println("no migrations to run down")
- // } else {
- // return fmt.Errorf("error running down migrations: %v", err)
- // }
- // }
- // log.Println("ran down migrations - database was reset")
- // }
-
- err = m.Up()
-
- if err != nil {
- if err == migrate.ErrNoChange {
- log.Println("migration state is up to date")
- } else {
-
- return fmt.Errorf("error running migrations: %v", err)
- }
- }
-
- if err == nil {
- log.Println("ran migrations successfully")
- }
-
- return nil
-}
diff --git a/server/db/fs.go b/server/db/fs.go
deleted file mode 100644
index 08de7650..00000000
--- a/server/db/fs.go
+++ /dev/null
@@ -1,78 +0,0 @@
-package db
-
-import (
- "fmt"
- "os"
- "path/filepath"
-)
-
-var BaseDir string
-
-func init() {
- home, err := os.UserHomeDir()
- if err != nil {
- panic(fmt.Errorf("error getting user home dir: %v", err))
- }
-
- BaseDir = filepath.Join(home, "plandex-server")
-}
-
-func InitPlan(orgId, planId string) error {
- dir := getPlanDir(orgId, planId)
- err := os.MkdirAll(dir, os.ModePerm)
-
- if err != nil {
- return fmt.Errorf("error creating plan dir: %v", err)
- }
-
- for _, subdirFn := range [](func(orgId, planId string) string){
- getPlanContextDir,
- getPlanConversationDir,
- getPlanResultsDir,
- getPlanDescriptionsDir} {
- err = os.MkdirAll(subdirFn(orgId, planId), os.ModePerm)
-
- if err != nil {
- return fmt.Errorf("error creating plan subdir: %v", err)
- }
- }
-
- err = InitGitRepo(orgId, planId)
-
- if err != nil {
- return fmt.Errorf("error initializing git repo: %v", err)
- }
-
- return nil
-}
-
-func DeletePlanDir(orgId, planId string) error {
- dir := getPlanDir(orgId, planId)
- err := os.RemoveAll(dir)
-
- if err != nil {
- return fmt.Errorf("error deleting plan dir: %v", err)
- }
-
- return nil
-}
-
-func getPlanDir(orgId, planId string) string {
- return filepath.Join(BaseDir, "orgs", orgId, "plans", planId)
-}
-
-func getPlanContextDir(orgId, planId string) string {
- return filepath.Join(getPlanDir(orgId, planId), "context")
-}
-
-func getPlanConversationDir(orgId, planId string) string {
- return filepath.Join(getPlanDir(orgId, planId), "conversation")
-}
-
-func getPlanResultsDir(orgId, planId string) string {
- return filepath.Join(getPlanDir(orgId, planId), "results")
-}
-
-func getPlanDescriptionsDir(orgId, planId string) string {
- return filepath.Join(getPlanDir(orgId, planId), "descriptions")
-}
diff --git a/server/db/git.go b/server/db/git.go
deleted file mode 100644
index 3b70e261..00000000
--- a/server/db/git.go
+++ /dev/null
@@ -1,204 +0,0 @@
-package db
-
-import (
- "bytes"
- "fmt"
- "os/exec"
- "strconv"
- "strings"
- "time"
-
- "github.com/fatih/color"
-)
-
-func init() {
- // ensure git is available
- cmd := exec.Command("git", "--version")
- if err := cmd.Run(); err != nil {
- panic(fmt.Errorf("error running git --version: %v", err))
- }
-}
-
-func InitGitRepo(orgId, planId string) error {
- dir := getPlanDir(orgId, planId)
-
- res, err := exec.Command("git", "init", dir).CombinedOutput()
- if err != nil {
- return fmt.Errorf("error initializing git repository for dir: %s, err: %v, output: %s", dir, err, string(res))
- }
-
- return nil
-}
-
-func GitAddAndCommit(orgId, planId, message string) error {
- dir := getPlanDir(orgId, planId)
-
- err := gitAdd(dir, ".")
- if err != nil {
- return fmt.Errorf("error adding files to git repository for dir: %s, err: %v", dir, err)
- }
-
- err = gitCommit(dir, message)
- if err != nil {
- return fmt.Errorf("error committing files to git repository for dir: %s, err: %v", dir, err)
- }
-
- return nil
-}
-
-func GitRewindToSha(orgId, planId, sha string) error {
- dir := getPlanDir(orgId, planId)
-
- err := gitRewindToSha(dir, sha)
- if err != nil {
- return fmt.Errorf("error rewinding git repository for dir: %s, err: %v", dir, err)
- }
-
- return nil
-}
-
-func GetGitCommitHistory(orgId, planId string) (body string, shas []string, err error) {
- dir := getPlanDir(orgId, planId)
-
- body, shas, err = getGitCommitHistory(dir)
- if err != nil {
- return "", nil, fmt.Errorf("error getting git history for dir: %s, err: %v", dir, err)
- }
-
- return body, shas, nil
-}
-
-func GetLatestCommit(orgId, planId string) (sha, body string, err error) {
- dir := getPlanDir(orgId, planId)
-
- sha, body, err = getLatestCommit(dir)
- if err != nil {
- return "", "", fmt.Errorf("error getting latest commit for dir: %s, err: %v", dir, err)
- }
-
- return sha, body, nil
-}
-
-func gitRewindToSha(repoDir, sha string) error {
- res, err := exec.Command("git", "-C", repoDir, "reset", "--hard",
- sha).CombinedOutput()
-
- if err != nil {
- return fmt.Errorf("error executing git reset for dir: %s, sha: %s, err: %v, output: %s", repoDir, sha, err, string(res))
- }
-
- return nil
-}
-
-func getLatestCommit(dir string) (sha, body string, err error) {
- var out bytes.Buffer
- cmd := exec.Command("git", "log", "--pretty=%h@@|@@%at@@|@@%B@>>>@")
- cmd.Dir = dir
- cmd.Stdout = &out
- err = cmd.Run()
- if err != nil {
- return "", "", fmt.Errorf("error getting git history for dir: %s, err: %v",
- dir, err)
- }
-
- // Process the log output to get it in the desired format.
- history := processGitHistoryOutput(strings.TrimSpace(out.String()))
-
- first := history[0]
-
- sha = first[0]
- body = first[1]
-
- return sha, body, nil
-}
-
-func getGitCommitHistory(dir string) (body string, shas []string, err error) {
- var out bytes.Buffer
- cmd := exec.Command("git", "log", "--pretty=%h@@|@@%at@@|@@%B@>>>@")
- cmd.Dir = dir
- cmd.Stdout = &out
- err = cmd.Run()
- if err != nil {
- return "", nil, fmt.Errorf("error getting git history for dir: %s, err: %v",
- dir, err)
- }
-
- // Process the log output to get it in the desired format.
- history := processGitHistoryOutput(strings.TrimSpace(out.String()))
-
- var output []string
- for _, el := range history {
- shas = append(shas, el[0])
- output = append(output, el[1])
- }
-
- return strings.Join(output, "\n\n"), shas, nil
-}
-
-// processGitHistoryOutput processes the raw output from the git log command and returns a formatted string.
-func processGitHistoryOutput(raw string) [][2]string {
- var history [][2]string
- entries := strings.Split(raw, "@>>>@") // Split entries using the custom separator.
-
- for _, entry := range entries {
- // First clean up any leading/trailing whitespace or newlines from each entry.
- entry = strings.TrimSpace(entry)
-
- // Now split the cleaned entry into its parts.
- parts := strings.Split(entry, "@@|@@")
- if len(parts) == 3 {
- sha := parts[0]
- timestampStr := parts[1]
- message := strings.TrimSpace(parts[2]) // Trim whitespace from message as well.
-
- // Extract and format timestamp.
- timestamp, err := strconv.ParseInt(timestampStr, 10, 64)
- if err != nil {
- continue // Skip entries with invalid timestamps.
- }
-
- dt := time.Unix(timestamp, 0).Local()
- formattedTs := dt.Format("Mon Jan 2, 2006 | 3:04:05pm MST")
- if dt.Day() == time.Now().Day() {
- formattedTs = dt.Format("Today | 3:04:05pm MST")
- } else if dt.Day() == time.Now().AddDate(0, 0, -1).Day() {
- formattedTs = dt.Format("Yesterday | 3:04:05pm MST")
- }
-
- // Prepare the header with colors.
- headerColor := color.New(color.FgCyan, color.Bold)
- dateColor := color.New(color.FgCyan)
-
- // Combine sha, formatted timestamp, and message header into one string.
- header := fmt.Sprintf("%s | %s", headerColor.Sprintf("📝 Update %s", sha), dateColor.Sprintf("%s", formattedTs))
-
- // Combine header and message with a newline only if the message is not empty.
- fullEntry := header
- if message != "" {
- fullEntry += "\n" + message
- }
-
- history = append(history, [2]string{sha, fullEntry})
- }
- }
-
- return history
-}
-
-func gitAdd(repoDir, path string) error {
- res, err := exec.Command("git", "-C", repoDir, "add", path).CombinedOutput()
- if err != nil {
- return fmt.Errorf("error adding files to git repository for dir: %s, err: %v, output: %s", repoDir, err, string(res))
- }
-
- return nil
-}
-
-func gitCommit(repoDir, commitMsg string) error {
- res, err := exec.Command("git", "-C", repoDir, "commit", "-m", commitMsg).CombinedOutput()
- if err != nil {
- return fmt.Errorf("error committing files to git repository for dir: %s, err: %v, output: %s", repoDir, err, string(res))
- }
-
- return nil
-}
diff --git a/server/db/invite_helpers.go b/server/db/invite_helpers.go
deleted file mode 100644
index 194d92cb..00000000
--- a/server/db/invite_helpers.go
+++ /dev/null
@@ -1,149 +0,0 @@
-package db
-
-import (
- "database/sql"
- "fmt"
- "log"
- "strings"
-)
-
-func CreateInvite(invite *Invite) error {
- _, err := Conn.NamedExec(`INSERT INTO invites (id, org_id, email, name, inviter_id) VALUES (:id, :org_id, :email, :name, :inviter_id)`, invite)
- if err != nil {
- return fmt.Errorf("error creating invite: %v", err)
- }
-
- return nil
-}
-
-func GetInvite(id string) (*Invite, error) {
- var invite Invite
- err := Conn.Get(&invite, "SELECT * FROM invites WHERE id = $1", id)
-
- if err != nil {
- return nil, fmt.Errorf("error getting invite: %v", err)
- }
-
- return &invite, nil
-}
-
-func GetInviteForOrgUser(orgId, userId string) (*Invite, error) {
- var invite Invite
- err := Conn.Get(&invite, "SELECT * FROM invites WHERE org_id = $1 AND invitee_id = $2", orgId, userId)
-
- if err != nil {
- if err == sql.ErrNoRows {
- return nil, nil
- }
-
- return nil, fmt.Errorf("error getting invite: %v", err)
- }
-
- return &invite, nil
-}
-
-func ListPendingInvites(orgId string) ([]*Invite, error) {
- var invites []*Invite
- err := Conn.Select(&invites, "SELECT * FROM invites WHERE org_id = $1 AND accepted_at IS NULL", orgId)
-
- if err != nil {
- return nil, fmt.Errorf("error getting invites for org: %v", err)
- }
-
- return invites, nil
-}
-
-func ListAllInvites(orgId string) ([]*Invite, error) {
- var invites []*Invite
- err := Conn.Select(&invites, "SELECT * FROM invites WHERE org_id = $1", orgId)
-
- if err != nil {
- return nil, fmt.Errorf("error getting invites for org: %v", err)
- }
-
- return invites, nil
-}
-
-func ListAcceptedInvites(orgId string) ([]*Invite, error) {
- var invites []*Invite
- err := Conn.Select(&invites, "SELECT * FROM invites WHERE org_id = $1 AND accepted_at IS NOT NULL", orgId)
-
- if err != nil {
- return nil, fmt.Errorf("error getting invites for org: %v", err)
- }
-
- return invites, nil
-}
-
-func GetPendingInvitesForEmail(email string) ([]*Invite, error) {
- email = strings.ToLower(email)
- var invites []*Invite
- err := Conn.Select(&invites, "SELECT * FROM invites WHERE email = $1 AND accepted_at IS NULL", email)
- if err != nil {
- if err == sql.ErrNoRows {
- return nil, nil
- }
-
- return nil, fmt.Errorf("error getting invites and org names for email: %v", err)
- }
-
- return invites, nil
-}
-
-func DeleteInvite(id string, tx *sql.Tx) error {
- query := "DELETE FROM invites WHERE id = $1"
- var err error
-
- if tx == nil {
- _, err = tx.Exec(query, id)
- } else {
- _, err = Conn.Exec(query, id)
- }
-
- if err != nil {
- return fmt.Errorf("error deleting invite: %v", err)
- }
-
- return nil
-}
-
-func AcceptInvite(invite *Invite, inviteeId string) error {
- // start a transaction
- tx, err := Conn.Begin()
- if err != nil {
- return fmt.Errorf("error starting transaction: %v", err)
- }
-
- // 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")
- }
- }
- }()
-
- _, err = tx.Exec(`UPDATE invites SET accepted_at = NOW(), invitee_id = $1 WHERE id = $2`, inviteeId, invite.Id)
- if err != nil {
- return fmt.Errorf("error accepting invite: %v", err)
- }
-
- // create org user
- err = CreateOrgUser(invite.OrgId, invite.InviteeId, invite.OrgRoleId, tx)
-
- if err != nil {
- return fmt.Errorf("error creating org user: %v", err)
- }
-
- // commit transaction
- err = tx.Commit()
- if err != nil {
- return fmt.Errorf("error committing transaction: %v", err)
- }
-
- invite.InviteeId = inviteeId
-
- return nil
-}
diff --git a/server/db/models.go b/server/db/models.go
deleted file mode 100644
index 2c1c3732..00000000
--- a/server/db/models.go
+++ /dev/null
@@ -1,346 +0,0 @@
-package db
-
-import (
- "time"
-
- "github.com/plandex/plandex/shared"
-)
-
-// The models below should only be used server-side.
-// Many of them have corresponding models in shared/api for client-side use.
-// This adds some duplication, but helps ensure that server-only data doesn't leak to the client.
-// Models used client-side have a ToApi() method to convert it to the corresponding client-side model.
-
-type AuthToken struct {
- Id string `db:"id"`
- UserId string `db:"user_id"`
- TokenHash string `db:"token_hash"`
- IsTrial bool `db:"is_trial"`
- CreatedAt time.Time `db:"created_at"`
- DeletedAt *time.Time `db:"deleted_at"`
-}
-
-type Org struct {
- Id string `db:"id"`
- Name string `db:"name"`
- Domain *string `db:"domain"`
- AutoAddDomainUsers bool `db:"auto_add_domain_users"`
- OwnerId string `db:"owner_id"`
- CreatedAt time.Time `db:"created_at"`
- UpdatedAt time.Time `db:"updated_at"`
-}
-
-func (org *Org) ToApi() *shared.Org {
- return &shared.Org{
- Id: org.Id,
- Name: org.Name,
- }
-}
-
-type User struct {
- Id string `db:"id"`
- Name string `db:"name"`
- Email string `db:"email"`
- Domain string `db:"domain"`
- NumNonDraftPlans int `db:"num_non_draft_plans"`
- IsTrial bool `db:"is_trial"`
- OrgRoleId string `db:"org_role_id"`
- CreatedAt time.Time `db:"created_at"`
- UpdatedAt time.Time `db:"updated_at"`
-}
-
-func (user *User) ToApi() *shared.User {
- return &shared.User{
- Id: user.Id,
- Name: user.Name,
- Email: user.Email,
- OrgRoleId: user.OrgRoleId,
- NumNonDraftPlans: user.NumNonDraftPlans,
- IsTrial: user.IsTrial,
- }
-}
-
-type Invite struct {
- Id string `db:"id"`
- OrgId string `db:"org_id"`
- Email string `db:"email"`
- Name string `db:"name"`
- InviterId string `db:"inviter_id"`
- InviteeId string `db:"invitee_id"`
- OrgRoleId string `db:"org_role_id"`
- AcceptedAt *time.Time `db:"accepted_at"`
- CreatedAt time.Time `db:"created_at"`
- UpdatedAt time.Time `db:"updated_at"`
-}
-
-func (invite *Invite) ToApi() *shared.Invite {
- return &shared.Invite{
- Id: invite.Id,
- OrgId: invite.OrgId,
- Email: invite.Email,
- Name: invite.Name,
- InviterId: invite.InviterId,
- InviteeId: invite.InviteeId,
- OrgRoleId: invite.OrgRoleId,
- AcceptedAt: invite.AcceptedAt,
- CreatedAt: invite.CreatedAt,
- }
-}
-
-type OrgUser struct {
- Id string `db:"id"`
- OrgId string `db:"org_id"`
- UserId string `db:"user_id"`
- CreatedAt time.Time `db:"created_at"`
- UpdatedAt time.Time `db:"updated_at"`
-}
-
-type Project struct {
- Id string `db:"id"`
- OrgId string `db:"org_id"`
- Name string `db:"name"`
- LastActivePlanId string `db:"last_active_plan_id"`
- CreatedAt time.Time `db:"created_at"`
- UpdatedAt time.Time `db:"updated_at"`
-}
-
-func (project *Project) ToApi() *shared.Project {
- return &shared.Project{
- Id: project.Id,
- Name: project.Name,
- LastActivePlanId: project.LastActivePlanId,
- }
-}
-
-type UserProject struct {
- Id string `db:"id"`
- OrgId string `db:"org_id"`
- UserId string `db:"user_id"`
- ProjectId string `db:"project_id"`
- LastActivePlanId string `db:"last_active_plan_id"`
- CreatedAt time.Time `db:"created_at"`
- UpdatedAt time.Time `db:"updated_at"`
-}
-
-type Plan struct {
- Id string `db:"id"`
- OrgId string `db:"org_id"`
- OwnerId string `db:"owner_id"`
- ProjectId string `db:"project_id"`
- Name string `db:"name"`
- Status shared.PlanStatus `db:"status"`
- Error *string `db:"error"`
- ContextTokens int `db:"context_tokens"`
- ConvoTokens int `db:"convo_tokens"`
- SharedWithOrgAt *time.Time `db:"shared_with_org_at,omitempty"`
- TotalMessages int `db:"total_messages"`
- ArchivedAt *time.Time `db:"archived_at,omitempty"`
- CreatedAt time.Time `db:"created_at"`
- UpdatedAt time.Time `db:"updated_at"`
-}
-
-func (plan *Plan) ToApi() *shared.Plan {
- return &shared.Plan{
- Id: plan.Id,
- OwnerId: plan.OwnerId,
- Name: plan.Name,
- Status: plan.Status,
- ContextTokens: plan.ContextTokens,
- ConvoTokens: plan.ConvoTokens,
- SharedWithOrgAt: plan.SharedWithOrgAt,
- TotalMessages: plan.TotalMessages,
- ArchivedAt: plan.ArchivedAt,
- CreatedAt: plan.CreatedAt,
- UpdatedAt: plan.UpdatedAt,
- }
-}
-
-type ConvoSummary struct {
- Id string `db:"id"`
- OrgId string `db:"org_id"`
- PlanId string `db:"plan_id"`
- LatestConvoMessageId string `db:"latest_convo_message_id"`
- LatestConvoMessageCreatedAt time.Time `db:"latest_convo_message_created_at"`
- Summary string `db:"summary"`
- Tokens int `db:"tokens"`
- NumMessages int `db:"num_messages"`
- CreatedAt time.Time `db:"created_at"`
-}
-
-func (summary *ConvoSummary) ToApi() *shared.ConvoSummary {
- return &shared.ConvoSummary{
- Id: summary.Id,
- LatestConvoMessageId: summary.LatestConvoMessageId,
- LatestConvoMessageCreatedAt: summary.LatestConvoMessageCreatedAt,
- Summary: summary.Summary,
- Tokens: summary.Tokens,
- NumMessages: summary.NumMessages,
- CreatedAt: summary.CreatedAt,
- }
-}
-
-type PlanBuild struct {
- Id string `db:"id"`
- OrgId string `db:"org_id"`
- PlanId string `db:"plan_id"`
- ConvoMessageId string `db:"convo_message_id"`
- Error string `db:"error"`
- ErrorPath string `db:"error_path"`
- CreatedAt time.Time `db:"created_at"`
- UpdatedAt time.Time `db:"updated_at"`
-}
-
-func (build *PlanBuild) ToApi() *shared.PlanBuild {
- return &shared.PlanBuild{
- Id: build.Id,
- ConvoMessageId: build.ConvoMessageId,
- Error: build.Error,
- ErrorPath: build.ErrorPath,
- CreatedAt: build.CreatedAt,
- UpdatedAt: build.UpdatedAt,
- }
-}
-
-type OrgRole struct {
- Id string `db:"id"`
- OrgId *string `db:"org_id"`
- Name string `db:"name"`
- Label string `db:"label"`
- Description string `db:"description"`
- CreatedAt time.Time `db:"created_at"`
- UpdatedAt time.Time `db:"updated_at"`
-}
-
-func (role *OrgRole) ToApi() *shared.OrgRole {
- return &shared.OrgRole{
- Id: role.Id,
- IsDefault: role.OrgId == nil,
- Label: role.Label,
- Description: role.Description,
- }
-}
-
-// Models below are stored in files, not in the database.
-// This allows us to store them in a git repo and use git to manage history.
-
-type Context struct {
- Id string `json:"id"`
- OrgId string `json:"orgId"`
- OwnerId string `json:"ownerId"`
- PlanId string `json:"planId"`
- ContextType shared.ContextType `json:"contextType"`
- Name string `json:"name"`
- Url string `json:"url"`
- FilePath string `json:"filePath"`
- Sha string `json:"sha"`
- NumTokens int `json:"numTokens"`
- Body string `json:"body,omitempty"`
- CreatedAt time.Time `json:"createdAt"`
- UpdatedAt time.Time `json:"updatedAt"`
-}
-
-func (context *Context) ToApi() *shared.Context {
- return &shared.Context{
- Id: context.Id,
- OwnerId: context.OwnerId,
- ContextType: context.ContextType,
- Name: context.Name,
- Url: context.Url,
- FilePath: context.FilePath,
- Sha: context.Sha,
- NumTokens: context.NumTokens,
- Body: context.Body,
- CreatedAt: context.CreatedAt,
- UpdatedAt: context.UpdatedAt,
- }
-}
-
-type ConvoMessage struct {
- Id string `json:"id"`
- OrgId string `json:"orgId"`
- PlanId string `json:"planId"`
- UserId string `json:"userId"`
- Role string `json:"role"`
- Tokens int `json:"tokens"`
- Num int `json:"num"`
- Message string `json:"message"`
- Stopped bool `json:"stopped"`
- CreatedAt time.Time `json:"createdAt"`
-}
-
-func (msg *ConvoMessage) ToApi() *shared.ConvoMessage {
- return &shared.ConvoMessage{
- Id: msg.Id,
- UserId: msg.UserId,
- Role: msg.Role,
- Tokens: msg.Tokens,
- Num: msg.Num,
- Message: msg.Message,
- Stopped: msg.Stopped,
- CreatedAt: msg.CreatedAt,
- }
-}
-
-type ConvoMessageDescription struct {
- Id string `json:"id"`
- OrgId string `json:"orgId"`
- PlanId string `json:"planId"`
- ConvoMessageId string `json:"convoMessageId"`
- SummarizedToMessageId string `json:"summarizedToMessageId"`
- MadePlan bool `json:"madePlan"`
- CommitMsg string `json:"commitMsg"`
- Files []string `json:"files"`
- Error string `json:"error"`
- AppliedAt *time.Time `json:"appliedAt,omitempty"`
- CreatedAt time.Time `json:"createdAt"`
- UpdatedAt time.Time `json:"updatedAt"`
-}
-
-func (desc *ConvoMessageDescription) ToApi() *shared.ConvoMessageDescription {
- return &shared.ConvoMessageDescription{
- Id: desc.Id,
- ConvoMessageId: desc.ConvoMessageId,
- SummarizedToMessageId: desc.SummarizedToMessageId,
- MadePlan: desc.MadePlan,
- CommitMsg: desc.CommitMsg,
- Files: desc.Files,
- Error: desc.Error,
- CreatedAt: desc.CreatedAt,
- UpdatedAt: desc.UpdatedAt,
- }
-}
-
-type PlanFileResult struct {
- Id string `json:"id"`
- OrgId string `json:"orgId"`
- PlanId string `json:"planId"`
- ConvoMessageId string `json:"convoMessageId"`
- PlanBuildId string `json:"planBuildId"`
- Path string `json:"path"`
- ContextSha string `json:"contextSha"`
- Content string `json:"content,omitempty"`
- Replacements []*shared.Replacement `json:"replacements"`
- AnyFailed bool `json:"anyFailed"`
- Error string `json:"error"`
- AppliedAt *time.Time `json:"appliedAt,omitempty"`
- RejectedAt *time.Time `json:"rejectedAt,omitempty"`
- CreatedAt time.Time `json:"createdAt"`
- UpdatedAt time.Time `json:"updatedAt"`
-}
-
-func (res *PlanFileResult) ToApi() *shared.PlanFileResult {
- return &shared.PlanFileResult{
- Id: res.Id,
- PlanBuildId: res.PlanBuildId,
- ConvoMessageId: res.ConvoMessageId,
- Path: res.Path,
- ContextSha: res.ContextSha,
- Content: res.Content,
- AnyFailed: res.AnyFailed,
- AppliedAt: res.AppliedAt,
- RejectedAt: res.RejectedAt,
- Replacements: res.Replacements,
- CreatedAt: res.CreatedAt,
- UpdatedAt: res.UpdatedAt,
- }
-}
diff --git a/server/db/org_helpers.go b/server/db/org_helpers.go
deleted file mode 100644
index cefd379e..00000000
--- a/server/db/org_helpers.go
+++ /dev/null
@@ -1,178 +0,0 @@
-package db
-
-import (
- "database/sql"
- "fmt"
- "strings"
-
- "github.com/plandex/plandex/shared"
-)
-
-func GetAccessibleOrgsForUser(user *User) ([]*Org, error) {
- // direct access
- var orgs []*Org
- err := Conn.Select(&orgs, "SELECT o.* FROM orgs o JOIN orgs_users ou ON o.id = ou.org_id WHERE ou.user_id = $1", user.Id)
-
- if err != nil {
- return nil, fmt.Errorf("error getting orgs for user: %v", err)
- }
-
- // access via invitation
- invites, err := GetPendingInvitesForEmail(user.Email)
-
- if err != nil {
- return nil, fmt.Errorf("error getting invites for user: %v", err)
- }
-
- var orgIds []string
- for _, invite := range invites {
- orgIds = append(orgIds, invite.OrgId)
- }
-
- if len(orgIds) > 0 {
- var orgsFromInvites []*Org
- err = Conn.Select(&orgsFromInvites, "SELECT * FROM orgs WHERE id IN (?)", strings.Join(orgIds, ","))
- if err != nil {
- return nil, fmt.Errorf("error getting orgs from invites: %v", err)
- }
- orgs = append(orgs, orgsFromInvites...)
- }
-
- return orgs, nil
-}
-
-func GetOrg(orgId string) (*Org, error) {
- var org Org
- err := Conn.Get(&org, "SELECT * FROM orgs WHERE id = $1", orgId)
-
- if err != nil {
- if err == sql.ErrNoRows {
- return nil, fmt.Errorf("org not found")
- }
-
- return nil, fmt.Errorf("error getting org: %v", err)
- }
-
- return &org, nil
-}
-
-func ValidateOrgMembership(userId string, orgId string) (bool, error) {
- var count int
- err := Conn.QueryRow("SELECT COUNT(*) FROM orgs_users WHERE user_id = $1 AND org_id = $2", userId, orgId).Scan(&count)
-
- if err != nil {
- return false, fmt.Errorf("error validating org membership: %v", err)
- }
-
- return count > 0, nil
-}
-
-func CreateOrg(req *shared.CreateOrgRequest, userId string, domain *string, tx *sql.Tx) (*Org, error) {
- org := &Org{
- Name: req.Name,
- Domain: domain,
- AutoAddDomainUsers: req.AutoAddDomainUsers,
- OwnerId: userId,
- }
-
- err := tx.QueryRow("INSERT INTO orgs (name, domain, auto_add_domain_users, owner_id) VALUES ($1, $2, $3, $4) RETURNING id", req.Name, domain, req.AutoAddDomainUsers, userId).Scan(&org.Id)
-
- if err != nil {
- if IsNonUniqueErr(err) {
- // Handle the uniqueness constraint violation
- return nil, fmt.Errorf("an org with domain %s already exists", domain)
-
- }
-
- return nil, fmt.Errorf("error creating org: %v", err)
- }
-
- _, err = tx.Exec("INSERT INTO orgs_users (org_id, user_id) VALUES ($1, $2)", org.Id, userId)
-
- if err != nil {
- return nil, fmt.Errorf("error adding org membership: %v", err)
- }
-
- return org, nil
-}
-
-func GetOrgForDomain(domain string) (*Org, error) {
- var org Org
- err := Conn.Get(&org, "SELECT * FROM orgs WHERE domain = $1", domain)
-
- if err != nil {
- if err == sql.ErrNoRows {
- return nil, nil
- }
-
- return nil, fmt.Errorf("error getting org for domain: %v", err)
- }
-
- return &org, nil
-}
-
-func AddOrgDomainUsers(orgId, domain string, tx *sql.Tx) error {
- usersForDomain, err := GetUsersForDomain(domain)
-
- if err != nil {
- return fmt.Errorf("error getting users for domain: %v", err)
- }
-
- if len(usersForDomain) > 0 {
-
- // create org users for each user
- var valueStrings []string
- var valueArgs []interface{}
- for i, user := range usersForDomain {
- valueStrings = append(valueStrings, fmt.Sprintf("($%d, $%d)", i*2+1, i*2+2))
- valueArgs = append(valueArgs, orgId, user.Id)
- }
-
- // Join all value strings and execute a single query
- stmt := fmt.Sprintf("INSERT INTO orgs_users (org_id, user_id) VALUES %s", strings.Join(valueStrings, ","))
- _, err = tx.Exec(stmt, valueArgs...)
-
- if err != nil {
- return fmt.Errorf("error adding org users: %v", err)
- }
- }
-
- return nil
-}
-
-func DeleteOrgUser(orgId, userId string, tx *sql.Tx) error {
- _, err := tx.Exec("DELETE FROM orgs_users WHERE org_id = $1 AND user_id = $2", orgId, userId)
-
- if err != nil {
- return fmt.Errorf("error deleting org member: %v", err)
- }
-
- return nil
-}
-
-func CreateOrgUser(orgId, userId, orgRoleId string, tx *sql.Tx) error {
- query := "INSERT INTO orgs_users (org_id, user_id, org_role_id) VALUES ($1, $2, $3)"
- var err error
- if tx == nil {
- _, err = Conn.Exec(query, orgId, userId, orgRoleId)
- } else {
- _, err = tx.Exec(query, orgId, userId, orgRoleId)
- }
-
- if err != nil {
- return fmt.Errorf("error adding org member: %v", err)
- }
-
- return nil
-}
-
-func ListOrgRoles(orgId string) ([]*OrgRole, error) {
- var orgRoles []*OrgRole
- err := Conn.Select(&orgRoles, "SELECT * FROM org_roles WHERE org_id IS NULL OR org_id = $1", orgId)
-
- if err != nil {
- return nil, fmt.Errorf("error listing org roles: %v", err)
- }
-
- return orgRoles, nil
-}
diff --git a/server/db/plan_helpers.go b/server/db/plan_helpers.go
deleted file mode 100644
index a4531e88..00000000
--- a/server/db/plan_helpers.go
+++ /dev/null
@@ -1,339 +0,0 @@
-package db
-
-import (
- "encoding/json"
- "fmt"
- "log"
- "os"
- "path/filepath"
- "time"
-
- "github.com/google/uuid"
- "github.com/plandex/plandex/shared"
-)
-
-func CreatePlan(orgId, projectId, userId, name string) (*Plan, error) {
- query := "INSERT INTO plans (org_id, owner_id, project_id, name, status) VALUES (:org_id, :owner_id, :project_id, :name, :status) RETURNING id, created_at, updated_at"
-
- plan := &Plan{
- OrgId: orgId,
- OwnerId: userId,
- ProjectId: projectId,
- Name: name,
- Status: shared.PlanStatusDraft,
- }
-
- row, err := Conn.NamedQuery(query, plan)
-
- if err != nil {
- return nil, fmt.Errorf("error creating plan: %v", err)
- }
-
- defer row.Close()
-
- if row.Next() {
- var createdAt, updatedAt time.Time
- var id string
- if err := row.Scan(&id, &createdAt, &updatedAt); err != nil {
- return nil, fmt.Errorf("error creating plan: %v", err)
- }
-
- plan.Id = id
- plan.CreatedAt = createdAt
- plan.UpdatedAt = updatedAt
- }
-
- err = InitPlan(orgId, plan.Id)
-
- if err != nil {
- return nil, fmt.Errorf("error initializing plan dir: %v", err)
- }
-
- return plan, nil
-}
-
-func ListOwnedPlans(projectId, userId string, archived bool, status string) ([]shared.Plan, error) {
- qs := "SELECT id, owner_id, name, status, context_tokens, convo_tokens, shared_with_org_at, archived_at, created_at, updated_at FROM plans WHERE project_id = $1 AND owner_id = $2"
- qargs := []interface{}{projectId, userId}
-
- if archived {
- qs += " AND archived_at IS NOT NULL"
- } else {
- qs += " AND archived_at IS NULL"
- }
-
- if status != "" {
- qs += " AND status = $3"
- qargs = append(qargs, status)
- }
-
- qs += " ORDER BY updated_at DESC"
- res, err := Conn.Query(qs, qargs...)
-
- if err != nil {
- return nil, fmt.Errorf("error listing plans: %v", err)
- }
-
- defer res.Close()
- var plans []shared.Plan
- for res.Next() {
- var plan shared.Plan
-
- err := res.Scan(&plan.Id, &plan.OwnerId, &plan.Name, &plan.Status, &plan.ContextTokens, &plan.ConvoTokens, &plan.SharedWithOrgAt, &plan.ArchivedAt, &plan.CreatedAt, &plan.UpdatedAt)
-
- if err != nil {
- return nil, fmt.Errorf("error scanning plan: %v", err)
- }
- plans = append(plans, plan)
- }
-
- return plans, nil
-}
-
-func AddPlanContextTokens(planId string, addTokens int) error {
- _, err := Conn.Exec("UPDATE plans SET context_tokens = context_tokens + $1 WHERE id = $2", addTokens, planId)
- if err != nil {
- return fmt.Errorf("error updating plan tokens: %v", err)
- }
- return nil
-}
-
-func AddPlanConvoMessage(planId string, addTokens int) error {
- _, err := Conn.Exec("UPDATE plans SET convo_tokens = convo_tokens + $1, total_messages = total_messages + 1 WHERE id = $2", addTokens, planId)
- if err != nil {
- return fmt.Errorf("error updating plan tokens: %v", err)
- }
- return nil
-}
-
-func SyncPlanTokens(orgId, planId string) error {
- var contexts []*Context
- var convos []*ConvoMessage
- errCh := make(chan error)
-
- go func() {
- var err error
- contexts, err = GetPlanContexts(orgId, planId, false)
- errCh <- err
- }()
-
- go func() {
- var err error
- convos, err = GetPlanConvo(orgId, planId)
- errCh <- err
- }()
-
- for i := 0; i < 2; i++ {
- err := <-errCh
- if err != nil {
- return fmt.Errorf("error getting contexts or convo: %v", err)
- }
- }
-
- contextTokens := 0
- for _, context := range contexts {
- contextTokens += context.NumTokens
- }
-
- convoTokens := 0
- for _, msg := range convos {
- convoTokens += msg.Tokens
- }
-
- _, err := Conn.Exec("UPDATE plans SET context_tokens = $1, convo_tokens = $2 WHERE id = $3", contextTokens, convoTokens, planId)
-
- if err != nil {
- return fmt.Errorf("error updating plan tokens: %v", err)
- }
-
- return nil
-}
-
-func GetPlan(planId string) (*Plan, error) {
- var plan Plan
-
- err := Conn.Get(&plan, "SELECT id, org_id, owner_id, project_id, name, status, error, context_tokens, convo_tokens, shared_with_org_at, total_messages, archived_at, created_at, updated_at FROM plans WHERE id = $1", planId)
-
- if err != nil {
- return nil, fmt.Errorf("error getting plan: %v", err)
- }
-
- return &plan, nil
-}
-
-func SetPlanStatus(planId string, status shared.PlanStatus, errStr string) error {
- _, err := Conn.Exec("UPDATE plans SET status = $1, error = $2 WHERE id = $3", status, errStr, planId)
-
- if err != nil {
- return fmt.Errorf("error setting plan status: %v", err)
- }
-
- return nil
-}
-
-func RenamePlan(planId string, name string) error {
- _, err := Conn.Exec("UPDATE plans SET name = $1 WHERE id = $2", name, planId)
-
- if err != nil {
- return fmt.Errorf("error renaming plan: %v", err)
- }
-
- return nil
-}
-
-func IncNumNonDraftPlans(userId string) error {
- _, err := Conn.Exec("UPDATE users SET num_non_draft_plans = num_non_draft_plans + 1 WHERE id = $1", userId)
-
- if err != nil {
- return fmt.Errorf("error updating user num_non_draft_plans: %v", err)
- }
-
- return nil
-}
-
-func StoreDescription(description *ConvoMessageDescription) error {
- descriptionsDir := getPlanDescriptionsDir(description.OrgId, description.PlanId)
-
- now := time.Now()
-
- if description.Id == "" {
- description.Id = uuid.New().String()
- description.CreatedAt = now
- }
- description.UpdatedAt = now
-
- bytes, err := json.Marshal(description)
-
- if err != nil {
- return fmt.Errorf("error marshalling convo message description: %v", err)
- }
-
- err = os.WriteFile(filepath.Join(descriptionsDir, description.Id+".json"), bytes, os.ModePerm)
-
- if err != nil {
- return fmt.Errorf("error writing convo message description: %v", err)
- }
-
- return nil
-}
-
-func DeleteDraftPlans(orgId, projectId, userId string) error {
- res, err := Conn.Query("DELETE FROM plans WHERE project_id = $1 AND owner_id = $2 AND name = 'draft' RETURNING id;", projectId, userId)
- if err != nil {
- return fmt.Errorf("error deleting draft plans: %v", err)
- }
-
- defer res.Close()
-
- // get ids
- var ids []string
-
- for res.Next() {
- var id string
- err := res.Scan(&id)
- if err != nil {
- return fmt.Errorf("error scanning deleted draft plan id: %v", err)
- }
- ids = append(ids, id)
- }
-
- errCh := make(chan error)
- for _, planId := range ids {
- go func(planId string) {
- errCh <- DeletePlanDir(orgId, planId)
- }(planId)
- }
-
- for i := 0; i < len(ids); i++ {
- err := <-errCh
- if err != nil {
- return fmt.Errorf("error deleting draft plan dir: %v", err)
- }
- }
-
- if len(ids) > 0 {
- log.Println("Deleted", len(ids), "draft plans")
- }
-
- return nil
-}
-
-func DeleteOwnerPlans(orgId, projectId, userId string) error {
- res, err := Conn.Query("DELETE FROM plans WHERE project_id = $1 AND owner_id = $2 RETURNING id;", projectId, userId)
- if err != nil {
- return fmt.Errorf("error deleting plans: %v", err)
- }
-
- defer res.Close()
-
- // get ids
- var ids []string
-
- for res.Next() {
- var id string
- err := res.Scan(&id)
- if err != nil {
- return fmt.Errorf("error scanning deleted draft plan id: %v", err)
- }
- ids = append(ids, id)
- }
-
- errCh := make(chan error)
- for _, planId := range ids {
- go func(planId string) {
- errCh <- DeletePlanDir(orgId, planId)
- }(planId)
- }
-
- for i := 0; i < len(ids); i++ {
- err := <-errCh
- if err != nil {
- return fmt.Errorf("error deleting plan dir: %v", err)
- }
- }
-
- if len(ids) > 0 {
- log.Println("Deleted", len(ids), "plans")
- }
-
- return nil
-}
-
-func ValidatePlanAccess(planId, userId, orgId string) (*Plan, error) {
- // get plan
- plan, err := GetPlan(planId)
-
- if err != nil {
- return nil, fmt.Errorf("error getting plan: %v", err)
- }
-
- if plan == nil {
- return nil, nil
- }
-
- if plan.OrgId != orgId {
- return nil, nil
- }
-
- hasProjectAccess, err := ValidateProjectAccess(plan.ProjectId, userId, orgId)
-
- if err != nil {
- return nil, fmt.Errorf("error validating project membership: %v", err)
- }
-
- if !hasProjectAccess {
- return nil, nil
- }
-
- // owner has access
- if plan.OwnerId == userId {
- return plan, nil
- }
-
- // plan is shared with org
- if plan.SharedWithOrgAt != nil {
- return plan, nil
- }
-
- return nil, nil
-}
diff --git a/server/db/project_helpers.go b/server/db/project_helpers.go
deleted file mode 100644
index 552e2624..00000000
--- a/server/db/project_helpers.go
+++ /dev/null
@@ -1,16 +0,0 @@
-package db
-
-import "fmt"
-
-func ValidateProjectAccess(projectId, userId, orgId string) (bool, error) {
-
- var count int
- err := Conn.QueryRow("SELECT COUNT(*) FROM users_projects WHERE project_id = $1 AND user_id = $2 AND org_id = $3", projectId, userId, orgId).Scan(&count)
-
- if err != nil {
- return false, fmt.Errorf("error validating project membership: %v", err)
- }
-
- return count > 0, nil
-
-}
diff --git a/server/db/rbac_helpers.go b/server/db/rbac_helpers.go
deleted file mode 100644
index a180041d..00000000
--- a/server/db/rbac_helpers.go
+++ /dev/null
@@ -1,14 +0,0 @@
-package db
-
-import "fmt"
-
-func GetOrgOwnerRoleId() (string, error) {
- var roleId string
- err := Conn.Get(&roleId, "SELECT id FROM org_roles WHERE name = 'owner'")
-
- if err != nil {
- return "", fmt.Errorf("error getting owner role id: %v", err)
- }
-
- return roleId, nil
-}
diff --git a/server/db/result_helpers.go b/server/db/result_helpers.go
deleted file mode 100644
index fe564c2e..00000000
--- a/server/db/result_helpers.go
+++ /dev/null
@@ -1,536 +0,0 @@
-package db
-
-import (
- "encoding/json"
- "fmt"
- "os"
- "path/filepath"
- "sort"
- "strings"
- "time"
-
- "github.com/google/uuid"
- "github.com/plandex/plandex/shared"
-)
-
-func StorePlanResult(result *PlanFileResult) error {
- now := time.Now()
- if result.Id == "" {
- result.Id = uuid.New().String()
- result.CreatedAt = now
- }
- result.UpdatedAt = now
-
- bytes, err := json.MarshalIndent(result, "", " ")
-
- if err != nil {
- return fmt.Errorf("error marshalling result: %v", err)
- }
-
- resultsDir := getPlanResultsDir(result.OrgId, result.PlanId)
-
- err = os.MkdirAll(resultsDir, 0755)
-
- if err != nil {
- return fmt.Errorf("error creating results dir: %v", err)
- }
-
- err = os.WriteFile(filepath.Join(resultsDir, result.Id+".json"), bytes, 0644)
-
- if err != nil {
- return fmt.Errorf("error writing result file: %v", err)
- }
-
- return nil
-
-}
-
-type CurrentPlanStateParams struct {
- OrgId string
- PlanId string
- Contexts []*Context
- PlanFileResults []*PlanFileResult
- PendingBuildDescriptions []*ConvoMessageDescription
-}
-
-func GetCurrentPlanState(params CurrentPlanStateParams) (*shared.CurrentPlanState, error) {
- orgId := params.OrgId
- planId := params.PlanId
-
- var dbPlanFileResults []*PlanFileResult
- var pendingBuildDescriptions []*shared.ConvoMessageDescription
- var contexts []*Context
-
- errCh := make(chan error)
-
- go func() {
- if params.PlanFileResults == nil {
- res, err := GetPlanFileResults(orgId, planId)
- dbPlanFileResults = res
-
- if err != nil {
- errCh <- fmt.Errorf("error getting plan file results: %v", err)
- return
- }
- } else {
- dbPlanFileResults = params.PlanFileResults
- }
-
- errCh <- nil
- }()
-
- go func() {
- if params.PendingBuildDescriptions == nil {
- res, err := GetPendingBuildDescriptions(orgId, planId)
- if err != nil {
- errCh <- fmt.Errorf("error getting latest plan build description: %v", err)
- return
- }
-
- for _, desc := range res {
- pendingBuildDescriptions = append(pendingBuildDescriptions, desc.ToApi())
- }
- } else {
- for _, desc := range params.PendingBuildDescriptions {
- pendingBuildDescriptions = append(pendingBuildDescriptions, desc.ToApi())
- }
- }
-
- errCh <- nil
- }()
-
- go func() {
- if params.Contexts == nil {
- res, err := GetPlanContexts(orgId, planId, true)
- if err != nil {
- errCh <- fmt.Errorf("error getting plan contexts: %v", err)
- return
- }
- contexts = res
- } else {
- contexts = params.Contexts
- }
-
- errCh <- nil
- }()
-
- for i := 0; i < 3; i++ {
- err := <-errCh
- if err != nil {
- return nil, err
- }
- }
-
- var apiPlanFileResults []*shared.PlanFileResult
-
- for _, dbPlanFileResult := range dbPlanFileResults {
- apiPlanFileResults = append(apiPlanFileResults, dbPlanFileResult.ToApi())
- }
- planResult := GetPlanResult(apiPlanFileResults)
-
- var apiContexts []*shared.Context
- apiContextsByPath := make(map[string]*shared.Context)
-
- for _, context := range contexts {
- apiContexts = append(apiContexts, context.ToApi())
-
- if context.FilePath != "" {
- apiContextsByPath[context.FilePath] = context.ToApi()
- }
- }
-
- planState := &shared.CurrentPlanState{
- PlanResult: planResult,
- Contexts: apiContexts,
- ContextsByPath: apiContextsByPath,
- PendingBuildDescriptions: pendingBuildDescriptions,
- }
-
- currentPlanFiles, err := planState.GetFiles()
-
- if err != nil {
- return nil, fmt.Errorf("error getting current plan files: %v", err)
- }
-
- planState.CurrentPlanFiles = currentPlanFiles
-
- return planState, nil
-}
-
-func GetPendingBuildDescriptions(orgId, planId string) ([]*ConvoMessageDescription, error) {
- descriptionsDir := getPlanDescriptionsDir(orgId, planId)
-
- files, err := os.ReadDir(descriptionsDir)
-
- if err != nil {
- return nil, fmt.Errorf("error reading descriptions dir: %v", err)
- }
-
- var descriptions []*ConvoMessageDescription
- errCh := make(chan error, len(files))
- descCh := make(chan *ConvoMessageDescription, len(files))
-
- for _, file := range files {
- go func(file os.DirEntry) {
- bytes, err := os.ReadFile(filepath.Join(descriptionsDir, file.Name()))
-
- if err != nil {
- errCh <- fmt.Errorf("error reading description file: %v", err)
- return
- }
-
- var description ConvoMessageDescription
- err = json.Unmarshal(bytes, &description)
-
- if err != nil {
- errCh <- fmt.Errorf("error unmarshalling description file: %v", err)
- return
- }
-
- descCh <- &description
- }(file)
- }
-
- for i := 0; i < len(files); i++ {
- select {
- case err := <-errCh:
- return nil, fmt.Errorf("error reading description files: %v", err)
- case description := <-descCh:
- if description.MadePlan && description.AppliedAt == nil {
- descriptions = append(descriptions, description)
- }
- }
- }
-
- sort.Slice(descriptions, func(i, j int) bool {
- return descriptions[i].CreatedAt.Before(descriptions[j].CreatedAt)
- })
-
- return descriptions, nil
-}
-
-func GetPlanFileResults(orgId, planId string) ([]*PlanFileResult, error) {
- var results []*PlanFileResult
-
- resultsDir := getPlanResultsDir(orgId, planId)
-
- files, err := os.ReadDir(resultsDir)
-
- if err != nil {
- return nil, fmt.Errorf("error reading results dir: %v", err)
- }
-
- errCh := make(chan error, len(files))
- resultCh := make(chan *PlanFileResult, len(files))
-
- for _, file := range files {
- go func(file os.DirEntry) {
-
- bytes, err := os.ReadFile(filepath.Join(resultsDir, file.Name()))
-
- if err != nil {
- errCh <- fmt.Errorf("error reading result file: %v", err)
- return
- }
-
- var result PlanFileResult
- err = json.Unmarshal(bytes, &result)
-
- if err != nil {
- errCh <- fmt.Errorf("error unmarshalling result file: %v", err)
- return
- }
-
- resultCh <- &result
- }(file)
- }
-
- for i := 0; i < len(files); i++ {
- select {
- case err := <-errCh:
- return nil, fmt.Errorf("error reading result files: %v", err)
- case result := <-resultCh:
- results = append(results, result)
- }
- }
-
- sort.Slice(results, func(i, j int) bool {
- return results[i].CreatedAt.Before(results[j].CreatedAt)
- })
-
- return results, nil
-}
-
-func GetPlanResult(planFileResults []*shared.PlanFileResult) *shared.PlanResult {
- resByPath := make(shared.PlanFileResultsByPath)
- replacementsByPath := make(map[string][]*shared.Replacement)
- var paths []string
-
- for _, planFileRes := range planFileResults {
- if planFileRes.IsPending() {
- _, hasPath := resByPath[planFileRes.Path]
-
- resByPath[planFileRes.Path] = append(resByPath[planFileRes.Path], planFileRes)
-
- if !hasPath {
- paths = append(paths, planFileRes.Path)
- }
- }
- }
-
- for _, results := range resByPath {
- for _, planRes := range results {
- replacementsByPath[planRes.Path] = append(replacementsByPath[planRes.Path], planRes.Replacements...)
- }
- }
-
- // sort paths ascending
- sort.Slice(paths, func(i, j int) bool {
- return paths[i] < paths[j]
- })
-
- return &shared.PlanResult{
- FileResultsByPath: resByPath,
- SortedPaths: paths,
- ReplacementsByPath: replacementsByPath,
- Results: planFileResults,
- }
-}
-
-func ApplyPlan(orgId, planId string) error {
- resultsDir := getPlanResultsDir(orgId, planId)
-
- errCh := make(chan error)
-
- var results []*PlanFileResult
- var pendingBuildDescriptions []*ConvoMessageDescription
- var contexts []*Context
-
- go func() {
- res, err := GetPlanFileResults(orgId, planId)
- if err != nil {
- errCh <- fmt.Errorf("error getting plan file results: %v", err)
- return
- }
- results = res
- errCh <- nil
- }()
-
- go func() {
- res, err := GetPendingBuildDescriptions(orgId, planId)
- if err != nil {
- errCh <- fmt.Errorf("error getting latest plan build description: %v", err)
- return
- }
- pendingBuildDescriptions = res
- errCh <- nil
- }()
-
- go func() {
- res, err := GetPlanContexts(orgId, planId, false)
- if err != nil {
- errCh <- fmt.Errorf("error getting plan contexts: %v", err)
- return
- }
- contexts = res
- errCh <- nil
- }()
-
- for i := 0; i < 3; i++ {
- err := <-errCh
- if err != nil {
- return fmt.Errorf("error applying plan: %v", err)
- }
- }
-
- planState, err := GetCurrentPlanState(CurrentPlanStateParams{
- OrgId: orgId,
- PlanId: planId,
- Contexts: contexts,
- PlanFileResults: results,
- PendingBuildDescriptions: pendingBuildDescriptions,
- })
-
- if err != nil {
- return fmt.Errorf("error getting current plan state: %v", err)
- }
-
- var pendingDbResults []*PlanFileResult
-
- for _, result := range results {
- apiResult := result.ToApi()
- if apiResult.IsPending() {
- pendingDbResults = append(pendingDbResults, result)
- }
- }
-
- errCh = make(chan error, len(pendingDbResults)+len(pendingBuildDescriptions))
- now := time.Now()
-
- for _, result := range pendingDbResults {
- go func(result *PlanFileResult) {
- result.AppliedAt = &now
-
- bytes, err := json.MarshalIndent(result, "", " ")
-
- if err != nil {
- errCh <- fmt.Errorf("error marshalling result: %v", err)
- return
- }
-
- err = os.WriteFile(filepath.Join(resultsDir, result.Id+".json"), bytes, 0644)
-
- if err != nil {
- errCh <- fmt.Errorf("error writing result file: %v", err)
- return
- }
-
- errCh <- nil
-
- }(result)
- }
-
- for _, description := range pendingBuildDescriptions {
- go func(description *ConvoMessageDescription) {
- description.AppliedAt = &now
-
- err := StoreDescription(description)
-
- if err != nil {
- errCh <- fmt.Errorf("error storing convo message description: %v", err)
- return
- }
-
- errCh <- nil
- }(description)
- }
-
- for i := 0; i < len(pendingDbResults)+len(pendingBuildDescriptions); i++ {
- err := <-errCh
- if err != nil {
- return fmt.Errorf("error applying plan: %v", err)
- }
- }
-
- msg := "Marked pending results as applied." + "\n\n" + planState.PendingChangesSummary()
-
- err = GitAddAndCommit(orgId, planId, msg)
-
- if err != nil {
- return fmt.Errorf("error committing plan: %v", err)
- }
-
- return nil
-}
-
-func RejectAllResults(orgId, planId string) error {
- resultsDir := getPlanResultsDir(orgId, planId)
-
- files, err := os.ReadDir(resultsDir)
-
- if err != nil {
- return fmt.Errorf("error reading results dir: %v", err)
- }
-
- errCh := make(chan error, len(files))
- now := time.Now()
-
- for _, file := range files {
- resultId := strings.TrimSuffix(file.Name(), ".json")
-
- go func(resultId string) {
- err := RejectPlanFileResult(orgId, planId, resultId, now)
-
- if err != nil {
- errCh <- fmt.Errorf("error rejecting result: %v", err)
- return
- }
-
- errCh <- nil
- }(resultId)
- }
-
- for i := 0; i < len(files); i++ {
- err := <-errCh
- if err != nil {
- return fmt.Errorf("error rejecting plan: %v", err)
- }
- }
-
- return nil
-}
-
-func RejectPlanFileResult(orgId, planId, resultId string, now time.Time) error {
- resultsDir := getPlanResultsDir(orgId, planId)
-
- bytes, err := os.ReadFile(filepath.Join(resultsDir, resultId+".json"))
-
- if err != nil {
- return fmt.Errorf("error reading result file: %v", err)
- }
-
- var result PlanFileResult
- err = json.Unmarshal(bytes, &result)
-
- if err != nil {
- return fmt.Errorf("error unmarshalling result file: %v", err)
- }
-
- if result.RejectedAt != nil {
- return nil
- }
-
- result.RejectedAt = &now
-
- bytes, err = json.MarshalIndent(result, "", " ")
-
- if err != nil {
- return fmt.Errorf("error marshalling result: %v", err)
- }
-
- err = os.WriteFile(filepath.Join(resultsDir, resultId+".json"), bytes, 0644)
-
- if err != nil {
- return fmt.Errorf("error writing result file: %v", err)
- }
-
- return nil
-}
-
-func RejectReplacement(orgId, planId, resultId, replacementId string) error {
- resultsDir := getPlanResultsDir(orgId, planId)
-
- bytes, err := os.ReadFile(filepath.Join(resultsDir, resultId+".json"))
-
- if err != nil {
- return fmt.Errorf("error reading result file: %v", err)
- }
-
- var result PlanFileResult
- err = json.Unmarshal(bytes, &result)
-
- if err != nil {
- return fmt.Errorf("error unmarshalling result file: %v", err)
- }
-
- if result.RejectedAt != nil {
- return nil
- }
-
- now := time.Now()
-
- foundReplacement := false
- for _, replacement := range result.Replacements {
- if replacement.Id == replacementId {
- replacement.RejectedAt = &now
- foundReplacement = true
- break
- }
- }
-
- if !foundReplacement {
- return fmt.Errorf("replacement not found: %s", replacementId)
- }
-
- return nil
-}
diff --git a/server/db/user_helpers.go b/server/db/user_helpers.go
deleted file mode 100644
index faa3995d..00000000
--- a/server/db/user_helpers.go
+++ /dev/null
@@ -1,62 +0,0 @@
-package db
-
-import (
- "database/sql"
- "fmt"
-)
-
-func GetUser(userId string) (*User, error) {
- var user User
- err := Conn.Get(&user, "SELECT * FROM users WHERE id = $1", userId)
-
- if err != nil {
- return nil, fmt.Errorf("error getting user: %v", err)
- }
-
- return &user, nil
-}
-
-func GetUserByEmail(email string) (*User, error) {
- var user User
- err := Conn.Get(&user, "SELECT * FROM users WHERE email = $1", email)
-
- if err != nil {
- if err == sql.ErrNoRows {
- return nil, nil
- }
-
- return nil, fmt.Errorf("error getting user: %v", err)
- }
-
- return &user, nil
-}
-
-func GetUsersForDomain(domain string) ([]*User, error) {
- var users []*User
- err := Conn.Select(&users, "SELECT * FROM users WHERE domain = $1", domain)
-
- if err != nil {
- if err == sql.ErrNoRows {
- return nil, nil
- }
-
- return nil, fmt.Errorf("error getting users for domain: %v", err)
- }
-
- return users, nil
-}
-
-func ListUsers(orgId string) ([]*User, error) {
- var users []*User
- err := Conn.Select(&users, "SELECT u.* FROM users u INNER JOIN orgs_users ou ON u.id = ou.user_id WHERE ou.org_id = $1", orgId)
-
- if err != nil {
- return nil, fmt.Errorf("error listing users: %v", err)
- }
-
- return users, nil
-}
-
-func CreateUser(user *User, tx *sql.Tx) error {
- return tx.QueryRow("INSERT INTO users (name, email, domain, is_trial) VALUES ($1, $2, $3, $4) RETURNING id", user.Name, user.Email, user.Domain, user.IsTrial).Scan(&user.Id)
-}
diff --git a/server/db/utils.go b/server/db/utils.go
deleted file mode 100644
index 39d8e543..00000000
--- a/server/db/utils.go
+++ /dev/null
@@ -1,12 +0,0 @@
-package db
-
-import "github.com/lib/pq"
-
-func IsNonUniqueErr(err error) bool {
- if err, ok := err.(*pq.Error); ok {
- if err.Code == "23505" {
- return true
- }
- }
- return false
-}
diff --git a/server/email/email.go b/server/email/email.go
deleted file mode 100644
index 02e4227e..00000000
--- a/server/email/email.go
+++ /dev/null
@@ -1,34 +0,0 @@
-package email
-
-import (
- "fmt"
- "os"
-
- "github.com/atotto/clipboard"
- "github.com/gen2brain/beeep"
-)
-
-func SendVerificationEmail(email string, pin string) error {
- // Check if the environment is production
- if os.Getenv("GOENV") == "production" {
- // TODO: send email in production
- return nil
- }
-
- if os.Getenv("GOENV") == "development" {
- // Development environment
- // Copy pin to clipboard
- if err := clipboard.WriteAll(pin); err != nil {
- return fmt.Errorf("error copying pin to clipboard in dev: %v", err)
- }
-
- // Send notification
- err := beeep.Notify("Verification Pin", fmt.Sprintf("Verification pin %s copied to clipboard %s", pin, email), "")
- if err != nil {
- return fmt.Errorf("error sending notification in dev: %v", err)
- }
-
- }
-
- return nil
-}
diff --git a/server/go.mod b/server/go.mod
deleted file mode 100644
index 6a29c27d..00000000
--- a/server/go.mod
+++ /dev/null
@@ -1,41 +0,0 @@
-module plandex-server
-
-go 1.21.3
-
-require (
- github.com/davecgh/go-spew v1.1.1
- github.com/google/uuid v1.4.0
- github.com/gorilla/mux v1.8.1
- github.com/pkg/errors v0.9.1
- github.com/plandex/plandex/shared v0.0.0-00010101000000-000000000000
- github.com/sashabaranov/go-openai v1.17.5
-)
-
-require (
- github.com/dlclark/regexp2 v1.10.0 // indirect
- github.com/go-toast/toast v0.0.0-20190211030409-01e6764cf0a4 // indirect
- github.com/godbus/dbus/v5 v5.1.0 // indirect
- github.com/hashicorp/errwrap v1.1.0 // indirect
- github.com/hashicorp/go-multierror v1.1.1 // indirect
- github.com/mattn/go-colorable v0.1.13 // indirect
- github.com/mattn/go-isatty v0.0.20 // indirect
- github.com/mattn/go-runewidth v0.0.9 // indirect
- github.com/nu7hatch/gouuid v0.0.0-20131221200532-179d4d0c4d8d // indirect
- github.com/olekukonko/tablewriter v0.0.5 // indirect
- github.com/pkoukk/tiktoken-go v0.1.6 // indirect
- github.com/tadvi/systray v0.0.0-20190226123456-11a2b8fa57af // indirect
- go.uber.org/atomic v1.7.0 // indirect
- golang.org/x/sys v0.14.0 // indirect
-)
-
-require (
- github.com/atotto/clipboard v0.1.4
- github.com/fatih/color v1.16.0
- github.com/gen2brain/beeep v0.0.0-20230907135156-1a38885a97fc
- github.com/golang-migrate/migrate/v4 v4.16.2
- github.com/jmoiron/sqlx v1.3.5
- github.com/lib/pq v1.10.9
- github.com/looplab/fsm v1.0.1 // indirect
-)
-
-replace github.com/plandex/plandex/shared => ../shared
diff --git a/server/go.sum b/server/go.sum
deleted file mode 100644
index 62fc0f88..00000000
--- a/server/go.sum
+++ /dev/null
@@ -1,103 +0,0 @@
-github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161 h1:L/gRVlceqvL25UVaW/CKtUDjefjrs0SPonmDGUVOYP0=
-github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E=
-github.com/Microsoft/go-winio v0.6.1 h1:9/kr64B9VUZrLm5YYwbGtUJnMgqWVOdUAXu6Migciow=
-github.com/Microsoft/go-winio v0.6.1/go.mod h1:LRdKpFKfdobln8UmuiYcKPot9D2v6svN5+sAH+4kjUM=
-github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4=
-github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI=
-github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
-github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
-github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
-github.com/dhui/dktest v0.3.16 h1:i6gq2YQEtcrjKbeJpBkWjE8MmLZPYllcjOFbTZuPDnw=
-github.com/dhui/dktest v0.3.16/go.mod h1:gYaA3LRmM8Z4vJl2MA0THIigJoZrwOansEOsp+kqxp0=
-github.com/dlclark/regexp2 v1.10.0 h1:+/GIL799phkJqYW+3YbOd8LCcbHzT0Pbo8zl70MHsq0=
-github.com/dlclark/regexp2 v1.10.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
-github.com/docker/distribution v2.8.2+incompatible h1:T3de5rq0dB1j30rp0sA2rER+m322EBzniBPB6ZIzuh8=
-github.com/docker/distribution v2.8.2+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w=
-github.com/docker/docker v20.10.24+incompatible h1:Ugvxm7a8+Gz6vqQYQQ2W7GYq5EUPaAiuPgIfVyI3dYE=
-github.com/docker/docker v20.10.24+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk=
-github.com/docker/go-connections v0.4.0 h1:El9xVISelRB7BuFusrZozjnkIM5YnzCViNKohAFqRJQ=
-github.com/docker/go-connections v0.4.0/go.mod h1:Gbd7IOopHjR8Iph03tsViu4nIes5XhDvyHbTtUxmeec=
-github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4=
-github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk=
-github.com/fatih/color v1.16.0 h1:zmkK9Ngbjj+K0yRhTVONQh1p/HknKYSlNT+vZCzyokM=
-github.com/fatih/color v1.16.0/go.mod h1:fL2Sau1YI5c0pdGEVCbKQbLXB6edEj1ZgiY4NijnWvE=
-github.com/gen2brain/beeep v0.0.0-20230907135156-1a38885a97fc h1:NNgdMgPX3j33uEAoVVxNxillDPnxT0xbGv8uh4CKIAo=
-github.com/gen2brain/beeep v0.0.0-20230907135156-1a38885a97fc/go.mod h1:0W7dI87PvXJ1Sjs0QPvWXKcQmNERY77e8l7GFhZB/s4=
-github.com/go-sql-driver/mysql v1.6.0 h1:BCTh4TKNUYmOmMUcQ3IipzF5prigylS7XXjEkfCHuOE=
-github.com/go-sql-driver/mysql v1.6.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg=
-github.com/go-toast/toast v0.0.0-20190211030409-01e6764cf0a4 h1:qZNfIGkIANxGv/OqtnntR4DfOY2+BgwR60cAcu/i3SE=
-github.com/go-toast/toast v0.0.0-20190211030409-01e6764cf0a4/go.mod h1:kW3HQ4UdaAyrUCSSDR4xUzBKW6O2iA4uHhk7AtyYp10=
-github.com/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk=
-github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
-github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=
-github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
-github.com/golang-migrate/migrate/v4 v4.16.2 h1:8coYbMKUyInrFk1lfGfRovTLAW7PhWp8qQDT2iKfuoA=
-github.com/golang-migrate/migrate/v4 v4.16.2/go.mod h1:pfcJX4nPHaVdc5nmdCikFBWtm+UBpiZjRNNsyBbp0/o=
-github.com/google/uuid v1.4.0 h1:MtMxsa51/r9yyhkyLsVeVt0B+BGQZzpQiTQ4eHZ8bc4=
-github.com/google/uuid v1.4.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
-github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY=
-github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ=
-github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
-github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I=
-github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
-github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo=
-github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM=
-github.com/jmoiron/sqlx v1.3.5 h1:vFFPA71p1o5gAeqtEAwLU4dnX2napprKtHr7PYIcN3g=
-github.com/jmoiron/sqlx v1.3.5/go.mod h1:nRVWtLre0KfCLJvgxzCsLVMogSvQ1zNJtpYr2Ccp0mQ=
-github.com/lib/pq v1.2.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo=
-github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
-github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
-github.com/looplab/fsm v1.0.1 h1:OEW0ORrIx095N/6lgoGkFkotqH6s7vaFPsgjLAaF5QU=
-github.com/looplab/fsm v1.0.1/go.mod h1:PmD3fFvQEIsjMEfvZdrCDZ6y8VwKTwWNjlpEr6IKPO4=
-github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
-github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
-github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
-github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
-github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
-github.com/mattn/go-runewidth v0.0.9 h1:Lm995f3rfxdpd6TSmuVCHVb/QhupuXlYr8sCI/QdE+0=
-github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
-github.com/mattn/go-sqlite3 v1.14.6/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU=
-github.com/mattn/go-sqlite3 v1.14.16 h1:yOQRA0RpS5PFz/oikGwBEqvAWhWg5ufRz4ETLjwpU1Y=
-github.com/mattn/go-sqlite3 v1.14.16/go.mod h1:2eHXhiwb8IkHr+BDWZGa96P6+rkvnG63S2DGjv9HUNg=
-github.com/moby/term v0.5.0 h1:xt8Q1nalod/v7BqbG21f8mQPqH+xAaC9C3N3wfWbVP0=
-github.com/moby/term v0.5.0/go.mod h1:8FzsFHVUBGZdbDsJw/ot+X+d5HLUbvklYLJ9uGfcI3Y=
-github.com/morikuni/aec v1.0.0 h1:nP9CBfwrvYnBRgY6qfDQkygYDmYwOilePFkwzv4dU8A=
-github.com/morikuni/aec v1.0.0/go.mod h1:BbKIizmSmc5MMPqRYbxO4ZU0S0+P200+tUnFx7PXmsc=
-github.com/nu7hatch/gouuid v0.0.0-20131221200532-179d4d0c4d8d h1:VhgPp6v9qf9Agr/56bj7Y/xa04UccTW04VP0Qed4vnQ=
-github.com/nu7hatch/gouuid v0.0.0-20131221200532-179d4d0c4d8d/go.mod h1:YUTz3bUH2ZwIWBy3CJBeOBEugqcmXREj14T+iG/4k4U=
-github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec=
-github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY=
-github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U=
-github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM=
-github.com/opencontainers/image-spec v1.0.2 h1:9yCKha/T5XdGtO0q9Q9a6T5NUCsTn/DrBg0D7ufOcFM=
-github.com/opencontainers/image-spec v1.0.2/go.mod h1:BtxoFyWECRxE4U/7sNtV5W15zMzWCbyJoFRP3s7yZA0=
-github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
-github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
-github.com/pkoukk/tiktoken-go v0.1.6 h1:JF0TlJzhTbrI30wCvFuiw6FzP2+/bR+FIxUdgEAcUsw=
-github.com/pkoukk/tiktoken-go v0.1.6/go.mod h1:9NiV+i9mJKGj1rYOT+njbv+ZwA/zJxYdewGl6qVatpg=
-github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
-github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
-github.com/sashabaranov/go-openai v1.17.5 h1:ItBzlrrfTtkFWOFlgfOhk3y/xRBC4PJol4gdbiK7hgg=
-github.com/sashabaranov/go-openai v1.17.5/go.mod h1:lj5b/K+zjTSFxVLijLSTDZuP7adOgerWeFyZLUhAKRg=
-github.com/sirupsen/logrus v1.9.2 h1:oxx1eChJGI6Uks2ZC4W1zpLlVgqB8ner4EuQwV4Ik1Y=
-github.com/sirupsen/logrus v1.9.2/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
-github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
-github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
-github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8=
-github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
-github.com/tadvi/systray v0.0.0-20190226123456-11a2b8fa57af h1:6yITBqGTE2lEeTPG04SN9W+iWHCRyHqlVYILiSXziwk=
-github.com/tadvi/systray v0.0.0-20190226123456-11a2b8fa57af/go.mod h1:4F09kP5F+am0jAwlQLddpoMDM+iewkxxt6nxUQ5nq5o=
-go.uber.org/atomic v1.7.0 h1:ADUqmZGgLDDfbSL9ZmPxKTybcoEYHgpYfELNoN+7hsw=
-go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
-golang.org/x/mod v0.10.0 h1:lFO9qtOdlre5W1jxS3r/4szv2/6iXxScdzjoBMXNhYk=
-golang.org/x/mod v0.10.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
-golang.org/x/net v0.10.0 h1:X2//UzNDwYmtCLn7To6G58Wr6f5ahEAQgKNzv9Y951M=
-golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
-golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
-golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
-golang.org/x/sys v0.14.0 h1:Vz7Qs629MkJkGyHxUlRHizWJRG2j8fbQKjELVSNhy7Q=
-golang.org/x/sys v0.14.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
-golang.org/x/tools v0.9.1 h1:8WMNJAz3zrtPmnYC7ISf5dEn3MT0gY7jBJfw27yrrLo=
-golang.org/x/tools v0.9.1/go.mod h1:owI94Op576fPu3cIGQeHs3joujW/2Oc6MtlxbF5dfNc=
-gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
-gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
diff --git a/server/handlers/accounts.go b/server/handlers/accounts.go
deleted file mode 100644
index fcd90d6b..00000000
--- a/server/handlers/accounts.go
+++ /dev/null
@@ -1,407 +0,0 @@
-package handlers
-
-import (
- "encoding/json"
- "fmt"
- "io"
- "log"
- "net/http"
- "plandex-server/db"
- "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")
-
- // read the request body
- body, err := io.ReadAll(r.Body)
- if err != nil {
- log.Printf("Error reading request body: %v\n", err)
- http.Error(w, "Error reading request body: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- var req shared.CreateAccountRequest
- err = json.Unmarshal(body, &req)
- if err != nil {
- log.Printf("Error unmarshalling request: %v\n", err)
- http.Error(w, "Error unmarshalling request: "+err.Error(), http.StatusInternalServerError)
- return
- }
- req.Email = strings.ToLower(req.Email)
-
- 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
- }
-
- // 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")
- }
- }
- }()
-
- // create user
- 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
- }
- domain := emailSplit[1]
-
- user := db.User{
- Name: req.UserName,
- Email: req.Email,
- Domain: domain,
- }
- err = db.CreateUser(&user, tx)
-
- 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 creating user: %v\n", err)
- http.Error(w, "Error creating user: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- userId := user.Id
-
- // create auth token
- token, authTokenId, err := db.CreateAuthToken(userId, 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", userId, 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
- }
-
- // add to org matching domain if one exists and auto add domain users is true for that org
- org, err := db.GetOrgForDomain(domain)
-
- if err != nil {
- log.Printf("Error getting org for domain: %v\n", err)
- http.Error(w, "Error getting org for domain: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- if org != nil && org.AutoAddDomainUsers {
- // 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
- }
-
- err = db.CreateOrgUser(org.Id, userId, orgOwnerRoleId, tx)
-
- if err != nil {
- log.Printf("Error adding org user: %v\n", err)
- http.Error(w, "Error adding org user: "+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
- }
-
- // 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")
- }
- }
- }()
-
- _, err = tx.Exec("UPDATE users SET name = $1, email = $2, domain = $3, is_trial = false WHERE id = $4", req.UserName, req.Email, userDomain, auth.AuthToken.UserId)
-
- 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
- }
-
- // 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.AuthToken.UserId, auth.AuthToken.Id, 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
- }
-
- // 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
- }
-
- log.Println("Successfully converted trial")
-}
diff --git a/server/handlers/auth_helpers.go b/server/handlers/auth_helpers.go
deleted file mode 100644
index 8b818dd6..00000000
--- a/server/handlers/auth_helpers.go
+++ /dev/null
@@ -1,278 +0,0 @@
-package handlers
-
-import (
- "encoding/base64"
- "encoding/json"
- "log"
- "net/http"
- "plandex-server/db"
- "plandex-server/types"
- "strings"
-
- "github.com/plandex/plandex/shared"
-)
-
-func authenticate(w http.ResponseWriter, r *http.Request, requireOrg bool) *types.ServerAuth {
- log.Println("authenticating request")
-
- authHeader := r.Header.Get("Authorization")
-
- if authHeader == "" {
- log.Println("no auth header")
- http.Error(w, "no auth header", http.StatusUnauthorized)
- return nil
- }
-
- if !strings.HasPrefix(authHeader, "Bearer ") {
- log.Println("invalid auth header")
- http.Error(w, "invalid auth header", http.StatusUnauthorized)
- return nil
- }
-
- // strip off the "Bearer " prefix
- encoded := strings.TrimPrefix(authHeader, "Bearer ")
-
- // decode the base64-encoded credentials
- bytes, err := base64.StdEncoding.DecodeString(encoded)
-
- if err != nil {
- log.Printf("error decoding auth token: %v\n", err)
- http.Error(w, "error decoding auth token", http.StatusUnauthorized)
- return nil
- }
-
- // parse the credentials
- var parsed shared.AuthHeader
- err = json.Unmarshal(bytes, &parsed)
-
- if err != nil {
- log.Printf("error parsing auth token: %v\n", err)
- http.Error(w, "error parsing auth token", http.StatusUnauthorized)
- return nil
- }
-
- // validate the token
- authToken, err := db.ValidateAuthToken(parsed.Token)
-
- if err != nil {
- log.Printf("error validating auth token: %v\n", err)
-
- writeApiError(w, shared.ApiError{
- Type: shared.ApiErrorTypeInvalidToken,
- Status: http.StatusUnauthorized,
- Msg: "Invalid auth token",
- })
- return nil
- }
-
- user, err := db.GetUser(authToken.UserId)
-
- if err != nil {
- log.Printf("error getting user: %v\n", err)
- http.Error(w, "error getting user", http.StatusInternalServerError)
- return nil
- }
-
- if !requireOrg {
- return &types.ServerAuth{
- AuthToken: authToken,
- User: user,
- }
- }
-
- if parsed.OrgId == "" {
- log.Println("no org id")
- http.Error(w, "no org id", http.StatusUnauthorized)
- return nil
- }
-
- // validate the org membership
- isMember, err := db.ValidateOrgMembership(authToken.UserId, parsed.OrgId)
-
- if err != nil {
- log.Printf("error validating org membership: %v\n", err)
- http.Error(w, "error validating org membership", http.StatusInternalServerError)
- return nil
- }
-
- if !isMember {
- // check if there's an invite for this user and accept it if so (adds the user to the org)
- invite, err := db.GetInviteForOrgUser(parsed.OrgId, authToken.UserId)
-
- if err != nil {
- log.Printf("error getting invite for org user: %v\n", err)
- http.Error(w, "error getting invite for org user", http.StatusInternalServerError)
- return nil
- }
-
- if invite != nil {
- err := db.AcceptInvite(invite, authToken.UserId)
-
- if err != nil {
- log.Printf("error accepting invite: %v\n", err)
- http.Error(w, "error accepting invite", http.StatusInternalServerError)
- return nil
- }
-
- } else {
- log.Println("user is not a member of the org")
- http.Error(w, "not a member of org", http.StatusUnauthorized)
- return nil
- }
- }
-
- // get user permissions
- permissions, err := db.GetUserPermissions(authToken.UserId, parsed.OrgId)
-
- if err != nil {
- log.Printf("error getting user permissions: %v\n", err)
- http.Error(w, "error getting user permissions", http.StatusInternalServerError)
- return nil
- }
-
- // build the permissions map
- permissionsMap := make(map[string]bool)
- for _, permission := range permissions {
- permissionsMap[permission] = true
- }
-
- return &types.ServerAuth{
- AuthToken: authToken,
- User: user,
- OrgId: parsed.OrgId,
- Permissions: permissionsMap,
- }
-
-}
-
-func authorizeProject(w http.ResponseWriter, projectId string, auth *types.ServerAuth) bool {
- log.Println("authorizing project")
-
- hasProjectAccess, err := db.ValidateProjectAccess(projectId, auth.User.Id, auth.OrgId)
-
- if err != nil {
- log.Printf("error validating project membership: %v\n", err)
- http.Error(w, "error validating project membership", http.StatusInternalServerError)
- return false
- }
-
- if !hasProjectAccess {
- log.Println("user is not a member of the project")
- http.Error(w, "not a member of project", http.StatusUnauthorized)
- return false
- }
-
- return true
-}
-
-func authorizeProjectRename(w http.ResponseWriter, projectId string, auth *types.ServerAuth) bool {
- if !authorizeProject(w, projectId, auth) {
- return false
- }
-
- if !auth.HasPermission("rename_any_project") {
- log.Println("User does not have permission to rename project")
- http.Error(w, "User does not have permission to rename project", http.StatusForbidden)
- return false
- }
-
- return true
-}
-
-func authorizeProjectDelete(w http.ResponseWriter, projectId string, auth *types.ServerAuth) bool {
- if !authorizeProject(w, projectId, auth) {
- return false
- }
-
- if !auth.HasPermission("delete_any_project") {
- log.Println("User does not have permission to delete project")
- http.Error(w, "User does not have permission to delete project", http.StatusForbidden)
- return false
- }
-
- return true
-}
-
-func authorizePlan(w http.ResponseWriter, planId string, auth *types.ServerAuth) *db.Plan {
- log.Println("authorizing plan")
-
- plan, err := db.ValidatePlanAccess(planId, auth.User.Id, auth.OrgId)
-
- if err != nil {
- log.Printf("error validating plan membership: %v\n", err)
- http.Error(w, "error validating plan membership", http.StatusInternalServerError)
- return nil
- }
-
- if plan == nil {
- log.Println("user doesn't have access the plan")
- http.Error(w, "no access to plan", http.StatusUnauthorized)
- return nil
- }
-
- return plan
-}
-
-func authorizePlanUpdate(w http.ResponseWriter, planId string, auth *types.ServerAuth) *db.Plan {
- plan := authorizePlan(w, planId, auth)
-
- if plan == nil {
- return nil
- }
-
- if plan.OwnerId != auth.User.Id && !auth.HasPermission("update_any_plan") {
- log.Println("User does not have permission to update plan")
- http.Error(w, "User does not have permission to update plan", http.StatusForbidden)
- return nil
- }
-
- return plan
-}
-
-func authorizePlanDelete(w http.ResponseWriter, planId string, auth *types.ServerAuth) *db.Plan {
- plan := authorizePlan(w, planId, auth)
-
- if plan == nil {
- return nil
- }
-
- if plan.OwnerId != auth.User.Id && !auth.HasPermission("delete_any_plan") {
- log.Println("User does not have permission to delete plan")
- http.Error(w, "User does not have permission to delete plan", http.StatusForbidden)
- return nil
- }
-
- return plan
-}
-
-func authorizePlanRename(w http.ResponseWriter, planId string, auth *types.ServerAuth) *db.Plan {
- plan := authorizePlan(w, planId, auth)
-
- if plan == nil {
- return nil
- }
-
- if plan.OwnerId != auth.User.Id && !auth.HasPermission("rename_any_plan") {
- log.Println("User does not have permission to rename plan")
- http.Error(w, "User does not have permission to rename plan", http.StatusForbidden)
- return nil
- }
-
- return plan
-}
-
-func authorizePlanArchive(w http.ResponseWriter, planId string, auth *types.ServerAuth) *db.Plan {
- plan := authorizePlan(w, planId, auth)
-
- if plan == nil {
- return nil
- }
-
- if plan.OwnerId != auth.User.Id && !auth.HasPermission("archive_any_plan") {
- log.Println("User does not have permission to archive plan")
- http.Error(w, "User does not have permission to archive plan", http.StatusForbidden)
- return nil
- }
-
- return plan
-}
diff --git a/server/handlers/err_helper.go b/server/handlers/err_helper.go
deleted file mode 100644
index 276b6157..00000000
--- a/server/handlers/err_helper.go
+++ /dev/null
@@ -1,29 +0,0 @@
-package handlers
-
-import (
- "encoding/json"
- "log"
- "net/http"
-
- "github.com/plandex/plandex/shared"
-)
-
-func writeApiError(w http.ResponseWriter, apiErr shared.ApiError) {
- bytes, err := json.Marshal(apiErr)
- if err != nil {
- log.Printf("Error marshalling response: %v\n", err)
- // If marshalling fails, fall back to a simpler error message
- http.Error(w, "Error marshalling response", http.StatusInternalServerError)
- return
- }
-
- log.Printf("API Error: %v\n", apiErr.Msg)
-
- w.Header().Set("Content-Type", "application/json")
- w.WriteHeader(apiErr.Status)
-
- _, writeErr := w.Write(bytes)
- if writeErr != nil {
- log.Printf("Error writing response: %v\n", writeErr)
- }
-}
diff --git a/server/handlers/invites.go b/server/handlers/invites.go
deleted file mode 100644
index c29be4f4..00000000
--- a/server/handlers/invites.go
+++ /dev/null
@@ -1,300 +0,0 @@
-package handlers
-
-import (
- "encoding/json"
- "log"
- "net/http"
- "plandex-server/db"
- "strings"
-
- "github.com/gorilla/mux"
- "github.com/plandex/plandex/shared"
-)
-
-func InviteUserHandler(w http.ResponseWriter, r *http.Request) {
- log.Println("Received a request for InviteUserHandler")
- auth := authenticate(w, r, true)
- if auth == nil {
- return
- }
-
- if auth.User.IsTrial {
- writeApiError(w, shared.ApiError{
- Type: shared.ApiErrorTypeTrialActionNotAllowed,
- Status: http.StatusForbidden,
- Msg: "Free trial user can't invite other users",
- })
-
- return
- }
-
- currentUserId := auth.User.Id
-
- var req shared.InviteRequest
- 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
- }
- req.Email = strings.ToLower(req.Email)
-
- // ensure current user can invite target user
- if !auth.HasPermission(strings.Join([]string{"invite_user", req.OrgRoleId}, "|")) {
- log.Printf("User does not have permission to invite user with role: %v\n", req.OrgRoleId)
- http.Error(w, "User does not have permission to invite user with role: "+req.OrgRoleId, http.StatusForbidden)
- return
- }
-
- // ensure user doesn't already have access to org via domain
- split := strings.Split(req.Email, "@")
- if len(split) != 2 {
- log.Printf("Invalid email: %v\n", req.Email)
- http.Error(w, "Invalid email: "+req.Email, http.StatusBadRequest)
- return
- }
- domain := &split[1]
- org, err := db.GetOrg(auth.OrgId)
-
- if err != nil {
- log.Printf("Error getting org: %v\n", err)
- http.Error(w, "Error getting org: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- if org.AutoAddDomainUsers && org.Domain == domain {
- log.Printf("User already has access to org via domain: %v\n", domain)
- http.Error(w, "User already has access to org via domain: "+*domain, http.StatusBadRequest)
- }
-
- // ensure user with this email isn't already in the org
- user, err := db.GetUserByEmail(req.Email)
-
- if err != nil {
- log.Printf("Error getting user: %v\n", err)
- http.Error(w, "Error getting user: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- if user != nil {
- isMember, err := db.ValidateOrgMembership(user.Id, auth.OrgId)
-
- if err != nil {
- log.Printf("Error validating org membership: %v\n", err)
- http.Error(w, "Error validating org membership: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- if isMember {
- log.Println("User is already a member of org")
- http.Error(w, "User is already a member of org", http.StatusBadRequest)
- return
- }
- }
-
- // ensure invite isn't already active
- invite, err := db.GetInviteForOrgUser(auth.OrgId, req.Email)
-
- if err != nil {
- log.Printf("Error getting invite: %v\n", err)
- http.Error(w, "Error getting invite: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- if invite != nil {
- log.Println("Invite already exists")
- http.Error(w, "Invite already exists", http.StatusBadRequest)
- return
- }
-
- err = db.CreateInvite(&db.Invite{
- OrgId: auth.OrgId,
- OrgRoleId: req.OrgRoleId,
- Email: req.Email,
- Name: req.Name,
- InviterId: currentUserId,
- })
-
- if err != nil {
- log.Printf("Error creating invite: %v\n", err)
- http.Error(w, "Error creating invite: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- log.Println("Successfully created invite")
-}
-
-func ListPendingInvitesHandler(w http.ResponseWriter, r *http.Request) {
- log.Println("Received a request for ListInvitesHandler")
- auth := authenticate(w, r, true)
- if auth == nil {
- return
- }
-
- if auth.User.IsTrial {
- writeApiError(w, shared.ApiError{
- Type: shared.ApiErrorTypeTrialActionNotAllowed,
- Status: http.StatusForbidden,
- Msg: "Free trial user can't list invites",
- })
- return
- }
-
- invites, err := db.ListPendingInvites(auth.OrgId)
-
- if err != nil {
- log.Printf("Error listing invites: %v\n", err)
- http.Error(w, "Error listing invites: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- var apiInvites []*shared.Invite
- for _, invite := range invites {
- apiInvites = append(apiInvites, invite.ToApi())
- }
-
- bytes, err := json.Marshal(apiInvites)
-
- if err != nil {
- log.Printf("Error marshalling invites: %v\n", err)
- http.Error(w, "Error marshalling invites: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- w.Write(bytes)
- log.Println("Successfully processed request for ListPendingInvitesHandler")
-}
-
-func ListAcceptedInvitesHandler(w http.ResponseWriter, r *http.Request) {
- log.Println("Received a request for ListAcceptedInvitesHandler")
- auth := authenticate(w, r, true)
- if auth == nil {
- return
- }
-
- if auth.User.IsTrial {
- writeApiError(w, shared.ApiError{
- Type: shared.ApiErrorTypeTrialActionNotAllowed,
- Status: http.StatusForbidden,
- Msg: "Free trial user can't list invites",
- })
- return
- }
-
- invites, err := db.ListAcceptedInvites(auth.OrgId)
-
- if err != nil {
- log.Printf("Error listing invites: %v\n", err)
- http.Error(w, "Error listing invites: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- var apiInvites []*shared.Invite
- for _, invite := range invites {
- apiInvites = append(apiInvites, invite.ToApi())
- }
-
- bytes, err := json.Marshal(apiInvites)
-
- if err != nil {
- log.Printf("Error marshalling invites: %v\n", err)
- http.Error(w, "Error marshalling invites: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- w.Write(bytes)
- log.Println("Successfully processed request for ListAcceptedInvitesHandler")
-}
-
-func ListAllInvitesHandler(w http.ResponseWriter, r *http.Request) {
- log.Println("Received a request for ListAllInvitesHandler")
- auth := authenticate(w, r, true)
- if auth == nil {
- return
- }
-
- if auth.User.IsTrial {
- writeApiError(w, shared.ApiError{
- Type: shared.ApiErrorTypeTrialActionNotAllowed,
- Status: http.StatusForbidden,
- Msg: "Free trial user can't list invites",
- })
- return
- }
-
- invites, err := db.ListAllInvites(auth.OrgId)
-
- if err != nil {
- log.Printf("Error listing invites: %v\n", err)
- http.Error(w, "Error listing invites: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- var apiInvites []*shared.Invite
- for _, invite := range invites {
- apiInvites = append(apiInvites, invite.ToApi())
- }
-
- bytes, err := json.Marshal(apiInvites)
-
- if err != nil {
- log.Printf("Error marshalling invites: %v\n", err)
- http.Error(w, "Error marshalling invites: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- w.Write(bytes)
- log.Println("Successfully processed request for ListAllInvitesHandler")
-}
-
-func DeleteInviteHandler(w http.ResponseWriter, r *http.Request) {
- log.Println("Received a request for DeleteInviteHandler")
- auth := authenticate(w, r, true)
- if auth == nil {
- return
- }
-
- if auth.User.IsTrial {
- writeApiError(w, shared.ApiError{
- Type: shared.ApiErrorTypeTrialActionNotAllowed,
- Status: http.StatusForbidden,
- Msg: "Free trial user can't delete invites",
- })
- return
- }
-
- vars := mux.Vars(r)
- inviteId := vars["inviteId"]
-
- invite, err := db.GetInvite(inviteId)
-
- if err != nil {
- log.Printf("Error getting invite: %v\n", err)
- http.Error(w, "Error getting invite: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- if invite.OrgId != auth.OrgId {
- log.Printf("Invite does not belong to org: %v\n", inviteId)
- http.Error(w, "Invite does not belong to org: "+inviteId, http.StatusBadRequest)
- return
- }
-
- // ensure current user can remove target invite
- if !(auth.HasPermission(strings.Join([]string{"remove_user", invite.OrgRoleId}, "|")) ||
- (auth.User.Id == invite.InviterId && auth.HasPermission(strings.Join([]string{"invite_user", invite.OrgRoleId}, "|")))) {
- log.Printf("User does not have permission to remove invite with role: %v\n", invite.OrgRoleId)
- http.Error(w, "User does not have permission to remove invite with role: "+invite.OrgRoleId, http.StatusForbidden)
- return
- }
-
- err = db.DeleteInvite(inviteId, nil)
-
- if err != nil {
- log.Printf("Error deleting invite: %v\n", err)
- http.Error(w, "Error deleting invite: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- log.Println("Successfully deleted invite")
-}
diff --git a/server/handlers/orgs.go b/server/handlers/orgs.go
deleted file mode 100644
index aa591291..00000000
--- a/server/handlers/orgs.go
+++ /dev/null
@@ -1,201 +0,0 @@
-package handlers
-
-import (
- "encoding/json"
- "io"
- "log"
- "net/http"
- "plandex-server/db"
-
- "github.com/plandex/plandex/shared"
-)
-
-func ListOrgsHandler(w http.ResponseWriter, r *http.Request) {
- log.Println("Received request for ListOrgsHandler")
-
- auth := authenticate(w, r, false)
- if auth == nil {
- return
- }
-
- orgs, err := db.GetAccessibleOrgsForUser(auth.User)
-
- if err != nil {
- log.Printf("Error listing orgs: %v\n", err)
- http.Error(w, "Error listing orgs: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- var apiOrgs []*shared.Org
- for _, org := range orgs {
- apiOrgs = append(apiOrgs, org.ToApi())
- }
-
- bytes, err := json.Marshal(apiOrgs)
-
- 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 listed orgs")
-
- w.Write(bytes)
-}
-
-func CreateOrgHandler(w http.ResponseWriter, r *http.Request) {
- log.Println("Received request for CreateOrgHandler")
-
- auth := authenticate(w, r, false)
- if auth == nil {
- return
- }
-
- if auth.User.IsTrial {
- writeApiError(w, shared.ApiError{
- Type: shared.ApiErrorTypeTrialActionNotAllowed,
- Status: http.StatusForbidden,
- Msg: "Free trial user can't create org",
- })
- return
- }
-
- // read the request body
- body, err := io.ReadAll(r.Body)
- if err != nil {
- log.Printf("Error reading request body: %v\n", err)
- http.Error(w, "Error reading request body: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- var req shared.CreateOrgRequest
- err = json.Unmarshal(body, &req)
- if err != nil {
- log.Printf("Error unmarshalling request: %v\n", err)
- http.Error(w, "Error unmarshalling request: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- // 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")
- }
- }
- }()
-
- var domain *string
- if req.AutoAddDomainUsers {
- if shared.IsEmailServiceDomain(auth.User.Domain) {
- log.Printf("Invalid domain: %v\n", auth.User.Domain)
- http.Error(w, "Invalid domain: "+auth.User.Domain, http.StatusBadRequest)
- return
- }
-
- domain = &auth.User.Domain
- }
-
- // create a new org
- org, err := db.CreateOrg(&req, auth.AuthToken.UserId, domain, tx)
-
- if err != nil {
- log.Printf("Error creating org: %v\n", err)
- http.Error(w, "Error creating org: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- if org.AutoAddDomainUsers && org.Domain != nil {
- err = db.AddOrgDomainUsers(org.Id, *org.Domain, tx)
-
- if err != nil {
- log.Printf("Error adding org domain users: %v\n", err)
- http.Error(w, "Error adding org domain users: "+err.Error(), http.StatusInternalServerError)
- return
- }
- }
-
- 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.CreateOrgResponse{
- Id: org.Id,
- }
-
- 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 org")
-
- w.Write(bytes)
-}
-
-func ListOrgRolesHandler(w http.ResponseWriter, r *http.Request) {
- log.Println("Received request for ListOrgRolesHandler")
-
- auth := authenticate(w, r, true)
- if auth == nil {
- return
- }
-
- if auth.User.IsTrial {
- writeApiError(w, shared.ApiError{
- Type: shared.ApiErrorTypeTrialActionNotAllowed,
- Status: http.StatusForbidden,
- Msg: "Free trial user can't list org roles",
- })
- return
- }
-
- if !auth.HasPermission("list_org_roles") {
- log.Println("User cannot list org roles")
- http.Error(w, "User cannot list org roles", http.StatusForbidden)
- return
- }
-
- roles, err := db.ListOrgRoles(auth.OrgId)
-
- if err != nil {
- log.Printf("Error listing org roles: %v\n", err)
- http.Error(w, "Error listing org roles: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- var apiRoles []*shared.OrgRole
- for _, role := range roles {
- apiRoles = append(apiRoles, role.ToApi())
- }
-
- bytes, err := json.Marshal(apiRoles)
-
- 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 listed org roles")
-
- w.Write(bytes)
-}
diff --git a/server/handlers/plans_changes.go b/server/handlers/plans_changes.go
deleted file mode 100644
index 2b076c9a..00000000
--- a/server/handlers/plans_changes.go
+++ /dev/null
@@ -1,222 +0,0 @@
-package handlers
-
-import (
- "encoding/json"
- "log"
- "net/http"
- "plandex-server/db"
- "time"
-
- "github.com/gorilla/mux"
-)
-
-func CurrentPlanHandler(w http.ResponseWriter, r *http.Request) {
- log.Println("Received request for ListPlanChangesHandler")
-
- auth := authenticate(w, r, true)
- if auth == nil {
- return
- }
-
- vars := mux.Vars(r)
- planId := vars["planId"]
-
- log.Println("planId: ", planId)
-
- if authorizePlan(w, planId, auth) == nil {
- return
- }
-
- contexts, err := db.GetPlanContexts(auth.OrgId, planId, true)
-
- if err != nil {
- log.Printf("Error getting plan contexts: %v\n", err)
- http.Error(w, "Error getting plan contexts: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- planState, err := db.GetCurrentPlanState(db.CurrentPlanStateParams{
- OrgId: auth.OrgId,
- PlanId: planId,
- Contexts: contexts,
- })
-
- if err != nil {
- log.Printf("Error getting current plan state: %v\n", err)
- http.Error(w, "Error getting current plan state: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- jsonBytes, err := json.Marshal(planState)
-
- if err != nil {
- log.Printf("Error marshalling plan state: %v\n", err)
- http.Error(w, "Error marshalling plan state: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- log.Println("Successfully retrieved current plan state")
-
- w.Write(jsonBytes)
-}
-
-func ApplyPlanHandler(w http.ResponseWriter, r *http.Request) {
- log.Println("Received request for ApplyPlanHandler")
-
- auth := authenticate(w, r, true)
- if auth == nil {
- return
- }
-
- vars := mux.Vars(r)
- planId := vars["planId"]
- log.Println("planId: ", planId)
-
- if authorizePlan(w, planId, auth) == nil {
- return
- }
-
- err := db.ApplyPlan(auth.OrgId, planId)
-
- if err != nil {
- log.Printf("Error applying plan: %v\n", err)
- http.Error(w, "Error applying plan: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- log.Println("Successfully applied plan", planId)
-}
-
-func RejectAllChangesHandler(w http.ResponseWriter, r *http.Request) {
- log.Println("Received request for RejectAllChangesHandler")
-
- auth := authenticate(w, r, true)
- if auth == nil {
- return
- }
-
- vars := mux.Vars(r)
- planId := vars["planId"]
- log.Println("planId: ", planId)
-
- if authorizePlan(w, planId, auth) == nil {
- return
- }
-
- err := db.RejectAllResults(auth.OrgId, planId)
-
- if err != nil {
- log.Printf("Error rejecting all changes: %v\n", err)
- http.Error(w, "Error rejecting all changes: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- log.Println("Successfully rejected all changes for plan", planId)
-}
-
-func RejectResultHandler(w http.ResponseWriter, r *http.Request) {
- log.Println("Received request for RejectResultHandler")
-
- auth := authenticate(w, r, true)
- if auth == nil {
- return
- }
-
- vars := mux.Vars(r)
- planId := vars["planId"]
- resultId := vars["resultId"]
-
- log.Println("planId: ", planId, "resultId: ", resultId)
-
- if authorizePlan(w, planId, auth) == nil {
- return
- }
-
- err := db.RejectPlanFileResult(auth.OrgId, planId, resultId, time.Now())
-
- if err != nil {
- log.Printf("Error rejecting result: %v\n", err)
- http.Error(w, "Error rejecting result: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- log.Println("Successfully rejected plan result", resultId)
-}
-
-func RejectReplacementHandler(w http.ResponseWriter, r *http.Request) {
- log.Println("Received request for RejectReplacementHandler")
-
- auth := authenticate(w, r, true)
- if auth == nil {
- return
- }
-
- vars := mux.Vars(r)
- planId := vars["planId"]
- resultId := vars["resultId"]
- replacementId := vars["replacementId"]
-
- log.Println("planId: ", planId, "resultId: ", resultId, "replacementId: ", replacementId)
-
- if authorizePlan(w, planId, auth) == nil {
- return
- }
-
- err := db.RejectReplacement(auth.OrgId, planId, resultId, replacementId)
-
- if err != nil {
- log.Printf("Error rejecting replacement: %v\n", err)
- http.Error(w, "Error rejecting replacement: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- log.Println("Successfully rejected replacement", replacementId)
-}
-
-func ArchivePlanHandler(w http.ResponseWriter, r *http.Request) {
- auth := authenticate(w, r, true)
- if auth == nil {
- return
- }
-
- log.Println("Received request for ArchivePlanHandler")
-
- vars := mux.Vars(r)
- planId := vars["planId"]
- log.Println("planId: ", planId)
-
- plan := authorizePlanArchive(w, planId, auth)
-
- if plan == nil {
- return
- }
-
- if plan.ArchivedAt != nil {
- log.Println("Plan already archived")
- http.Error(w, "Plan already archived", http.StatusBadRequest)
- return
- }
-
- res, err := db.Conn.Exec("UPDATE plans SET archived_at = NOW() WHERE id = $1", planId)
-
- if err != nil {
- log.Printf("Error archiving plan: %v\n", err)
- http.Error(w, "Error archiving plan: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- rowsAffected, err := res.RowsAffected()
- if err != nil {
- log.Printf("Error getting rows affected: %v\n", err)
- http.Error(w, "Error getting rows affected: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- if rowsAffected == 0 {
- log.Println("Plan not found")
- http.Error(w, "Not found", http.StatusNotFound)
- return
- }
-
- log.Println("Successfully archived plan", planId)
-}
diff --git a/server/handlers/plans_context.go b/server/handlers/plans_context.go
deleted file mode 100644
index 13a0ffda..00000000
--- a/server/handlers/plans_context.go
+++ /dev/null
@@ -1,524 +0,0 @@
-package handlers
-
-import (
- "crypto/sha256"
- "encoding/hex"
- "encoding/json"
- "fmt"
- "io"
- "log"
- "net/http"
- "plandex-server/db"
- "sync"
-
- "github.com/davecgh/go-spew/spew"
- "github.com/google/uuid"
- "github.com/gorilla/mux"
- "github.com/plandex/plandex/shared"
-)
-
-func ListContextHandler(w http.ResponseWriter, r *http.Request) {
- log.Println("Received request for ListContextHandler")
-
- auth := authenticate(w, r, true)
- if auth == nil {
- return
- }
-
- vars := mux.Vars(r)
- planId := vars["planId"]
- log.Println("planId: ", planId)
-
- if authorizePlan(w, planId, auth) == nil {
- return
- }
-
- dbContexts, err := db.GetPlanContexts(auth.OrgId, planId, false)
-
- if err != nil {
- log.Printf("Error getting contexts: %v\n", err)
- http.Error(w, "Error getting contexts: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- var apiContexts []*shared.Context
-
- for _, dbContext := range dbContexts {
- apiContexts = append(apiContexts, dbContext.ToApi())
- }
-
- bytes, err := json.Marshal(apiContexts)
-
- if err != nil {
- log.Printf("Error marshalling contexts: %v\n", err)
- http.Error(w, "Error marshalling contexts: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- w.Write(bytes)
-}
-
-func LoadContextHandler(w http.ResponseWriter, r *http.Request) {
- log.Println("Received request for LoadContextHandler")
-
- auth := authenticate(w, r, true)
- if auth == nil {
- return
- }
- currentUserId := auth.User.Id
-
- vars := mux.Vars(r)
- planId := vars["planId"]
- log.Println("planId: ", planId)
-
- if authorizePlan(w, planId, auth) == nil {
- return
- }
-
- // read the request body
- body, err := io.ReadAll(r.Body)
- if err != nil {
- log.Printf("Error reading request body: %v\n", err)
- http.Error(w, "Error reading request body", http.StatusInternalServerError)
- return
- }
- defer r.Body.Close()
-
- var requestBody shared.LoadContextRequest
- if err := json.Unmarshal(body, &requestBody); err != nil {
- log.Printf("Error parsing request body: %v\n", err)
- http.Error(w, "Error parsing request body", http.StatusBadRequest)
- return
- }
-
- // load plan
- plan, err := db.GetPlan(planId)
-
- if err != nil {
- log.Printf("Plan not found: %v\n", err)
- http.Error(w, "Plan not found: "+err.Error(), http.StatusBadRequest)
- }
-
- maxTokens := shared.MaxContextTokens
- tokensAdded := 0
- totalTokens := plan.ContextTokens
-
- paramsByTempId := make(map[string]*shared.LoadContextParams)
- numTokensByTempId := make(map[string]int)
-
- for _, context := range requestBody {
- tempId := uuid.New().String()
- numTokens, err := shared.GetNumTokens(context.Body)
-
- if err != nil {
- log.Printf("Error getting num tokens: %v\n", err)
- http.Error(w, "Error getting num tokens: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- paramsByTempId[tempId] = context
- numTokensByTempId[tempId] = numTokens
-
- tokensAdded += numTokens
- totalTokens += numTokens
- }
-
- if totalTokens > maxTokens {
- log.Printf("The total number of tokens (%d) exceeds the maximum allowed (%d)", totalTokens, maxTokens)
- res := shared.LoadContextResponse{
- TokensAdded: tokensAdded,
- TotalTokens: totalTokens,
- MaxTokensExceeded: true,
- }
-
- bytes, err := json.Marshal(res)
-
- if err != nil {
- log.Printf("Error marshalling response: %v\n", err)
- http.Error(w, "Error marshalling response: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- w.Write(bytes)
- return
- }
-
- dbContextsCh := make(chan *db.Context)
- errCh := make(chan error)
- for tempId, params := range paramsByTempId {
-
- go func(tempId string, params *shared.LoadContextParams) {
- hash := sha256.Sum256([]byte(params.Body))
- sha := hex.EncodeToString(hash[:])
-
- context := db.Context{
- // Id generated by db layer
- OrgId: auth.OrgId,
- OwnerId: currentUserId,
- PlanId: planId,
- ContextType: params.ContextType,
- Name: params.Name,
- Url: params.Url,
- FilePath: params.FilePath,
- NumTokens: numTokensByTempId[tempId],
- Sha: sha,
- Body: params.Body,
- }
-
- err := db.StoreContext(&context)
-
- if err != nil {
- errCh <- err
- return
- }
-
- dbContextsCh <- &context
-
- }(tempId, params)
- }
-
- var apiContexts []*shared.Context
-
- for i := 0; i < len(requestBody); i++ {
- select {
- case err := <-errCh:
- log.Printf("Error creating context: %v\n", err)
- http.Error(w, "Error creating context: "+err.Error(), http.StatusInternalServerError)
- return
- case dbContext := <-dbContextsCh:
- apiContext := dbContext.ToApi()
- apiContext.Body = ""
- apiContexts = append(apiContexts, apiContext)
- }
- }
-
- commitMsg := shared.SummaryForLoadContext(apiContexts, tokensAdded, totalTokens) + "\n\n" + shared.TableForLoadContext(apiContexts)
- err = db.GitAddAndCommit(auth.OrgId, planId, commitMsg)
-
- if err != nil {
- log.Printf("Error committing changes: %v\n", err)
- http.Error(w, "Error committing changes: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- err = db.AddPlanContextTokens(planId, tokensAdded)
- if err != nil {
- log.Printf("Error updating plan tokens: %v\n", err)
- http.Error(w, "Error updating plan tokens: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- res := shared.LoadContextResponse{
- TokensAdded: tokensAdded,
- TotalTokens: totalTokens,
- Msg: commitMsg,
- }
-
- bytes, err := json.Marshal(res)
-
- 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 processed LoadContextHandler request")
-
- w.Write(bytes)
-}
-
-func UpdateContextHandler(w http.ResponseWriter, r *http.Request) {
- log.Println("Received request for UpdateContextHandler")
-
- auth := authenticate(w, r, true)
- if auth == nil {
- return
- }
-
- vars := mux.Vars(r)
- planId := vars["planId"]
- log.Println("planId: ", planId)
-
- if authorizePlan(w, planId, auth) == nil {
- return
- }
-
- // read the request body
- body, err := io.ReadAll(r.Body)
- if err != nil {
- log.Printf("Error reading request body: %v\n", err)
- http.Error(w, "Error reading request body", http.StatusInternalServerError)
- return
- }
- defer r.Body.Close()
-
- var requestBody shared.UpdateContextRequest
- if err := json.Unmarshal(body, &requestBody); err != nil {
- log.Printf("Error parsing request body: %v\n", err)
- http.Error(w, "Error parsing request body", http.StatusBadRequest)
- return
- }
-
- // load plan
- plan, err := db.GetPlan(planId)
-
- if err != nil {
- log.Printf("Plan not found: %v\n", err)
- http.Error(w, "Plan not found: "+err.Error(), http.StatusBadRequest)
- }
-
- maxTokens := shared.MaxContextTokens
- tokensDiff := 0
- totalTokens := plan.ContextTokens
- tokensDiffById := make(map[string]int)
- contextsById := make(map[string]*db.Context)
- var updatedContexts []*shared.Context
-
- numFiles := 0
- numUrls := 0
- numTrees := 0
-
- var mu sync.Mutex
- errCh := make(chan error)
-
- for id, params := range requestBody {
- go func(id string, params *shared.UpdateContextParams) {
- context, err := db.GetContext(auth.OrgId, planId, id, true)
-
- if err != nil {
- errCh <- fmt.Errorf("error getting context: %v", err)
- return
- }
-
- spew.Dump(context)
-
- mu.Lock()
- defer mu.Unlock()
-
- contextsById[id] = context
- updatedContexts = append(updatedContexts, context.ToApi())
- updateNumTokens, err := shared.GetNumTokens(params.Body)
-
- if err != nil {
- errCh <- fmt.Errorf("error getting num tokens: %v", err)
- return
- }
-
- tokenDiff := updateNumTokens - context.NumTokens
- tokensDiffById[id] = tokenDiff
- tokensDiff += tokenDiff
- totalTokens += tokenDiff
-
- context.NumTokens = updateNumTokens
-
- switch context.ContextType {
- case shared.ContextFileType:
- numFiles++
- case shared.ContextURLType:
- numUrls++
- case shared.ContextDirectoryTreeType:
- numTrees++
- }
-
- errCh <- nil
- }(id, params)
- }
-
- for i := 0; i < len(requestBody); i++ {
- err := <-errCh
- if err != nil {
- log.Printf("Error updating context: %v\n", err)
- http.Error(w, "Error updating context: "+err.Error(), http.StatusInternalServerError)
- return
- }
- }
-
- if totalTokens > maxTokens {
- log.Printf("The total number of tokens (%d) exceeds the maximum allowed (%d)", totalTokens, maxTokens)
- res := shared.LoadContextResponse{
- TokensAdded: tokensDiff,
- TotalTokens: totalTokens,
- MaxTokensExceeded: true,
- }
-
- bytes, err := json.Marshal(res)
-
- if err != nil {
- log.Printf("Error marshalling response: %v\n", err)
- http.Error(w, "Error marshalling response: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- w.Write(bytes)
- return
- }
-
- errCh = make(chan error)
-
- for id, params := range requestBody {
- go func(id string, params *shared.UpdateContextParams) {
-
- context := contextsById[id]
-
- hash := sha256.Sum256([]byte(params.Body))
- sha := hex.EncodeToString(hash[:])
-
- context.Body = params.Body
- context.Sha = sha
-
- errCh <- db.StoreContext(context)
- }(id, params)
- }
-
- for i := 0; i < len(requestBody); i++ {
- err := <-errCh
- if err != nil {
- log.Printf("Error creating context: %v\n", err)
- http.Error(w, "Error creating context: "+err.Error(), http.StatusInternalServerError)
- return
- }
- }
-
- updateRes := &shared.ContextUpdateResult{
- UpdatedContexts: updatedContexts,
- TokenDiffsById: tokensDiffById,
- TokensDiff: tokensDiff,
- TotalTokens: totalTokens,
- NumFiles: numFiles,
- NumUrls: numUrls,
- NumTrees: numTrees,
- }
-
- commitMsg := shared.SummaryForUpdateContext(updateRes) + "\n\n" + shared.TableForContextUpdate(updateRes)
- err = db.GitAddAndCommit(auth.OrgId, planId, commitMsg)
-
- if err != nil {
- log.Printf("Error committing changes: %v\n", err)
- http.Error(w, "Error committing changes: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- err = db.AddPlanContextTokens(planId, tokensDiff)
- if err != nil {
- log.Printf("Error updating plan tokens: %v\n", err)
- http.Error(w, "Error updating plan tokens: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- res := shared.UpdateContextResponse{
- TokensAdded: tokensDiff,
- TotalTokens: totalTokens,
- Msg: commitMsg,
- }
-
- bytes, err := json.Marshal(res)
-
- 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 processed UpdateContextHandler request")
-
- w.Write(bytes)
-}
-
-func DeleteContextHandler(w http.ResponseWriter, r *http.Request) {
- log.Println("Received request for DeleteContextHandler")
-
- auth := authenticate(w, r, true)
- if auth == nil {
- return
- }
-
- vars := mux.Vars(r)
- planId := vars["planId"]
- log.Println("planId: ", planId)
-
- plan := authorizePlan(w, planId, auth)
-
- if plan == nil {
- return
- }
-
- // read the request body
- body, err := io.ReadAll(r.Body)
- if err != nil {
- log.Printf("Error reading request body: %v\n", err)
- http.Error(w, "Error reading request body", http.StatusInternalServerError)
- return
- }
- defer r.Body.Close()
-
- var requestBody shared.DeleteContextRequest
- if err := json.Unmarshal(body, &requestBody); err != nil {
- log.Printf("Error parsing request body: %v\n", err)
- http.Error(w, "Error parsing request body", http.StatusBadRequest)
- return
- }
-
- dbContexts, err := db.GetPlanContexts(auth.OrgId, planId, false)
-
- if err != nil {
- log.Printf("Error getting contexts: %v\n", err)
- http.Error(w, "Error getting contexts: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- var toRemove []*db.Context
- for _, dbContext := range dbContexts {
- if _, ok := requestBody.Ids[dbContext.Id]; ok {
- toRemove = append(toRemove, dbContext)
- }
- }
-
- err = db.ContextRemove(toRemove)
-
- if err != nil {
- log.Printf("Error deleting contexts: %v\n", err)
- http.Error(w, "Error deleting contexts: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- removeTokens := 0
- var toRemoveApiContexts []*shared.Context
- for _, dbContext := range toRemove {
- toRemoveApiContexts = append(toRemoveApiContexts, dbContext.ToApi())
- removeTokens += dbContext.NumTokens
- }
-
- commitMsg := shared.SummaryForRemoveContext(toRemoveApiContexts, plan.ContextTokens) + "\n\n" + shared.TableForRemoveContext(toRemoveApiContexts)
- err = db.GitAddAndCommit(auth.OrgId, planId, commitMsg)
-
- if err != nil {
- log.Printf("Error committing changes: %v\n", err)
- http.Error(w, "Error committing changes: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- err = db.AddPlanContextTokens(planId, -removeTokens)
- if err != nil {
- log.Printf("Error updating plan tokens: %v\n", err)
- http.Error(w, "Error updating plan tokens: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- res := shared.DeleteContextResponse{
- TokensRemoved: removeTokens,
- TotalTokens: plan.ContextTokens - removeTokens,
- Msg: commitMsg,
- }
-
- bytes, err := json.Marshal(res)
-
- 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 deleted contexts")
-
- w.Write(bytes)
-}
diff --git a/server/handlers/plans_convo.go b/server/handlers/plans_convo.go
deleted file mode 100644
index 7bb3e873..00000000
--- a/server/handlers/plans_convo.go
+++ /dev/null
@@ -1,47 +0,0 @@
-package handlers
-
-import (
- "encoding/json"
- "log"
- "net/http"
- "plandex-server/db"
-
- "github.com/gorilla/mux"
-)
-
-func ListConvoHandler(w http.ResponseWriter, r *http.Request) {
- log.Println("Received a request for ListConvoHandler")
- auth := authenticate(w, r, true)
- if auth == nil {
- return
- }
-
- vars := mux.Vars(r)
- planId := vars["planId"]
-
- log.Println("planId: ", planId)
-
- if authorizePlan(w, planId, auth) == nil {
- return
- }
-
- convoMessage, err := db.GetPlanConvo(auth.OrgId, planId)
-
- if err != nil {
- log.Println("Error getting plan convo: ", err)
- http.Error(w, "Error getting plan convo: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- bytes, err := json.Marshal(convoMessage)
-
- if err != nil {
- log.Println("Error marshalling plan convo: ", err)
- http.Error(w, "Error marshalling plan convo: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- log.Println("Successfully processed request for ListConvoHandler")
- w.Write(bytes)
-
-}
diff --git a/server/handlers/plans_crud.go b/server/handlers/plans_crud.go
deleted file mode 100644
index ca61926f..00000000
--- a/server/handlers/plans_crud.go
+++ /dev/null
@@ -1,348 +0,0 @@
-package handlers
-
-import (
- "encoding/json"
- "fmt"
- "io"
- "log"
- "net/http"
- "os"
- "plandex-server/db"
-
- "github.com/gorilla/mux"
- "github.com/plandex/plandex/shared"
-)
-
-const TrialMaxPlans = 10
-
-func CreatePlanHandler(w http.ResponseWriter, r *http.Request) {
- log.Println("Received request for CreatePlanHandler")
-
- auth := authenticate(w, r, true)
- if auth == nil {
- return
- }
-
- if !auth.HasPermission("create_plan") {
- log.Println("User does not have permission to create a plan")
- http.Error(w, "User does not have permission to create a plan", http.StatusForbidden)
- return
- }
-
- vars := mux.Vars(r)
- projectId := vars["projectId"]
-
- log.Println("projectId: ", projectId)
-
- if !authorizeProject(w, projectId, auth) {
- 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 >= TrialMaxPlans {
- writeApiError(w, shared.ApiError{
- Type: shared.ApiErrorTypeTrialPlansExceeded,
- Status: http.StatusForbidden,
- Msg: "User has reached max number of free trial plans",
- TrialPlansExceededError: &shared.TrialPlansExceededError{
- MaxPlans: TrialMaxPlans,
- },
- })
- return
- }
- }
- }
-
- // read the request body
- body, err := io.ReadAll(r.Body)
- if err != nil {
- log.Printf("Error reading request body: %v\n", err)
- http.Error(w, "Error reading request body", http.StatusInternalServerError)
- return
- }
- defer r.Body.Close()
-
- var requestBody shared.CreatePlanRequest
- if err := json.Unmarshal(body, &requestBody); err != nil {
- log.Printf("Error parsing request body: %v\n", err)
- http.Error(w, "Error parsing request body", http.StatusBadRequest)
- return
- }
-
- name := requestBody.Name
- if name == "" {
- name = "draft"
- }
-
- if name == "draft" {
- // delete any existing draft plans
- err = db.DeleteDraftPlans(auth.OrgId, projectId, auth.User.Id)
-
- if err != nil {
- log.Printf("Error deleting draft plans: %v\n", err)
- http.Error(w, "Error deleting draft plans: "+err.Error(), http.StatusInternalServerError)
- return
- }
- } else {
- i := 2
- originalName := name
- for {
- var count int
- err := db.Conn.Get(&count, "SELECT COUNT(*) FROM plans WHERE project_id = $1 AND owner_id = $2 AND name = $3", projectId, auth.User.Id, name)
-
- if err != nil {
- log.Printf("Error checking if plan exists: %v\n", err)
- http.Error(w, "Error checking if plan exists: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- if count == 0 {
- break
- }
-
- name = originalName + "." + fmt.Sprint(i)
- i++
- }
- }
-
- plan, err := db.CreatePlan(auth.OrgId, projectId, auth.User.Id, name)
-
- if err != nil {
- log.Printf("Error creating plan: %v\n", err)
- http.Error(w, "Error creating plan: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- resp := shared.CreatePlanResponse{
- Id: plan.Id,
- Name: plan.Name,
- }
-
- 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
- }
-
- w.Write(bytes)
-
- log.Printf("Successfully created plan: %v\n", plan)
-}
-
-func GetPlanHandler(w http.ResponseWriter, r *http.Request) {
- log.Println("Received request for GetPlanHandler")
-
- auth := authenticate(w, r, true)
- if auth == nil {
- return
- }
-
- vars := mux.Vars(r)
- planId := vars["planId"]
-
- log.Println("planId: ", planId)
-
- plan := authorizePlan(w, planId, auth)
-
- if plan == nil {
- return
- }
-
- bytes, err := json.Marshal(plan)
-
- if err != nil {
- log.Printf("Error marshalling plan: %v\n", err)
- http.Error(w, "Error marshalling plan: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- w.Write(bytes)
-}
-
-func DeletePlanHandler(w http.ResponseWriter, r *http.Request) {
- log.Println("Received request for DeletePlanHandler")
-
- auth := authenticate(w, r, true)
- if auth == nil {
- return
- }
-
- vars := mux.Vars(r)
- planId := vars["planId"]
-
- log.Println("planId: ", planId)
-
- plan := authorizePlanDelete(w, planId, auth)
-
- if plan == nil {
- return
- }
-
- if plan.OwnerId != auth.User.Id {
- log.Println("Only the plan owner can delete a plan")
- http.Error(w, "Only the plan owner can delete a plan", http.StatusForbidden)
- return
- }
-
- res, err := db.Conn.Exec("DELETE FROM plans WHERE id = $1", planId)
-
- if err != nil {
- log.Printf("Error deleting plan: %v\n", err)
- http.Error(w, "Error deleting plan: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- rowsAffected, err := res.RowsAffected()
- if err != nil {
- log.Printf("Error getting rows affected: %v\n", err)
- http.Error(w, "Error getting rows affected: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- if rowsAffected == 0 {
- log.Println("Plan not found")
- http.Error(w, "Not found", http.StatusNotFound)
- return
- }
-
- err = db.DeletePlanDir(auth.OrgId, planId)
-
- if err != nil {
- log.Printf("Error deleting plan dir: %v\n", err)
- http.Error(w, "Error deleting plan dir: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- log.Println("Successfully deleted plan", planId)
-}
-
-func DeleteAllPlansHandler(w http.ResponseWriter, r *http.Request) {
- log.Println("Received request for DeleteAllPlansHandler")
-
- auth := authenticate(w, r, true)
- if auth == nil {
- return
- }
-
- vars := mux.Vars(r)
- projectId := vars["projectId"]
-
- log.Println("projectId: ", projectId)
-
- if !authorizeProject(w, projectId, auth) {
- return
- }
-
- err := db.DeleteOwnerPlans(auth.OrgId, projectId, auth.User.Id)
-
- if err != nil {
- log.Printf("Error deleting plans: %v\n", err)
- http.Error(w, "Error deleting plans: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- log.Println("Successfully deleted all plans")
-}
-
-func ListPlansHandler(w http.ResponseWriter, r *http.Request) {
- log.Println("Received request for ListPlansHandler")
- auth := authenticate(w, r, true)
- if auth == nil {
- return
- }
-
- vars := mux.Vars(r)
- projectId := vars["projectId"]
-
- log.Println("projectId: ", projectId)
-
- if !authorizeProject(w, projectId, auth) {
- return
- }
-
- plans, err := db.ListOwnedPlans(projectId, auth.User.Id, false, "")
-
- if err != nil {
- log.Printf("Error listing plans: %v\n", err)
- http.Error(w, "Error listing plans: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- jsonBytes, err := json.Marshal(plans)
- if err != nil {
- log.Printf("Error marshalling plans: %v\n", err)
- http.Error(w, "Error marshalling plans: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- log.Println("Successfully processed ListPlansHandler request")
-
- w.Write(jsonBytes)
-}
-
-func ListArchivedPlansHandler(w http.ResponseWriter, r *http.Request) {
- log.Println("Received request for ListArchivedPlansHandler")
- auth := authenticate(w, r, true)
- if auth == nil {
- return
- }
-
- vars := mux.Vars(r)
- projectId := vars["projectId"]
-
- log.Println("projectId: ", projectId)
-
- if !authorizeProject(w, projectId, auth) {
- return
- }
-
- plans, err := db.ListOwnedPlans(projectId, "", true, "")
-
- if err != nil {
- log.Printf("Error listing plans: %v\n", err)
- http.Error(w, "Error listing plans: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- jsonBytes, err := json.Marshal(plans)
- if err != nil {
- log.Printf("Error marshalling plans: %v\n", err)
- http.Error(w, "Error marshalling plans: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- log.Println("Successfully processed ListArchivedPlansHandler request")
-
- w.Write(jsonBytes)
-}
-
-func ListPlansRunningHandler(w http.ResponseWriter, r *http.Request) {
- log.Println("Received request for ListPlansRunningHandler")
- auth := authenticate(w, r, true)
- if auth == nil {
- return
- }
-
- vars := mux.Vars(r)
- projectId := vars["projectId"]
-
- log.Println("projectId: ", projectId)
-
- if !authorizeProject(w, projectId, auth) {
- return
- }
-
- // TODO: implement when status is figured out
-
-}
diff --git a/server/handlers/plans_exec.go b/server/handlers/plans_exec.go
deleted file mode 100644
index 02960a70..00000000
--- a/server/handlers/plans_exec.go
+++ /dev/null
@@ -1,156 +0,0 @@
-package handlers
-
-import (
- "encoding/json"
- "io"
- "log"
- "net/http"
- "os"
- "plandex-server/db"
- model "plandex-server/model/plan"
-
- "github.com/gorilla/mux"
- "github.com/plandex/plandex/shared"
-)
-
-const TrialMaxMessages = 15
-
-func TellPlanHandler(w http.ResponseWriter, r *http.Request) {
- log.Println("Received request for TellPlanHandler")
-
- auth := authenticate(w, r, true)
- if auth == nil {
- return
- }
-
- vars := mux.Vars(r)
- planId := vars["planId"]
-
- log.Println("planId: ", planId)
-
- plan := authorizePlanUpdate(w, planId, auth)
-
- if plan == nil {
- return
- }
-
- if plan.OwnerId != auth.User.Id && !auth.HasPermission("update_any_plan") {
- log.Println("User does not have permission to update plan")
- http.Error(w, "User does not have permission to update plan", http.StatusForbidden)
- return
- }
-
- body, err := io.ReadAll(r.Body)
- if err != nil {
- log.Printf("Error reading request body: %v\n", err)
- http.Error(w, "Error reading request body", http.StatusInternalServerError)
- return
- }
- defer func() {
- log.Println("Closing request body")
- r.Body.Close()
- }()
-
- var requestBody shared.TellPlanRequest
- if err := json.Unmarshal(body, &requestBody); err != nil {
- log.Printf("Error parsing request body: %v\n", err)
- http.Error(w, "Error parsing request body", http.StatusBadRequest)
- 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.TotalMessages >= TrialMaxMessages {
- writeApiError(w, shared.ApiError{
- Type: shared.ApiErrorTypeTrialMessagesExceeded,
- Status: http.StatusForbidden,
- Msg: "Free trial message limit exceeded",
- TrialMessagesExceededError: &shared.TrialMessagesExceededError{
- MaxMessages: TrialMaxMessages,
- },
- })
- return
- }
- }
- }
-
- err = model.Tell(plan, auth, &requestBody)
-
- if err != nil {
- log.Printf("Error telling plan: %v\n", err)
- http.Error(w, "Error telling plan", http.StatusInternalServerError)
- return
- }
-
- if requestBody.ConnectStream {
- active := model.Active.Get(planId)
- subscriptionId, ch := model.SubscribePlan(planId)
-
- startResponseStream(w, ch, active.Ctx, func() {
- model.UnsubscribePlan(planId, subscriptionId)
- })
- }
-
-}
-
-func BuildPlanHandler(w http.ResponseWriter, r *http.Request) {
- log.Println("Received request for BuildPlanHandler")
- auth := authenticate(w, r, true)
- if auth == nil {
- return
- }
-
- vars := mux.Vars(r)
- planId := vars["planId"]
-
- log.Println("planId: ", planId)
-
- if authorizePlan(w, planId, auth) == nil {
- return
- }
-
-}
-
-func ConnectPlanHandler(w http.ResponseWriter, r *http.Request) {
- log.Println("Received request for ConnectPlanHandler")
- auth := authenticate(w, r, true)
- if auth == nil {
- return
- }
-
- vars := mux.Vars(r)
- planId := vars["planId"]
-
- log.Println("planId: ", planId)
-
- if authorizePlan(w, planId, auth) == nil {
- return
- }
-
-}
-
-func StopPlanHandler(w http.ResponseWriter, r *http.Request) {
- log.Println("Received request for StopPlanHandler")
- auth := authenticate(w, r, true)
- if auth == nil {
- return
- }
-
- vars := mux.Vars(r)
- planId := vars["planId"]
-
- log.Println("planId: ", planId)
-
- if authorizePlan(w, planId, auth) == nil {
- return
- }
-
-}
diff --git a/server/handlers/plans_versions.go b/server/handlers/plans_versions.go
deleted file mode 100644
index 653a03bf..00000000
--- a/server/handlers/plans_versions.go
+++ /dev/null
@@ -1,130 +0,0 @@
-package handlers
-
-import (
- "encoding/json"
- "io"
- "log"
- "net/http"
- "plandex-server/db"
-
- "github.com/gorilla/mux"
- "github.com/plandex/plandex/shared"
-)
-
-func ListLogsHandler(w http.ResponseWriter, r *http.Request) {
- log.Println("Received request for ListLogsHandler")
-
- auth := authenticate(w, r, true)
- if auth == nil {
- return
- }
-
- vars := mux.Vars(r)
- planId := vars["planId"]
-
- log.Println("planId: ", planId)
-
- if authorizePlan(w, planId, auth) == nil {
- return
- }
-
- body, shas, err := db.GetGitCommitHistory(auth.OrgId, planId)
-
- if err != nil {
- log.Println("Error getting logs: ", err)
- w.WriteHeader(http.StatusInternalServerError)
- return
- }
-
- res := shared.LogResponse{
- Body: body,
- Shas: shas,
- }
-
- bytes, err := json.Marshal(res)
-
- if err != nil {
- log.Println("Error marshalling logs: ", err)
- w.WriteHeader(http.StatusInternalServerError)
- return
- }
-
- w.Write(bytes)
-
- log.Println("Successfully processed request for ListLogsHandler")
-}
-
-func RewindPlanHandler(w http.ResponseWriter, r *http.Request) {
- log.Println("Received request for RewindPlanHandler")
-
- auth := authenticate(w, r, true)
- if auth == nil {
- return
- }
-
- vars := mux.Vars(r)
- planId := vars["planId"]
-
- log.Println("planId: ", planId)
-
- if authorizePlan(w, planId, auth) == nil {
- return
- }
-
- // read the request body
- body, err := io.ReadAll(r.Body)
- if err != nil {
- log.Printf("Error reading request body: %v\n", err)
- http.Error(w, "Error reading request body", http.StatusInternalServerError)
- return
- }
- defer r.Body.Close()
-
- var requestBody shared.RewindPlanRequest
- if err := json.Unmarshal(body, &requestBody); err != nil {
- log.Printf("Error parsing request body: %v\n", err)
- http.Error(w, "Error parsing request body", http.StatusBadRequest)
- return
- }
-
- err = db.GitRewindToSha(auth.OrgId, planId, requestBody.Sha)
-
- if err != nil {
- log.Println("Error rewinding plan: ", err)
- w.WriteHeader(http.StatusInternalServerError)
- return
- }
-
- err = db.SyncPlanTokens(auth.OrgId, planId)
-
- if err != nil {
- log.Println("Error syncing plan tokens: ", err)
- w.WriteHeader(http.StatusInternalServerError)
- return
- }
-
- sha, latest, err := db.GetLatestCommit(auth.OrgId, planId)
-
- if err != nil {
- log.Println("Error getting latest commit: ", err)
- w.WriteHeader(http.StatusInternalServerError)
- return
- }
-
- res := shared.RewindPlanResponse{
- LatestSha: sha,
- LatestCommit: latest,
- }
-
- bytes, err := json.Marshal(res)
-
- if err != nil {
- log.Println("Error marshalling response: ", err)
- w.WriteHeader(http.StatusInternalServerError)
- return
- }
-
- w.Write(bytes)
-
- log.Println("Successfully processed request for RewindPlanHandler")
-}
diff --git a/server/handlers/projects.go b/server/handlers/projects.go
deleted file mode 100644
index 146ef823..00000000
--- a/server/handlers/projects.go
+++ /dev/null
@@ -1,254 +0,0 @@
-package handlers
-
-import (
- "encoding/json"
- "io"
- "log"
- "net/http"
- "plandex-server/db"
-
- "github.com/gorilla/mux"
- "github.com/plandex/plandex/shared"
-)
-
-func CreateProjectHandler(w http.ResponseWriter, r *http.Request) {
- log.Println("Received request for CreateProjectHandler")
-
- auth := authenticate(w, r, true)
- if auth == nil {
- return
- }
-
- // read the request body
- body, err := io.ReadAll(r.Body)
- if err != nil {
- log.Printf("Error reading request body: %v\n", err)
- http.Error(w, "Error reading request body", http.StatusInternalServerError)
- return
- }
- defer r.Body.Close()
-
- var requestBody shared.CreateProjectRequest
- if err := json.Unmarshal(body, &requestBody); err != nil {
- log.Printf("Error parsing request body: %v\n", err)
- http.Error(w, "Error parsing request body", http.StatusBadRequest)
- return
- }
-
- if requestBody.Name == "" {
- log.Println("Received empty name field")
- http.Error(w, "name field is required", http.StatusBadRequest)
- return
- }
-
- // 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")
- }
- }
- }()
-
- var projectId string
- err = tx.QueryRow("INSERT INTO projects (org_id, name) VALUES ($1, $2) RETURNING id", auth.OrgId, requestBody.Name).Scan(&projectId)
-
- if err != nil {
- log.Printf("Error creating project: %v\n", err)
- http.Error(w, "Error creating project: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- _, err = tx.Exec("INSERT INTO users_projects (user_id, org_id, project_id) VALUES ($1, $2, $3)", auth.User.Id, auth.OrgId, projectId)
-
- if err != nil {
- log.Printf("Error adding owner to project: %v\n", err)
- http.Error(w, "Error adding owner to project: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- 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.CreateProjectResponse{
- Id: projectId,
- }
-
- 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
- }
-
- w.Write(bytes)
-
- log.Println("Successfully created project", projectId)
-}
-
-func ListProjectsHandler(w http.ResponseWriter, r *http.Request) {
- log.Println("Received request for ListProjectsHandler")
-
- auth := authenticate(w, r, true)
- if auth == nil {
- return
- }
-
- rows, err := db.Conn.Query("SELECT project.id, project.name FROM users_projects INNER JOIN project ON users_projects.project_id = project.id WHERE users_projects.user_id = $1 AND users_projects.org_id = $2", auth)
-
- if err != nil {
- log.Printf("Error listing projects: %v\n", err)
- http.Error(w, "Error listing projects: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- var projects []shared.Project
-
- for rows.Next() {
- var project shared.Project
- err := rows.Scan(&project.Id, &project.Name)
- if err != nil {
- log.Printf("Error scanning project: %v\n", err)
- http.Error(w, "Error scanning project: "+err.Error(), http.StatusInternalServerError)
- return
- }
- projects = append(projects, project)
- }
-
- bytes, err := json.Marshal(projects)
- if err != nil {
- log.Printf("Error marshalling projects: %v\n", err)
- http.Error(w, "Error marshalling projects: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- w.Write(bytes)
-}
-
-func ProjectSetPlanHandler(w http.ResponseWriter, r *http.Request) {
- log.Println("Received request for UpdateProjectSetPlanHandler")
- auth := authenticate(w, r, true)
- if auth == nil {
- return
- }
-
- vars := mux.Vars(r)
- projectId := vars["projectId"]
-
- log.Println("projectId: ", projectId)
-
- if !authorizeProject(w, projectId, auth) {
- return
- }
-
- // read the request body
- body, err := io.ReadAll(r.Body)
- if err != nil {
- log.Printf("Error reading request body: %v\n", err)
- http.Error(w, "Error reading request body", http.StatusInternalServerError)
- return
- }
- defer r.Body.Close()
-
- var requestBody shared.SetProjectPlanRequest
- if err := json.Unmarshal(body, &requestBody); err != nil {
- log.Printf("Error parsing request body: %v\n", err)
- http.Error(w, "Error parsing request body", http.StatusBadRequest)
- return
- }
-
- if requestBody.PlanId == "" {
- log.Println("Received empty planId field")
- http.Error(w, "planId field is required", http.StatusBadRequest)
- return
- }
-
- // update statement here -- need auth / current user id
-
- if err != nil {
- log.Printf("Error updating project: %v\n", err)
- http.Error(w, "Error updating project: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- log.Println("Successfully set project plan", projectId)
-}
-
-func RenameProjectHandler(w http.ResponseWriter, r *http.Request) {
- log.Println("Received request for RenameProjectHandler")
- auth := authenticate(w, r, true)
- if auth == nil {
- return
- }
-
- vars := mux.Vars(r)
- projectId := vars["projectId"]
-
- log.Println("projectId: ", projectId)
-
- if !authorizeProjectRename(w, projectId, auth) {
- return
- }
-
- // read the request body
- body, err := io.ReadAll(r.Body)
- if err != nil {
- log.Printf("Error reading request body: %v\n", err)
- http.Error(w, "Error reading request body", http.StatusInternalServerError)
- return
- }
- defer r.Body.Close()
-
- var requestBody shared.RenameProjectRequest
- if err := json.Unmarshal(body, &requestBody); err != nil {
- log.Printf("Error parsing request body: %v\n", err)
- http.Error(w, "Error parsing request body", http.StatusBadRequest)
- return
- }
-
- if requestBody.Name == "" {
- log.Println("Received empty name field")
- http.Error(w, "name field is required", http.StatusBadRequest)
- return
- }
-
- res, err := db.Conn.Exec("UPDATE projects SET name = $1 WHERE id = $2", requestBody.Name, projectId)
-
- if err != nil {
- log.Printf("Error updating project: %v\n", err)
- http.Error(w, "Error updating project: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- rowsAffected, err := res.RowsAffected()
-
- if err != nil {
- log.Printf("Error getting rows affected: %v\n", err)
- http.Error(w, "Error getting rows affected: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- if rowsAffected == 0 {
- log.Printf("Project not found: %v\n", projectId)
- http.Error(w, "Project not found: "+projectId, http.StatusNotFound)
- return
- }
-
- log.Println("Successfully renamed project", projectId)
-
-}
diff --git a/server/handlers/sessions.go b/server/handlers/sessions.go
deleted file mode 100644
index 737f3f6b..00000000
--- a/server/handlers/sessions.go
+++ /dev/null
@@ -1,228 +0,0 @@
-package handlers
-
-import (
- "crypto/sha256"
- "encoding/hex"
- "encoding/json"
- "io"
- "log"
- "net/http"
- "plandex-server/db"
- "plandex-server/email"
- "strings"
-
- "github.com/plandex/plandex/shared"
-)
-
-func CreateEmailVerificationHandler(w http.ResponseWriter, r *http.Request) {
- log.Println("Received request for CreateEmailVerificationHandler")
-
- // read the request body
- body, err := io.ReadAll(r.Body)
- if err != nil {
- log.Printf("Error reading request body: %v\n", err)
- http.Error(w, "Error reading request body: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- var req shared.CreateEmailVerificationRequest
- err = json.Unmarshal(body, &req)
- if err != nil {
- log.Printf("Error unmarshalling request: %v\n", err)
- http.Error(w, "Error unmarshalling request: "+err.Error(), http.StatusInternalServerError)
- return
- }
- req.Email = strings.ToLower(req.Email)
-
- // create pin - 6 alphanumeric characters
- pinBytes, err := shared.GetRandomAlphanumeric(6)
- if err != nil {
- log.Printf("Error generating random pin: %v\n", err)
- http.Error(w, "Error generating random pin: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- // get sha256 hash of pin
- hashBytes := sha256.Sum256(pinBytes)
- pinHash := hex.EncodeToString(hashBytes[:])
-
- // create verification
- err = db.CreateEmailVerification(req.Email, pinHash, req.UserId)
-
- if err != nil {
- log.Printf("Error creating email verification: %v\n", err)
- http.Error(w, "Error creating email verification: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- err = email.SendVerificationEmail(req.Email, string(pinBytes))
-
- if err != nil {
- log.Printf("Error sending verification email: %v\n", err)
- http.Error(w, "Error sending verification email: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- res := shared.CreateEmailVerificationResponse{
- HasAccount: true,
- }
-
- bytes, err := json.Marshal(res)
-
- 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 email verification")
-
- w.Write(bytes)
-}
-
-func SignInHandler(w http.ResponseWriter, r *http.Request) {
- log.Println("Received request for SignInHandler")
-
- // read the request body
- body, err := io.ReadAll(r.Body)
- if err != nil {
- log.Printf("Error reading request body: %v\n", err)
- http.Error(w, "Error reading request body: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- var req shared.SignInRequest
- err = json.Unmarshal(body, &req)
- if err != nil {
- log.Printf("Error unmarshalling request: %v\n", err)
- http.Error(w, "Error unmarshalling request: "+err.Error(), http.StatusInternalServerError)
- return
- }
- req.Email = strings.ToLower(req.Email)
-
- user, err := db.GetUserByEmail(req.Email)
-
- if err != nil {
- log.Printf("Error getting user: %v\n", err)
- http.Error(w, "Error getting user: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- if user == nil {
- log.Printf("User not found for email: %v\n", req.Email)
- http.Error(w, "Not found", http.StatusNotFound)
- return
- }
-
- if user != nil && user.IsTrial {
- log.Printf("Trial user can't sign in: %v\n", req.Email)
- http.Error(w, "Trial user can't sign in", http.StatusForbidden)
- 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
- }
-
- // 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")
- }
- }
- }()
-
- // create auth token
- token, authTokenId, err := db.CreateAuthToken(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", 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
- }
-
- // 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
- }
-
- // 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: user.Id,
- Token: token,
- Email: user.Email,
- UserName: user.Name,
- 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 signed in")
-
- w.Write(bytes)
-}
-
-func SignOutHandler(w http.ResponseWriter, r *http.Request) {
- log.Println("Received request for SignOutHandler")
-
- auth := authenticate(w, r, false)
- if auth == nil {
- return
- }
-
- _, 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
- }
-
- log.Println("Successfully signed out")
-}
diff --git a/server/handlers/stream_helper.go b/server/handlers/stream_helper.go
deleted file mode 100644
index 1105abfe..00000000
--- a/server/handlers/stream_helper.go
+++ /dev/null
@@ -1,42 +0,0 @@
-package handlers
-
-import (
- "context"
- "log"
- "net/http"
-
- "github.com/plandex/plandex/shared"
-)
-
-func startResponseStream(w http.ResponseWriter, ch chan string, ctx context.Context, closeFn func()) {
- log.Println("Response stream manager: starting plan stream")
-
- w.Header().Set("Transfer-Encoding", "chunked")
- w.Header().Set("Content-Type", "text/plain; charset=utf-8")
-
- defer func() {
- log.Println("Response stream manager: plan stream done")
- closeFn()
- }()
-
- for {
- select {
- case <-ctx.Done():
- log.Println("Response stream manager: context done")
- return
- case msg := <-ch:
- // log.Println("Response stream manager: sending message:", msg)
-
- bytes := []byte(msg + shared.STREAM_MESSAGE_SEPARATOR)
- _, err := w.Write(bytes)
- if err != nil {
- log.Printf("Response stream mananger: error writing to client: %v\n", err)
- return
- }
- if flusher, ok := w.(http.Flusher); ok {
- flusher.Flush()
- }
- }
- }
-
-}
diff --git a/server/handlers/users.go b/server/handlers/users.go
deleted file mode 100644
index f8205367..00000000
--- a/server/handlers/users.go
+++ /dev/null
@@ -1,144 +0,0 @@
-package handlers
-
-import (
- "encoding/json"
- "log"
- "net/http"
- "plandex-server/db"
- "strings"
-
- "github.com/gorilla/mux"
- "github.com/plandex/plandex/shared"
-)
-
-func ListUsersHandler(w http.ResponseWriter, r *http.Request) {
- log.Println("Received a request for ListUsersHandler")
- auth := authenticate(w, r, true)
- if auth == nil {
- return
- }
-
- if auth.User.IsTrial {
- writeApiError(w, shared.ApiError{
- Type: shared.ApiErrorTypeTrialActionNotAllowed,
- Status: http.StatusForbidden,
- Msg: "Free trial user can't list users",
- })
- return
- }
-
- users, err := db.ListUsers(auth.OrgId)
- if err != nil {
- log.Println("Error listing users: ", err)
- http.Error(w, "Error listing users: "+err.Error(), http.StatusInternalServerError)
- }
-
- bytes, err := json.Marshal(users)
-
- if err != nil {
- log.Println("Error marshalling users: ", err)
- http.Error(w, "Error marshalling users: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- log.Println("Successfully processed request for ListUsersHandler")
-
- w.Write(bytes)
-}
-
-func DeleteOrgUserHandler(w http.ResponseWriter, r *http.Request) {
- log.Println("Received a request for DeleteOrgUserHandler")
- auth := authenticate(w, r, true)
- if auth == nil {
- return
- }
-
- if auth.User.IsTrial {
- writeApiError(w, shared.ApiError{
- Type: shared.ApiErrorTypeTrialActionNotAllowed,
- Status: http.StatusForbidden,
- Msg: "Free trial user can't delete users",
- })
- return
- }
-
- vars := mux.Vars(r)
- userId := vars["userId"]
-
- user, err := db.GetUser(userId)
-
- if err != nil {
- log.Printf("Error getting user: %v\n", err)
- http.Error(w, "Error getting user: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- // ensure current user can invite target user
- if !auth.HasPermission(strings.Join([]string{"remove_user", user.OrgRoleId}, "|")) {
- log.Printf("User does not have permission to invite user with role: %v\n", user.OrgRoleId)
- http.Error(w, "User does not have permission to invite user with role: "+user.OrgRoleId, http.StatusForbidden)
- return
- }
-
- // verify user is org member
- isMember, err := db.ValidateOrgMembership(userId, auth.OrgId)
-
- if err != nil {
- log.Printf("Error validating org membership: %v\n", err)
- http.Error(w, "Error validating org membership: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- if !isMember {
- log.Printf("User %s is not a member of org %s\n", userId, auth.OrgId)
- http.Error(w, "User "+userId+" is not a member of org "+auth.OrgId, http.StatusForbidden)
- return
- }
-
- // 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")
- }
- }
- }()
-
- err = db.DeleteOrgUser(userId, auth.OrgId, tx)
-
- if err != nil {
- log.Println("Error deleting org user: ", err)
- http.Error(w, "Error deleting org user: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- invite, err := db.GetInviteForOrgUser(auth.OrgId, userId)
-
- if err != nil {
- log.Println("Error getting invite for org user: ", err)
- http.Error(w, "Error getting invite for org user: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- if invite != nil {
- err = db.DeleteInvite(invite.Id, tx)
-
- if err != nil {
- log.Println("Error deleting invite: ", err)
- http.Error(w, "Error deleting invite: "+err.Error(), http.StatusInternalServerError)
- return
- }
- }
-
- log.Println("Successfully processed request for DeleteOrgUserHandler")
-}
diff --git a/server/main.go b/server/main.go
deleted file mode 100644
index 45bf897a..00000000
--- a/server/main.go
+++ /dev/null
@@ -1,40 +0,0 @@
-package main
-
-import (
- "fmt"
- "log"
- "net/http"
- "os"
- "plandex-server/db"
-
- openai "github.com/sashabaranov/go-openai"
-)
-
-var client *openai.Client
-
-func main() {
- if os.Getenv("OPENAI_API_KEY") == "" {
- log.Fatal("OPENAI_API_KEY environment variable is not set")
- }
-
- err := db.Connect()
- if err != nil {
- log.Fatal("Error initializing database: ", err)
- }
-
- err = db.MigrationsUp()
- if err != nil {
- log.Fatal("Error running migrations: ", err)
- }
-
- routes := InitRoutes()
-
- // Get port from the environment variable or default to 8088
- port := os.Getenv("PORT")
- if port == "" {
- port = "8088"
- }
-
- log.Printf("Plandex server is running on :%s", port)
- log.Fatal(http.ListenAndServe(fmt.Sprintf(":%s", port), routes))
-}
diff --git a/server/migrations/2023120500_init.down.sql b/server/migrations/2023120500_init.down.sql
deleted file mode 100644
index 2d23a548..00000000
--- a/server/migrations/2023120500_init.down.sql
+++ /dev/null
@@ -1,14 +0,0 @@
-DROP TABLE IF EXISTS convo_summaries;
-DROP TABLE IF EXISTS plan_builds;
-
-DROP TABLE IF EXISTS users_projects;
-DROP TABLE IF EXISTS plans;
-DROP TABLE IF EXISTS projects;
-DROP TABLE IF EXISTS orgs_users;
-
-DROP TABLE IF EXISTS email_verifications;
-DROP TABLE IF EXISTS auth_tokens;
-DROP TABLE IF EXISTS invites;
-
-DROP TABLE IF EXISTS orgs;
-DROP TABLE IF EXISTS users;
diff --git a/server/migrations/2023120500_init.up.sql b/server/migrations/2023120500_init.up.sql
deleted file mode 100644
index b89aa949..00000000
--- a/server/migrations/2023120500_init.up.sql
+++ /dev/null
@@ -1,158 +0,0 @@
-CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
-
-CREATE OR REPLACE FUNCTION update_updated_at_column()
-RETURNS TRIGGER AS $$
-BEGIN
- NEW.updated_at = NOW();
- RETURN NEW;
-END;
-$$ LANGUAGE plpgsql;
-
-CREATE TABLE IF NOT EXISTS users (
- id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
- name VARCHAR(255) NOT NULL,
- email VARCHAR(255) NOT NULL,
- domain VARCHAR(255) NOT NULL,
- is_trial BOOLEAN NOT NULL,
- num_non_draft_plans INTEGER NOT NULL DEFAULT 0,
- created_at TIMESTAMP NOT NULL DEFAULT NOW(),
- updated_at TIMESTAMP NOT NULL DEFAULT NOW()
-);
-CREATE TRIGGER update_users_modtime BEFORE UPDATE ON users FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
-
-ALTER TABLE users ADD UNIQUE (email);
-CREATE INDEX users_domain_idx ON users(domain);
-
-CREATE TABLE IF NOT EXISTS orgs (
- id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
- name VARCHAR(255) NOT NULL,
- domain VARCHAR(255),
- auto_add_domain_users BOOLEAN NOT NULL DEFAULT FALSE,
- owner_id UUID NOT NULL REFERENCES users(id),
- is_trial BOOLEAN NOT NULL,
- created_at TIMESTAMP NOT NULL DEFAULT NOW(),
- updated_at TIMESTAMP NOT NULL DEFAULT NOW()
-);
-CREATE TRIGGER update_orgs_modtime BEFORE UPDATE ON orgs FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
-
-ALTER TABLE orgs ADD UNIQUE (domain);
-
-CREATE TABLE IF NOT EXISTS orgs_users (
- id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
- org_id UUID NOT NULL REFERENCES orgs(id) ON DELETE CASCADE,
- user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
- created_at TIMESTAMP NOT NULL DEFAULT NOW(),
- updated_at TIMESTAMP NOT NULL DEFAULT NOW()
-);
-CREATE TRIGGER update_orgs_users_modtime BEFORE UPDATE ON orgs_users FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
-
-CREATE INDEX orgs_users_user_idx ON orgs_users(user_id);
-CREATE INDEX orgs_users_org_idx ON orgs_users(org_id);
-
-CREATE TABLE IF NOT EXISTS invites (
- id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
- org_id UUID NOT NULL REFERENCES orgs(id) ON DELETE CASCADE,
- name VARCHAR(255) NOT NULL,
- email VARCHAR(255) NOT NULL,
- inviter_id UUID NOT NULL REFERENCES users(id),
- invitee_id UUID REFERENCES users(id),
- accepted_at TIMESTAMP,
- created_at TIMESTAMP NOT NULL DEFAULT NOW(),
- updated_at TIMESTAMP NOT NULL DEFAULT NOW()
-);
-CREATE TRIGGER update_invites_modtime BEFORE UPDATE ON invites FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
-
-CREATE INDEX invites_pending_idx ON invites(org_id, (accepted_at IS NULL));
-CREATE INDEX invites_email_idx ON invites(email, (accepted_at IS NULL));
-CREATE INDEX invites_org_user_idx ON invites(org_id, invitee_id);
-
-CREATE TABLE IF NOT EXISTS auth_tokens (
- id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
- user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
- token_hash VARCHAR(64) NOT NULL,
- is_trial BOOLEAN NOT NULL DEFAULT FALSE,
- created_at TIMESTAMP NOT NULL DEFAULT NOW(),
- deleted_at TIMESTAMP
-);
-CREATE UNIQUE INDEX auth_tokens_idx ON auth_tokens(token_hash);
-
-CREATE TABLE IF NOT EXISTS email_verifications (
- id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
- email VARCHAR(255) NOT NULL,
- pin_hash VARCHAR(64) NOT NULL,
- user_id UUID REFERENCES users(id),
- auth_token_id UUID REFERENCES auth_tokens(id),
- created_at TIMESTAMP NOT NULL DEFAULT NOW(),
- updated_at TIMESTAMP NOT NULL DEFAULT NOW()
-);
-CREATE TRIGGER update_email_verifications_modtime BEFORE UPDATE ON email_verifications FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
-
-CREATE UNIQUE INDEX email_verifications_idx ON email_verifications(pin_hash, email, created_at DESC);
-
-CREATE TABLE IF NOT EXISTS projects (
- id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
- org_id UUID NOT NULL REFERENCES orgs(id) ON DELETE CASCADE,
- name VARCHAR(255) NOT NULL,
- created_at TIMESTAMP NOT NULL DEFAULT NOW(),
- updated_at TIMESTAMP NOT NULL DEFAULT NOW()
-);
-CREATE TRIGGER update_projects_modtime BEFORE UPDATE ON projects FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
-
-CREATE TABLE IF NOT EXISTS plans (
- id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
- org_id UUID NOT NULL REFERENCES orgs(id) ON DELETE CASCADE,
- owner_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
- project_id UUID NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
- name VARCHAR(255) NOT NULL,
- status VARCHAR(32) NOT NULL,
- error TEXT,
- context_tokens INTEGER NOT NULL DEFAULT 0,
- convo_tokens INTEGER NOT NULL DEFAULT 0,
- shared_with_org_at TIMESTAMP,
- total_messages INTEGER NOT NULL DEFAULT 0,
- archived_at TIMESTAMP,
- created_at TIMESTAMP NOT NULL DEFAULT NOW(),
- updated_at TIMESTAMP NOT NULL DEFAULT NOW()
-);
-CREATE TRIGGER update_plans_modtime BEFORE UPDATE ON plans FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
-
-CREATE INDEX plans_name_idx ON plans(project_id, owner_id, name);
-CREATE INDEX plans_archived_idx ON plans(project_id, owner_id, archived_at);
-
-CREATE TABLE IF NOT EXISTS users_projects (
- id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
- org_id UUID NOT NULL REFERENCES orgs(id) ON DELETE CASCADE,
- user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
- project_id UUID NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
- last_active_plan_id UUID REFERENCES plans(id),
- created_at TIMESTAMP NOT NULL DEFAULT NOW(),
- updated_at TIMESTAMP NOT NULL DEFAULT NOW()
-);
-CREATE TRIGGER update_users_projects_modtime BEFORE UPDATE ON users_projects FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
-
-CREATE INDEX users_projects_idx ON users_projects(user_id, org_id, project_id);
-
-CREATE TABLE IF NOT EXISTS convo_summaries (
- id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
- org_id UUID NOT NULL REFERENCES orgs(id) ON DELETE CASCADE,
- plan_id UUID NOT NULL REFERENCES plans(id) ON DELETE CASCADE,
- latest_convo_message_id UUID NOT NULL,
- latest_convo_message_created_at TIMESTAMP NOT NULL,
- summary TEXT NOT NULL,
- tokens INTEGER NOT NULL,
- num_messages INTEGER NOT NULL,
- created_at TIMESTAMP NOT NULL DEFAULT NOW()
-);
-
-CREATE TABLE IF NOT EXISTS plan_builds (
- id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
- org_id UUID NOT NULL REFERENCES orgs(id) ON DELETE CASCADE,
- plan_id UUID NOT NULL REFERENCES plans(id) ON DELETE CASCADE,
- convo_message_id UUID NOT NULL,
- error TEXT,
- error_path TEXT,
- finished_at TIMESTAMP,
- created_at TIMESTAMP NOT NULL DEFAULT NOW(),
- updated_at TIMESTAMP NOT NULL DEFAULT NOW()
-);
-CREATE TRIGGER update_plan_builds_modtime BEFORE UPDATE ON plan_builds FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
\ No newline at end of file
diff --git a/server/migrations/2024011700_rbac.down.sql b/server/migrations/2024011700_rbac.down.sql
deleted file mode 100644
index 4bcf2173..00000000
--- a/server/migrations/2024011700_rbac.down.sql
+++ /dev/null
@@ -1,8 +0,0 @@
-ALTER TABLE orgs_users DROP COLUMN org_role_id;
-ALTER TABLE invites DROP COLUMN org_role_id;
-
-DROP TABLE IF EXISTS org_roles_permissions;
-DROP TABLE IF EXISTS permissions;
-DROP TABLE IF EXISTS org_roles;
-
-
diff --git a/server/migrations/2024011700_rbac.up.sql b/server/migrations/2024011700_rbac.up.sql
deleted file mode 100644
index a51f7a62..00000000
--- a/server/migrations/2024011700_rbac.up.sql
+++ /dev/null
@@ -1,133 +0,0 @@
-
-CREATE TABLE IF NOT EXISTS org_roles (
- id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
- org_id UUID REFERENCES orgs(id) ON DELETE CASCADE,
- name VARCHAR(255) NOT NULL,
- label VARCHAR(255) NOT NULL,
- description TEXT NOT NULL,
- created_at TIMESTAMP NOT NULL DEFAULT NOW(),
- updated_at TIMESTAMP NOT NULL DEFAULT NOW()
-);
-CREATE TRIGGER update_org_roles_modtime BEFORE UPDATE ON org_roles FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
-
-CREATE UNIQUE INDEX org_roles_org_idx ON org_roles(org_id, name);
-
-ALTER TABLE orgs_users ADD COLUMN org_role_id UUID NOT NULL REFERENCES org_roles(id) ON DELETE RESTRICT;
-CREATE INDEX orgs_users_org_role_idx ON orgs_users(org_id, org_role_id);
-
-ALTER TABLE invites ADD COLUMN org_role_id UUID NOT NULL REFERENCES org_roles(id) ON DELETE RESTRICT;
-CREATE INDEX invites_org_role_idx ON invites(org_id, org_role_id);
-
-CREATE TABLE IF NOT EXISTS permissions (
- id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
- name VARCHAR(255) NOT NULL,
- description TEXT NOT NULL,
- resource_id UUID,
- created_at TIMESTAMP NOT NULL DEFAULT NOW()
-);
-
-CREATE TABLE IF NOT EXISTS org_roles_permissions (
- id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
- org_role_id UUID NOT NULL REFERENCES org_roles(id) ON DELETE CASCADE,
- permission_id UUID NOT NULL REFERENCES permissions(id) ON DELETE CASCADE,
- created_at TIMESTAMP NOT NULL DEFAULT NOW()
-);
-
-INSERT INTO org_roles (name, label, description) VALUES
- ('owner', 'Owner', 'Can read and update any plan, invite other owners/admins/members, manage email domain auth, manage billing, read audit logs, delete the org'),
- ('billing_admin', 'Billing Admin', 'Can manage billing'),
- ('admin', 'Admin', 'Can read and update any plan, invite other admins/members'),
- ('member', 'Member', 'Can read and update their own plans or plans shared with them');
-
-DO $$
-DECLARE
- owner_org_role_id UUID;
- billing_admin_org_role_id UUID;
- admin_org_role_id UUID;
- member_org_role_id UUID;
-BEGIN
- SELECT id INTO owner_org_role_id FROM org_roles WHERE org_id IS NULL AND name = 'owner';
- SELECT id INTO billing_admin_org_role_id FROM org_roles WHERE org_id IS NULL AND name = 'billing_admin';
- SELECT id INTO admin_org_role_id FROM org_roles WHERE org_id IS NULL AND name = 'admin';
- SELECT id INTO member_org_role_id FROM org_roles WHERE org_id IS NULL AND name = 'member';
-
- INSERT INTO permissions (name, description, resource_id) VALUES
- ('delete_org', 'Delete an org', NULL),
- ('manage_email_domain_auth', 'Configure whether orgs_users from the org''s email domain are auto-admitted to org', NULL),
- ('manage_billing', 'Manage an org''s billing', NULL),
-
- ('invite_user', 'Invite owners to an org', owner_org_role_id),
- ('invite_user', 'Invite admins to an org', admin_org_role_id),
- ('invite_user', 'Invite billing admins to an org', billing_admin_org_role_id),
- ('invite_user', 'Invite members to an org', member_org_role_id),
-
- ('remove_user', 'Remove owners from an org', owner_org_role_id),
- ('remove_user', 'Remove admins from an org', admin_org_role_id),
- ('remove_user', 'Remove billing admins from an org', billing_admin_org_role_id),
- ('remove_user', 'Remove members from an org', member_org_role_id),
-
- ('set_user_role', 'Update an owner''s role in an org', owner_org_role_id),
- ('set_user_role', 'Update an admin''s role in an org', admin_org_role_id),
- ('set_user_role', 'Update a billing admin''s role in an org', billing_admin_org_role_id),
- ('set_user_role', 'Update a member''s role in an org', member_org_role_id),
-
- ('list_org_roles', 'List org roles', NULL),
-
- ('create_project', 'Create a project', NULL),
- ('rename_any_project', 'Rename a project', NULL),
- ('delete_any_project', 'Delete a project', NULL),
-
- ('create_plan', 'Create a plan', NULL),
-
- ('manage_any_plan_shares', 'Unshare a plan any user shared', NULL),
- ('rename_any_plan', 'Rename a plan', NULL),
- ('delete_any_plan', 'Delete a plan', NULL),
- ('update_any_plan', 'Update a plan', NULL),
- ('archive_any_plan', 'Archive a plan', NULL);
-END $$;
-
--- Insert all permissions for the 'org owner' role
-INSERT INTO org_roles_permissions (org_role_id, permission_id)
-SELECT
- (SELECT id FROM org_roles WHERE name = 'owner') AS org_role_id,
- p.id AS permission_id
-FROM
- permissions p;
-
--- Insert all permissions except specific ones and those exclusive to 'owner' or 'billing admin' for the 'org admin' role
-INSERT INTO org_roles_permissions (org_role_id, permission_id)
-SELECT
- (SELECT id FROM org_roles WHERE name = 'admin') AS org_role_id,
- p.id AS permission_id
-FROM
- permissions p
-WHERE
- p.name NOT IN ('delete_org', 'manage_email_domain_auth', 'manage_billing')
- AND NOT EXISTS (
- SELECT 1 FROM permissions p2
- WHERE p2.resource_id IN (SELECT id FROM org_roles WHERE name IN ('owner', 'billing_admin'))
- AND p2.id = p.id
- );
-
-INSERT INTO org_roles_permissions (org_role_id, permission_id)
-SELECT
- (SELECT id FROM org_roles WHERE name = 'billing_admin') AS org_role_id,
- p.id AS permission_id
-FROM
- permissions p
-WHERE
- p.name IN (
- 'manage_billing'
- );
-
-INSERT INTO org_roles_permissions (org_role_id, permission_id)
-SELECT
- (SELECT id FROM org_roles WHERE name = 'member') AS org_role_id,
- p.id AS permission_id
-FROM
- permissions p
-WHERE
- p.name IN (
- 'create_project',
- 'create_plan'
- );
diff --git a/server/model/client.go b/server/model/client.go
deleted file mode 100644
index 340f20ce..00000000
--- a/server/model/client.go
+++ /dev/null
@@ -1,16 +0,0 @@
-package model
-
-import (
- "os"
- "time"
-
- "github.com/sashabaranov/go-openai"
-)
-
-const OPENAI_STREAM_CHUNK_TIMEOUT = time.Duration(30) * time.Second
-
-var Client *openai.Client
-
-func init() {
- Client = openai.NewClient(os.Getenv("OPENAI_API_KEY"))
-}
diff --git a/server/model/lib/context.go b/server/model/lib/context.go
deleted file mode 100644
index 933e068d..00000000
--- a/server/model/lib/context.go
+++ /dev/null
@@ -1,46 +0,0 @@
-package lib
-
-import (
- "fmt"
- "plandex-server/db"
- "strings"
-
- "github.com/plandex/plandex/shared"
-)
-
-func FormatModelContext(context []*db.Context) (string, int, error) {
- var contextMessages []string
- var numTokens int
- for _, part := range context {
- var message string
- var fmtStr string
- var args []any
-
- if part.ContextType == shared.ContextDirectoryTreeType {
- fmtStr = "\n\n- %s | directory tree:\n\n```\n%s\n```"
- args = append(args, part.FilePath, part.Body)
- } else if part.ContextType == shared.ContextFileType {
- fmtStr = "\n\n- %s:\n\n```\n%s\n```"
- args = append(args, part.FilePath, part.Body)
- } else if part.Url != "" {
- fmtStr = "\n\n- %s:\n\n```\n%s\n```"
- args = append(args, part.Url, part.Body)
- } else {
- fmtStr = "\n\n- content%s:\n\n```\n%s\n```"
- args = append(args, part.Name, part.Body)
- }
-
- numContextTokens, err := shared.GetNumTokens(fmt.Sprintf(fmtStr, ""))
- if err != nil {
- err = fmt.Errorf("failed to get the number of tokens in the context: %v", err)
- return "", 0, err
- }
-
- numTokens += part.NumTokens + numContextTokens
-
- message = fmt.Sprintf(fmtStr, args...)
-
- contextMessages = append(contextMessages, message)
- }
- return strings.Join(contextMessages, "\n"), numTokens, nil
-}
diff --git a/server/model/name.go b/server/model/name.go
deleted file mode 100644
index 5acc96ad..00000000
--- a/server/model/name.go
+++ /dev/null
@@ -1,67 +0,0 @@
-package model
-
-import (
- "context"
- "encoding/json"
- "fmt"
- "plandex-server/model/prompts"
-
- "github.com/sashabaranov/go-openai"
-)
-
-func GenPlanName(planContent string) (string, error) {
- messages := []openai.ChatCompletionMessage{
- {
- Role: openai.ChatMessageRoleSystem,
- Content: prompts.SysPlanName,
- },
- }
-
- messages = append(messages, openai.ChatCompletionMessage{
- Role: openai.ChatMessageRoleUser,
- Content: prompts.GetPlanNamePrompt(planContent),
- })
-
- resp, err := Client.CreateChatCompletion(
- context.Background(),
- openai.ChatCompletionRequest{
- Model: NameModel,
- Functions: []openai.FunctionDefinition{prompts.PlanNameFn},
- Messages: messages,
- ResponseFormat: &openai.ChatCompletionResponseFormat{Type: "json_object"},
- },
- )
-
- var res string
- var nameRes prompts.PlanNameRes
-
- if err != nil {
- fmt.Printf("Error during plan name model call: %v\n", err)
- return "", err
- }
-
- for _, choice := range resp.Choices {
- if choice.FinishReason == "function_call" &&
- choice.Message.FunctionCall != nil &&
- choice.Message.FunctionCall.Name == "namePlan" {
- fnCall := choice.Message.FunctionCall
- res = fnCall.Arguments
- }
- }
-
- if res == "" {
- fmt.Println("no namePlan function call found in response")
- return "", err
- }
-
- bytes := []byte(res)
-
- err = json.Unmarshal(bytes, &nameRes)
- if err != nil {
- fmt.Printf("Error unmarshalling plan description response: %v\n", err)
- return "", err
- }
-
- return nameRes.PlanName, nil
-
-}
diff --git a/server/model/openai_models.go b/server/model/openai_models.go
deleted file mode 100644
index ea9377ce..00000000
--- a/server/model/openai_models.go
+++ /dev/null
@@ -1,39 +0,0 @@
-package model
-
-import (
- "os"
-
- "github.com/sashabaranov/go-openai"
-)
-
-const strongModel = openai.GPT4 // gpt-4-turbo-preview has huge context and is faster, but seems much weaker than gpt-4
-const mediumModel = openai.GPT4TurboPreview
-const weakModel = openai.GPT3Dot5Turbo1106
-
-var PlannerModel = strongModel
-var PlanSummaryModel = mediumModel
-var BuilderModel = mediumModel
-var ShortSummaryModel = weakModel
-var NameModel = weakModel
-var CommitMsgModel = weakModel
-
-func init() {
- if os.Getenv("PLANNER_MODEL") != "" {
- PlannerModel = os.Getenv("PLANNER_MODEL")
- }
- if os.Getenv("PLAN_SUMMARY_MODEL") != "" {
- PlanSummaryModel = os.Getenv("PLAN_SUMMARY_MODEL")
- }
- if os.Getenv("BUILDER_MODEL") != "" {
- BuilderModel = os.Getenv("BUILDER_MODEL")
- }
- if os.Getenv("SHORT_SUMMARY_MODEL") != "" {
- ShortSummaryModel = os.Getenv("SHORT_SUMMARY_MODEL")
- }
- if os.Getenv("NAME_MODEL") != "" {
- NameModel = os.Getenv("NAME_MODEL")
- }
- if os.Getenv("COMMIT_MSG_MODEL") != "" {
- CommitMsgModel = os.Getenv("COMMIT_MSG_MODEL")
- }
-}
diff --git a/server/model/plan/build.go b/server/model/plan/build.go
deleted file mode 100644
index 262d5d19..00000000
--- a/server/model/plan/build.go
+++ /dev/null
@@ -1,556 +0,0 @@
-package plan
-
-import (
- "context"
- "encoding/json"
- "fmt"
- "log"
- "math"
- "plandex-server/db"
- "plandex-server/model"
- "plandex-server/model/prompts"
- "plandex-server/types"
- "sort"
- "strings"
- "time"
-
- "github.com/davecgh/go-spew/spew"
- "github.com/google/uuid"
- "github.com/plandex/plandex/shared"
- "github.com/sashabaranov/go-openai"
-)
-
-const MaxRetries = 3
-const MaxReplacementRetries = 1
-
-func Build(currentOrgId, planId string) *types.ActivePlan {
- log.Printf("Building plan: %s\n", planId)
-
- // goEnv := os.Getenv("GOENV")
- // if goEnv == "test" {
- // streamFilesLoremIpsum(onStream)
- // return nil
- // }
-
- active := Active.Get(planId)
-
- if active == nil {
- log.Printf("Active plan not found for plan %s\n", planId)
- // TODO: to allow for rebuilds or selective builds, construct the active plan here from the db
- } else {
- go execPlanBuild(currentOrgId, planId, active)
- }
-
- return active
-}
-
-func execPlanBuild(currentOrgId, planId string, active *types.ActivePlan) {
- for _, filePath := range active.Files {
- tokenCount := &shared.PlanTokenCount{
- Path: filePath,
- NumTokens: 0,
- Finished: false,
- }
- json, err := json.Marshal(tokenCount)
- if err != nil {
- log.Printf("Error marshalling plan token count: %v\n", err)
- active.StreamDoneCh <- err
- return
- }
- active.StreamCh <- string(json)
- }
-
- replyInfo := types.NewReplyInfo()
- replyInfo.AddToken(active.Content, true)
- _, fileContents, numTokensByFile, _ := replyInfo.FinishAndRead()
-
- errCh := make(chan error)
-
- var build *db.PlanBuild
- var currentPlan *shared.CurrentPlanState
-
- go func() {
- build = &db.PlanBuild{
- OrgId: currentOrgId,
- PlanId: planId,
- ConvoMessageId: active.AssistantMessageId,
- }
- err := db.StorePlanBuild(build)
-
- if err != nil {
- errCh <- fmt.Errorf("error storing plan build: %v", err)
- return
- }
-
- errCh <- nil
- }()
-
- go func() {
- err := db.SetPlanStatus(planId, shared.PlanStatusBuilding, "")
- if err != nil {
- errCh <- fmt.Errorf("error setting plan status to building: %v", err)
- return
- }
- errCh <- nil
- }()
-
- go func() {
- res, err := db.GetCurrentPlanState(db.CurrentPlanStateParams{
- OrgId: currentOrgId,
- PlanId: planId,
- Contexts: active.Contexts,
- })
- if err != nil {
- errCh <- fmt.Errorf("error getting current plan state: %v", err)
- return
- }
- currentPlan = res
- errCh <- nil
- }()
-
- for i := 0; i < 3; i++ {
- err := <-errCh
- if err != nil {
- log.Printf("Error building plan %s: %v\n", planId, err)
- active.StreamDoneCh <- err
- return
- }
- }
-
- onFinishBuild := func() {
- log.Println("Build finished.")
- active.StreamCh <- shared.STREAM_FINISHED
- active.StreamDoneCh <- nil
- }
-
- onFinishBuildFile := func(filePath string, planRes *db.PlanFileResult) {
- finished := false
-
- // log.Println("onFinishBuildFile: " + filePath)
- // spew.Dump(planRes)
-
- err := db.StorePlanResult(planRes)
- if err != nil {
- log.Printf("Error storing plan result: %v\n", err)
- active.StreamDoneCh <- err
- return
- }
-
- Active.Update(planId, func(ap *types.ActivePlan) {
- ap.BuiltFiles[filePath] = true
-
- if ap.BuildFinished() {
- finished = true
- }
- })
-
- log.Printf("Finished building file %s\n", filePath)
-
- if finished {
- onFinishBuild()
- }
- }
-
- onBuildFileError := func(filePath string, err error) {
- log.Printf("Error for file %s: %v\n", filePath, err)
-
- active.StreamDoneCh <- err
-
- if err != nil {
- log.Printf("Error storing plan error result: %v\n", err)
- }
-
- build.Error = err.Error()
- build.ErrorPath = filePath
-
- err = db.SetBuildError(build)
- if err != nil {
- log.Printf("Error setting build error: %v\n", err)
- }
- }
-
- var buildFile func(filePath string, numRetry int, numReplacementRetry int, res *db.PlanFileResult)
- buildFile = func(filePath string, numRetry int, numReplacementsRetry int, res *db.PlanFileResult) {
- log.Printf("Building file %s, numRetry: %d\n", filePath, numRetry)
-
- // get relevant file context (if any)
- contextPart := active.ContextsByPath[filePath]
-
- var currentState string
- currentPlanFile, fileInCurrentPlan := currentPlan.CurrentPlanFiles.Files[filePath]
-
- if fileInCurrentPlan {
- currentState = currentPlanFile
-
- log.Printf("File %s found in current plan. Using current state.\n", filePath)
- log.Println("Current state:")
- log.Println(currentState)
- } else if contextPart != nil {
- currentState = contextPart.Body
- }
-
- if currentState == "" {
- log.Printf("File %s not found in model context or current plan. Creating new file.\n", filePath)
-
- planTokenCount := &shared.PlanTokenCount{
- Path: filePath,
- NumTokens: numTokensByFile[filePath],
- Finished: true,
- }
-
- // log.Printf("%s: %s", filePath, content)
- planTokenCountJson, err := json.Marshal(planTokenCount)
- if err != nil {
- onBuildFileError(filePath, fmt.Errorf("error marshalling plan chunk: %v", err))
- return
- }
- active.StreamCh <- string(planTokenCountJson)
-
- // new file
- planRes := &db.PlanFileResult{
- OrgId: currentOrgId,
- PlanId: planId,
- PlanBuildId: build.Id,
- ConvoMessageId: build.ConvoMessageId,
- Path: filePath,
- Content: fileContents[filePath],
- }
- onFinishBuildFile(filePath, planRes)
- return
- }
-
- log.Println("Getting file from model: " + filePath)
- // log.Println("File context:", fileContext)
-
- replacePrompt := prompts.GetReplacePrompt(filePath)
- currentStatePrompt := prompts.GetBuildCurrentStatePrompt(filePath, currentState)
- sysPrompt := prompts.GetBuildSysPrompt(filePath, currentStatePrompt)
-
- fileMessages := []openai.ChatCompletionMessage{
- {
- Role: openai.ChatMessageRoleSystem,
- Content: sysPrompt,
- }, {
- Role: openai.ChatMessageRoleUser,
- Content: active.Prompt,
- }, {
- Role: openai.ChatMessageRoleAssistant,
- Content: active.Content,
- },
- {
- Role: openai.ChatMessageRoleUser,
- Content: replacePrompt,
- },
- }
-
- if numReplacementsRetry > 0 && res != nil {
- bytes, err := json.Marshal(res.Replacements)
- if err != nil {
- onBuildFileError(filePath, fmt.Errorf("error marshalling replacements: %v", err))
- return
- }
-
- correctReplacementPrompt, err := prompts.GetCorrectReplacementPrompt(res.Replacements, currentState)
- if err != nil {
- onBuildFileError(filePath, fmt.Errorf("error getting correct replacement prompt: %v", err))
- return
- }
-
- fileMessages = append(fileMessages,
- openai.ChatCompletionMessage{
- Role: openai.ChatMessageRoleAssistant,
- Content: string(bytes),
- },
-
- openai.ChatCompletionMessage{
- Role: openai.ChatMessageRoleUser,
- Content: correctReplacementPrompt,
- })
- }
-
- log.Println("Calling model for file: " + filePath)
-
- // for _, msg := range fileMessages {
- // log.Printf("%s: %s\n", msg.Role, msg.Content)
- // }
-
- modelReq := openai.ChatCompletionRequest{
- Model: model.BuilderModel,
- Functions: []openai.FunctionDefinition{prompts.ReplaceFn},
- Messages: fileMessages,
- Temperature: 0.2,
- TopP: 0.1,
- // ResponseFormat: &openai.ChatCompletionResponseFormat{Type: "json_object"},
- }
-
- stream, err := model.Client.CreateChatCompletionStream(active.Ctx, modelReq)
- if err != nil {
- log.Printf("Error creating plan file stream for path '%s': %v\n", filePath, err)
-
- if numRetry >= MaxRetries {
- onBuildFileError(filePath, fmt.Errorf("failed to create plan file stream for path '%s' after %d retries: %v", filePath, numRetry, err))
- } else {
- log.Println("Retrying build plan for file: " + filePath)
- buildFile(filePath, numRetry+1, numReplacementsRetry, res)
- if err != nil {
- onBuildFileError(filePath, fmt.Errorf("failed to retry build plan for file '%s': %v", filePath, err))
- }
- }
- return
- }
-
- go func() {
- defer stream.Close()
-
- // Create a timer that will trigger if no chunk is received within the specified duration
- timer := time.NewTimer(model.OPENAI_STREAM_CHUNK_TIMEOUT)
- defer timer.Stop()
-
- handleErrorRetry := func(maxRetryErr error, shouldSleep bool, isReplacementsRetry bool, res *db.PlanFileResult) {
- log.Printf("Error for file %s: %v\n", filePath, maxRetryErr)
-
- if isReplacementsRetry && numReplacementsRetry >= MaxReplacementRetries {
- // in this case, we just want to ignore the error and continue
- } else if !isReplacementsRetry && numRetry >= MaxRetries {
- onBuildFileError(filePath, maxRetryErr)
- } else {
- if shouldSleep {
- time.Sleep(1 * time.Second * time.Duration(math.Pow(float64(numRetry+1), 2)))
- }
- if isReplacementsRetry {
- buildFile(filePath, numRetry+1, numReplacementsRetry+1, res)
- } else {
- buildFile(filePath, numRetry+1, numReplacementsRetry, res)
- }
- if err != nil {
- onBuildFileError(filePath, fmt.Errorf("failed to retry build plan for file '%s': %v", filePath, err))
- }
- }
-
- }
-
- for {
- select {
- case <-active.Ctx.Done():
- // The main context was canceled (not the timer)
- return
- case <-timer.C:
- // Timer triggered because no new chunk was received in time
- handleErrorRetry(
- fmt.Errorf("stream timeout due to inactivity for file '%s' after %d retries", filePath, numRetry),
- true,
- false,
- res,
- )
- return
- default:
- response, err := stream.Recv()
-
- if err == nil {
- // Successfully received a chunk, reset the timer
- if !timer.Stop() {
- <-timer.C
- }
- timer.Reset(model.OPENAI_STREAM_CHUNK_TIMEOUT)
- } else {
- log.Printf("File %s: Error receiving stream chunk: %v\n", filePath, err)
-
- if err == context.Canceled {
- log.Printf("File %s: Stream canceled\n", filePath)
- return
- }
-
- handleErrorRetry(
- fmt.Errorf("stream error for file '%s' after %d retries: %v", filePath, numRetry, err),
- true,
- false,
- res,
- )
- return
- }
-
- if len(response.Choices) == 0 {
- handleErrorRetry(fmt.Errorf("stream error: no choices"), true, false, res)
- return
- }
-
- choice := response.Choices[0]
-
- if choice.FinishReason != "" {
- if choice.FinishReason != openai.FinishReasonFunctionCall {
- handleErrorRetry(
- fmt.Errorf("stream finished without a function call. Reason: %s, File: %s", choice.FinishReason, filePath),
- false,
- false,
- res,
- )
- return
- }
-
- log.Printf("File %s: Stream finished with non-function call\n", filePath)
- log.Println("finish reason: " + choice.FinishReason)
-
- active := Active.Get(planId)
- if !active.BuiltFiles[filePath] {
- log.Printf("Stream finished before replacements parsed. File: %s\n", filePath)
- log.Println("Buffer:")
- log.Println(active.BuildBuffers[filePath])
-
- handleErrorRetry(
- fmt.Errorf("stream finished before replacements parsed. File: %s", filePath),
- true,
- false,
- res,
- )
- return
- }
- }
-
- var content string
- delta := response.Choices[0].Delta
-
- if delta.FunctionCall == nil {
- log.Println("No function call in delta. File:", filePath)
- spew.Dump(delta)
- continue
- } else {
- content = delta.FunctionCall.Arguments
- }
-
- planTokenCount := &shared.PlanTokenCount{
- Path: filePath,
- NumTokens: 1,
- Finished: false,
- }
-
- // log.Printf("%s: %s", filePath, content)
- planTokenCountJson, err := json.Marshal(planTokenCount)
- if err != nil {
- onBuildFileError(filePath, fmt.Errorf("error marshalling plan chunk: %v", err))
- return
- }
- active.StreamCh <- string(planTokenCountJson)
-
- var buffer string
- Active.Update(planId, func(ap *types.ActivePlan) {
- ap.BuildBuffers[filePath] += content
- buffer = ap.BuildBuffers[filePath]
- })
-
- var streamed types.StreamedReplacements
- err = json.Unmarshal([]byte(buffer), &streamed)
- if err == nil && len(streamed.Replacements) > 0 {
- log.Printf("File %s: Parsed replacements\n", filePath)
-
- planFileResult, allSucceeded := getPlanResult(
- planResultParams{
- orgId: currentOrgId,
- planId: planId,
- planBuildId: build.Id,
- convoMessageId: build.ConvoMessageId,
- filePath: filePath,
- currentState: currentState,
- context: contextPart,
- replacements: streamed.Replacements,
- },
- )
-
- // proposalId, filePath, currentState, contextPart, replacements.Replacements)
-
- if !allSucceeded {
- log.Println("Failed replacements:")
- for _, replacement := range planFileResult.Replacements {
- if replacement.Failed {
- spew.Dump(replacement)
- }
- }
-
- if numReplacementsRetry < MaxReplacementRetries {
- handleErrorRetry(
- nil, // no error -- if we reach MAX_REPLACEMENT_RETRIES, we just ignore the error and continue
- false,
- true,
- planFileResult,
- )
- return
- }
- }
-
- planTokenCount := &shared.PlanTokenCount{
- Path: filePath,
- NumTokens: 0,
- Finished: true,
- }
-
- // log.Printf("%s: %s", filePath, content)
- planTokenCountJson, err := json.Marshal(planTokenCount)
- if err != nil {
- onBuildFileError(filePath, fmt.Errorf("error marshalling plan chunk: %v", err))
- return
- }
- active.StreamCh <- string(planTokenCountJson)
-
- onFinishBuildFile(filePath, planFileResult)
- return
- }
- }
- }
- }()
- }
-
- for _, filePath := range active.Files {
- go buildFile(filePath, 0, 0, nil)
- }
-}
-
-type planResultParams struct {
- orgId string
- planId string
- planBuildId string
- convoMessageId string
- filePath string
- currentState string
- context *db.Context
- replacements []*shared.Replacement
-}
-
-func getPlanResult(params planResultParams) (*db.PlanFileResult, bool) {
- orgId := params.orgId
- planId := params.planId
- planBuildId := params.planBuildId
- filePath := params.filePath
- currentState := params.currentState
- contextPart := params.context
- replacements := params.replacements
- updated := params.currentState
-
- sort.Slice(replacements, func(i, j int) bool {
- iIdx := strings.Index(updated, replacements[i].Old)
- jIdx := strings.Index(updated, replacements[j].Old)
- return iIdx < jIdx
- })
-
- _, allSucceeded := shared.ApplyReplacements(currentState, replacements, true)
-
- var contextSha string
- if contextPart != nil {
- contextSha = contextPart.Sha
- }
-
- for _, replacement := range replacements {
- id := uuid.New().String()
- replacement.Id = id
- }
-
- return &db.PlanFileResult{
- OrgId: orgId,
- PlanId: planId,
- PlanBuildId: planBuildId,
- ConvoMessageId: params.convoMessageId,
- Content: "",
- Path: filePath,
- Replacements: replacements,
- ContextSha: contextSha,
- AnyFailed: !allSucceeded,
- }, allSucceeded
-}
diff --git a/server/model/plan/describe.go b/server/model/plan/describe.go
deleted file mode 100644
index e2abc163..00000000
--- a/server/model/plan/describe.go
+++ /dev/null
@@ -1,70 +0,0 @@
-package plan
-
-import (
- "context"
- "encoding/json"
- "fmt"
- "plandex-server/db"
- "plandex-server/model"
- "plandex-server/model/prompts"
-
- "github.com/plandex/plandex/shared"
- "github.com/sashabaranov/go-openai"
-)
-
-func genPlanDescription(planId string, ctx context.Context) (*db.ConvoMessageDescription, error) {
-
- descResp, err := model.Client.CreateChatCompletion(
- ctx,
- openai.ChatCompletionRequest{
- Model: model.CommitMsgModel,
- Functions: []openai.FunctionDefinition{prompts.DescribePlanFn},
- Messages: []openai.ChatCompletionMessage{
- {
- Role: openai.ChatMessageRoleSystem,
- Content: prompts.SysDescribe,
- },
- {
- Role: openai.ChatMessageRoleAssistant,
- Content: Active.Get(planId).Content,
- },
- },
- ResponseFormat: &openai.ChatCompletionResponseFormat{Type: "json_object"},
- },
- )
-
- var descStrRes string
- var desc shared.ConvoMessageDescription
-
- if err != nil {
- fmt.Printf("Error during plan description model call: %v\n", err)
- return nil, err
- }
-
- for _, choice := range descResp.Choices {
- if choice.FinishReason == "function_call" &&
- choice.Message.FunctionCall != nil &&
- choice.Message.FunctionCall.Name == "describePlan" {
- fnCall := choice.Message.FunctionCall
- descStrRes = fnCall.Arguments
- }
- }
-
- if descStrRes == "" {
- fmt.Println("no describePlan function call found in response")
- return nil, err
- }
-
- descByteRes := []byte(descStrRes)
-
- err = json.Unmarshal(descByteRes, &desc)
- if err != nil {
- fmt.Printf("Error unmarshalling plan description response: %v\n", err)
- return nil, err
- }
-
- return &db.ConvoMessageDescription{
- PlanId: planId,
- CommitMsg: desc.CommitMsg,
- }, nil
-}
diff --git a/server/model/plan/lorem_ipsum.go b/server/model/plan/lorem_ipsum.go
deleted file mode 100644
index c16c6cdb..00000000
--- a/server/model/plan/lorem_ipsum.go
+++ /dev/null
@@ -1,121 +0,0 @@
-package plan
-
-// import (
-// "encoding/json"
-// "plandex-server/types"
-// "strings"
-// "sync"
-// "time"
-
-// lorem "github.com/drhodes/golorem"
-// "github.com/plandex/plandex/shared"
-// )
-
-// func applyLoremStyling(paragraphs []string) []string {
-// for p, paragraph := range paragraphs {
-// sentences := strings.Split(paragraph, ". ")
-// for _, sentence := range sentences {
-// words := strings.Split(sentence, " ")
-// for i, word := range words {
-// if (i+1)%5 == 0 { // Bold every 5th word
-// words[i] = "**" + word + "**"
-// }
-// if (i+1)%8 == 0 { // Italicize every 8th word
-// words[i] = "_" + word + "_"
-// }
-// if (i+1)%7 == 0 { // Color every 7th word
-// words[i] = `<span style="color:blue">` + word + `</span>`
-// }
-// }
-// }
-// paragraphs[p] = strings.Join(sentences, ". ")
-// }
-// return paragraphs
-// }
-
-// // Function to stream "lorem ipsum" text sentence by sentence with delay
-// func streamLoremIpsum(onStream types.OnStreamFunc) {
-// paragraphs := []string{lorem.Paragraph(1, 1), lorem.Paragraph(1, 1), lorem.Paragraph(1, 1)}
-// paragraphs = applyLoremStyling(paragraphs)
-
-// for _, paragraph := range paragraphs {
-// for _, line := range strings.Split(paragraph, "\n") {
-// for _, word := range strings.Split(line, " ") {
-// onStream(word+" ", nil)
-// time.Sleep(50 * time.Millisecond)
-// }
-// onStream("\n", nil)
-// time.Sleep(50 * time.Millisecond)
-// }
-// onStream("\n\n", nil)
-// time.Sleep(50 * time.Millisecond)
-// }
-// onStream(shared.STREAM_DESCRIPTION_PHASE, nil)
-
-// planDescription := &shared.PlanDescription{
-// MadePlan: true,
-// Files: []string{"file1.txt", "file2.txt"},
-// }
-// planDescriptionBytes, _ := json.Marshal(planDescription)
-// planDescriptionJson := string(planDescriptionBytes)
-// time.Sleep(2000 * time.Millisecond)
-
-// onStream(planDescriptionJson, nil)
-
-// onStream(shared.STREAM_BUILD_PHASE, nil)
-// buildPlan("", map[string]string{}, map[string]int{}, onStream)
-
-// }
-
-// func streamFilesLoremIpsum(onStream types.OnStreamFunc) {
-// writeNumTokens := func(filePath string, content string) {
-// numTokens := shared.GetNumTokens(content)
-// chunk := shared.PlanTokenCount{Path: filePath, NumTokens: numTokens}
-// chunkJson, _ := json.Marshal(chunk)
-// onStream(string(chunkJson), nil)
-// time.Sleep(50 * time.Millisecond) // Adding a small delay between files for effect
-// }
-
-// writeFile := func(filePath string, content string) {
-// file := shared.PlanFile{Path: filePath, Content: content}
-// fileJson, _ := json.Marshal(file)
-// onStream(string(fileJson), nil)
-// }
-
-// // For each file in the proposal, stream some unstyled lorem ipsum content
-// var wg sync.WaitGroup
-// files := []string{"file1.txt", "file2.txt"}
-// contentByPath := map[string]string{}
-// for _, filePath := range files {
-// wg.Add(1)
-// go func(filePath string) {
-// defer wg.Done()
-// text := strings.Join([]string{lorem.Paragraph(1, 1), lorem.Paragraph(1, 1), lorem.Paragraph(1, 1)}, "\n\n")
-// contentByPath[filePath] = text
-
-// for _, line := range strings.Split(text, "\n") {
-// for _, word := range strings.Split(line, " ") {
-// writeNumTokens(filePath, word+" ")
-// }
-// writeNumTokens(filePath, "\n")
-// }
-// }(filePath)
-// }
-
-// wg.Wait()
-
-// onStream(shared.STREAM_WRITE_PHASE, nil)
-
-// for _, filePath := range files {
-// wg.Add(1)
-// go func(filePath string) {
-// defer wg.Done()
-// text := contentByPath[filePath]
-// writeFile(filePath, text)
-// }(filePath)
-// }
-
-// wg.Wait()
-
-// onStream(shared.STREAM_FINISHED, nil)
-// }
diff --git a/server/model/plan/state.go b/server/model/plan/state.go
deleted file mode 100644
index 80191bbf..00000000
--- a/server/model/plan/state.go
+++ /dev/null
@@ -1,72 +0,0 @@
-package plan
-
-import (
- "log"
- "plandex-server/db"
- "plandex-server/types"
-
- "github.com/plandex/plandex/shared"
-)
-
-var (
- Active types.SafeMap[*types.ActivePlan] = *types.NewSafeMap[*types.ActivePlan]()
-)
-
-func CreateActivePlan(planId, prompt string) *types.ActivePlan {
- activePlan := types.NewActivePlan(prompt)
- Active.Set(planId, activePlan)
-
- go func() {
- for {
- select {
- case <-activePlan.Ctx.Done():
- return
- case err := <-activePlan.StreamDoneCh:
- if err == nil {
- log.Printf("Plan %s stream completed successfully", planId)
-
- err = db.SetPlanStatus(planId, shared.PlanStatusFinished, "")
- if err != nil {
- log.Printf("Error setting plan %s status to ready: %v\n", planId, err)
- }
-
- } else {
- log.Printf("Error streaming plan %s: %v\n", planId, err)
-
- err = db.SetPlanStatus(planId, shared.PlanStatusError, err.Error())
- if err != nil {
- log.Printf("Error setting plan %s status to error: %v\n", planId, err)
- }
- }
-
- activePlan.CancelFn()
-
- Active.Delete(planId)
- return
- }
- }
- }()
-
- return activePlan
-}
-
-func SubscribePlan(planId string) (string, chan string) {
- var id string
- var ch chan string
- Active.Update(planId, func(activePlan *types.ActivePlan) {
- id, ch = activePlan.Subscribe()
- })
- return id, ch
-}
-
-func UnsubscribePlan(planId, subscriptionId string) {
- active := Active.Get(planId)
-
- if active == nil {
- return
- }
-
- Active.Update(planId, func(activePlan *types.ActivePlan) {
- activePlan.Unsubscribe(subscriptionId)
- })
-}
diff --git a/server/model/plan/stop.go b/server/model/plan/stop.go
deleted file mode 100644
index 550fdafc..00000000
--- a/server/model/plan/stop.go
+++ /dev/null
@@ -1,40 +0,0 @@
-package plan
-
-import (
- "fmt"
- "plandex-server/db"
-
- "github.com/sashabaranov/go-openai"
-)
-
-func Stop(planId, currentUserId, currentOrgId string) error {
-
- active := Active.Get(planId)
-
- if active == nil {
- return fmt.Errorf("no active plan with id %s", planId)
- }
-
- content := active.Content
-
- active.CancelFn()
-
- userMsg := db.ConvoMessage{
- OrgId: currentOrgId,
- PlanId: planId,
- UserId: currentUserId,
- Role: openai.ChatMessageRoleAssistant,
- Tokens: active.NumTokens,
- Num: active.PromptMessageNum + 1,
- Stopped: true,
- Message: content,
- }
-
- _, err := db.StoreConvoMessage(&userMsg, true)
-
- if err != nil {
- return fmt.Errorf("error storing convo message: %v", err)
- }
-
- return nil
-}
diff --git a/server/model/plan/tell.go b/server/model/plan/tell.go
deleted file mode 100644
index 85934faf..00000000
--- a/server/model/plan/tell.go
+++ /dev/null
@@ -1,615 +0,0 @@
-package plan
-
-import (
- "errors"
- "fmt"
- "log"
- "strings"
- "time"
-
- "plandex-server/db"
- "plandex-server/model"
- "plandex-server/model/lib"
- "plandex-server/model/prompts"
- "plandex-server/types"
-
- "github.com/plandex/plandex/shared"
- "github.com/sashabaranov/go-openai"
-)
-
-// Proposal function to create a new proposal
-func Tell(plan *db.Plan, auth *types.ServerAuth, req *shared.TellPlanRequest) error {
- // goEnv := os.Getenv("GOENV") // Fetch the GO_ENV environment variable
-
- // log.Println("GOENV: " + goEnv)
- // if goEnv == "test" {
- // streamLoremIpsum(onStream)
- // return nil
- // }
-
- planId := plan.Id
-
- active := Active.Get(planId)
- if active != nil {
- return fmt.Errorf("plan %s already has an active stream", planId)
- }
-
- active = CreateActivePlan(planId, req.Prompt)
-
- go execTellPlan(plan, auth, req, active)
-
- return nil
-}
-
-func execTellPlan(plan *db.Plan, auth *types.ServerAuth, req *shared.TellPlanRequest, active *types.ActivePlan) {
- currentUserId := auth.User.Id
- currentOrgId := auth.OrgId
-
- planId := plan.Id
- err := db.SetPlanStatus(planId, shared.PlanStatusReplying, "")
- if err != nil {
- log.Printf("Error setting plan %s status to replying: %v\n", planId, err)
- active.StreamDoneCh <- fmt.Errorf("error setting plan status to replying: %v", err)
- return
- }
-
- errCh := make(chan error)
- var modelContext []*db.Context
- var convo []*db.ConvoMessage
- var summaries []*db.ConvoSummary
-
- // get name for plan and rename it's a draft
- go func() {
- if plan.Name == "draft" {
- name, err := model.GenPlanName(req.Prompt)
-
- if err != nil {
- log.Printf("Error generating plan name: %v\n", err)
- errCh <- fmt.Errorf("error generating plan name: %v", err)
- return
- }
-
- err = db.RenamePlan(planId, name)
-
- if err != nil {
- log.Printf("Error renaming plan: %v\n", err)
- errCh <- fmt.Errorf("error renaming plan: %v", err)
- return
- }
-
- err = db.IncNumNonDraftPlans(currentUserId)
-
- if err != nil {
- log.Printf("Error incrementing num non draft plans: %v\n", err)
- errCh <- fmt.Errorf("error incrementing num non draft plans: %v", err)
- return
- }
- }
-
- errCh <- nil
- }()
-
- go func() {
- res, err := db.GetPlanContexts(currentOrgId, planId, true)
- if err != nil {
- log.Printf("Error getting plan modelContext: %v\n", err)
- errCh <- fmt.Errorf("error getting plan modelContext: %v", err)
- return
- }
- modelContext = res
- errCh <- nil
- }()
-
- go func() {
- res, err := db.GetPlanConvo(currentOrgId, planId)
- if err != nil {
- log.Printf("Error getting plan convo: %v\n", err)
- errCh <- fmt.Errorf("error getting plan convo: %v", err)
- return
- }
- convo = res
-
- promptTokens, err := shared.GetNumTokens(req.Prompt)
- if err != nil {
- log.Printf("Error getting prompt num tokens: %v\n", err)
- errCh <- fmt.Errorf("error getting prompt num tokens: %v", err)
- return
- }
-
- userMsg := db.ConvoMessage{
- OrgId: currentOrgId,
- PlanId: planId,
- UserId: currentUserId,
- Role: openai.ChatMessageRoleUser,
- Tokens: promptTokens,
- Num: len(convo) + 1,
- Message: req.Prompt,
- }
-
- _, err = db.StoreConvoMessage(&userMsg, true)
-
- if err != nil {
- log.Printf("Error storing user message: %v\n", err)
- errCh <- fmt.Errorf("error storing user message: %v", err)
- return
- }
-
- errCh <- nil
- }()
-
- go func() {
- res, err := db.GetPlanSummaries(planId)
- if err != nil {
- log.Printf("Error getting plan summaries: %v\n", err)
- errCh <- fmt.Errorf("error getting plan summaries: %v", err)
- return
- }
- summaries = res
-
- errCh <- nil
- }()
-
- for i := 0; i < 4; i++ {
- err := <-errCh
- if err != nil {
- active.StreamDoneCh <- fmt.Errorf("error getting plan, context, convo, or summaries: %v", err)
- return
- }
- }
-
- Active.Update(planId, func(ap *types.ActivePlan) {
- ap.Contexts = modelContext
- ap.PromptMessageNum = len(convo) + 1
-
- for _, context := range modelContext {
- if context.FilePath != "" {
- ap.ContextsByPath[context.FilePath] = context
- }
- }
- })
-
- modelContextText, modelContextTokens, err := lib.FormatModelContext(modelContext)
- if err != nil {
- err = fmt.Errorf("error formatting model modelContext: %v", err)
- log.Println(err)
- active.StreamDoneCh <- err
- return
- }
-
- systemMessageText := prompts.SysCreate + modelContextText
- systemMessage := openai.ChatCompletionMessage{
- Role: openai.ChatMessageRoleSystem,
- Content: systemMessageText,
- }
-
- messages := []openai.ChatCompletionMessage{
- systemMessage,
- }
-
- numPromptTokens, err := shared.GetNumTokens(req.Prompt)
- if err != nil {
- err = fmt.Errorf("error getting number of tokens in prompt: %v", err)
- log.Println(err)
- active.StreamDoneCh <- err
- return
- }
-
- promptTokens := prompts.PromptWrapperTokens + numPromptTokens
- totalTokens := prompts.CreateSysMsgNumTokens + modelContextTokens + promptTokens
-
- // print out breakdown of token usage
- log.Printf("System message tokens: %d\n", prompts.CreateSysMsgNumTokens)
- log.Printf("Context tokens: %d\n", modelContextTokens)
- log.Printf("Prompt tokens: %d\n", promptTokens)
- log.Printf("Total tokens before convo: %d\n", totalTokens)
-
- if totalTokens > shared.MaxTokens {
- // token limit already exceeded before adding conversation
- err := fmt.Errorf("token limit exceeded before adding conversation")
- log.Printf("Error: %v\n", err)
- active.StreamDoneCh <- err
- return
- }
-
- conversationTokens := 0
- tokensUpToTimestamp := make(map[time.Time]int)
- for _, convoMessage := range convo {
- conversationTokens += convoMessage.Tokens
- tokensUpToTimestamp[convoMessage.CreatedAt] = conversationTokens
- // log.Printf("Timestamp: %s | Tokens: %d | Total: %d | conversationTokens\n", convoMessage.Timestamp, convoMessage.Tokens, conversationTokens)
- }
-
- log.Printf("Conversation tokens: %d\n", conversationTokens)
-
- var summary *db.ConvoSummary
- var summarizedToMessageId string
- if (totalTokens+conversationTokens) > shared.MaxTokens ||
- conversationTokens > shared.MaxConvoTokens {
- log.Println("Token limit exceeded. Attempting to reduce via conversation summary.")
-
- // token limit exceeded after adding conversation
- // get summary for as much as the conversation as necessary to stay under the token limit
- for _, s := range summaries {
- tokens, ok := tokensUpToTimestamp[s.LatestConvoMessageCreatedAt]
-
- log.Printf("Last message id: %s\n", s.LatestConvoMessageCreatedAt)
-
- if !ok {
- err := fmt.Errorf("conversation summary timestamp not found in conversation")
- log.Printf("Error: %v\n", err)
- active.StreamDoneCh <- err
- return
- }
-
- updatedConversationTokens := (conversationTokens - tokens) + s.Tokens
- savedTokens := conversationTokens - updatedConversationTokens
-
- log.Printf("Conversation summary tokens: %d\n", tokens)
- log.Printf("Updated conversation tokens: %d\n", updatedConversationTokens)
- log.Printf("Saved tokens: %d\n", savedTokens)
-
- if updatedConversationTokens <= shared.MaxConvoTokens &&
- (totalTokens+updatedConversationTokens) <= shared.MaxTokens {
- log.Printf("Summarizing up to %s | saving %d tokens\n", s.LatestConvoMessageCreatedAt.Format(time.RFC3339), savedTokens)
- summary = s
- break
- }
- }
-
- if summary == nil {
- err := errors.New("couldn't get under token limit with conversation summary")
- log.Printf("Error: %v\n", err)
- active.StreamDoneCh <- err
- return
- }
- }
-
- if summary == nil {
- for _, convoMessage := range convo {
- messages = append(messages, openai.ChatCompletionMessage{
- Role: convoMessage.Role,
- Content: convoMessage.Message,
- })
- }
- } else {
- if (totalTokens + summary.Tokens) > shared.MaxTokens {
- err := fmt.Errorf("token limit still exceeded after summarizing conversation")
- active.StreamDoneCh <- err
- return
- }
- summarizedToMessageId = summary.LatestConvoMessageId
- messages = append(messages, openai.ChatCompletionMessage{
- Role: openai.ChatMessageRoleAssistant,
- Content: summary.Summary,
- })
-
- // add messages after the last message in the summary
- for _, convoMessage := range convo {
- if convoMessage.CreatedAt.After(summary.LatestConvoMessageCreatedAt) {
- messages = append(messages, openai.ChatCompletionMessage{
- Role: convoMessage.Role,
- Content: convoMessage.Message,
- })
- }
- }
- }
-
- promptMessage := openai.ChatCompletionMessage{
- Role: openai.ChatMessageRoleUser,
- Content: fmt.Sprintf(prompts.PromptWrapperFormatStr, req.Prompt),
- }
-
- messages = append(messages, promptMessage)
-
- // log.Println("\n\nMessages:")
- // for _, message := range messages {
- // log.Printf("%s: %s\n", message.Role, message.Content)
- // }
-
- replyInfo := types.NewReplyInfo()
-
- modelReq := openai.ChatCompletionRequest{
- Model: model.PlannerModel,
- Messages: messages,
- Stream: true,
- Temperature: 0.6,
- TopP: 0.7,
- }
-
- stream, err := model.Client.CreateChatCompletionStream(active.Ctx, modelReq)
- if err != nil {
- log.Printf("Error creating proposal GPT4 stream: %v\n", err)
- log.Println(err)
-
- errStr := err.Error()
- if strings.Contains(errStr, "status code: 400") &&
- strings.Contains(errStr, "reduce the length of the messages") {
- log.Println("Token limit exceeded")
- }
-
- active.StreamDoneCh <- err
- return
- }
-
- storeAssistantReply := func() (*db.ConvoMessage, []string, string, error) {
- files, _, _, replyNumTokens := replyInfo.FinishAndRead()
-
- assistantMsg := db.ConvoMessage{
- OrgId: currentOrgId,
- PlanId: planId,
- UserId: currentUserId,
- Role: openai.ChatMessageRoleAssistant,
- Tokens: replyNumTokens,
- Num: len(convo) + 2,
- Message: Active.Get(planId).Content,
- }
-
- commitMsg, err := db.StoreConvoMessage(&assistantMsg, false)
-
- if err != nil {
- log.Printf("Error storing assistant message: %v\n", err)
- return nil, files, "", err
- }
-
- Active.Update(planId, func(active *types.ActivePlan) {
- active.AssistantMessageId = assistantMsg.Id
- })
-
- return &assistantMsg, files, commitMsg, err
- }
-
- onError := func(streamErr error, storeDesc bool, convoMessageId, commitMsg string) {
- log.Printf("\nStream error: %v\n", streamErr)
- active.StreamDoneCh <- streamErr
-
- storedMessage := false
- storedDesc := false
-
- if convoMessageId == "" {
- assistantMsg, _, msg, err := storeAssistantReply()
- if err == nil {
- convoMessageId = assistantMsg.Id
- commitMsg = msg
- storedMessage = true
- } else {
- log.Printf("Error storing assistant message after stream error: %v\n", err)
- }
- }
-
- if storeDesc && convoMessageId != "" {
- err = db.StoreDescription(&db.ConvoMessageDescription{
- OrgId: currentOrgId,
- PlanId: planId,
- SummarizedToMessageId: summarizedToMessageId,
- MadePlan: false,
- ConvoMessageId: convoMessageId,
- Error: streamErr.Error(),
- })
- if err == nil {
- storedDesc = true
- } else {
- log.Printf("Error storing description after stream error: %v\n", err)
- }
- }
-
- if storedMessage || storedDesc {
- err = db.GitAddAndCommit(currentOrgId, planId, commitMsg)
- if err != nil {
- log.Printf("Error committing after stream error: %v\n", err)
- }
- }
- }
-
- go func() {
- defer stream.Close()
-
- // Create a timer that will trigger if no chunk is received within the specified duration
- timer := time.NewTimer(model.OPENAI_STREAM_CHUNK_TIMEOUT)
- defer timer.Stop()
-
- for {
- select {
- case <-active.Ctx.Done():
- // The main modelContext was canceled (not the timer)
- return
- case <-timer.C:
- // Timer triggered because no new chunk was received in time
- log.Println("\nStream timeout due to inactivity")
- onError(fmt.Errorf("stream timeout due to inactivity"), true, "", "")
- return
- default:
- response, err := stream.Recv()
-
- if err == nil {
- // Successfully received a chunk, reset the timer
- if !timer.Stop() {
- <-timer.C
- }
- timer.Reset(model.OPENAI_STREAM_CHUNK_TIMEOUT)
- }
-
- if err != nil {
- onError(fmt.Errorf("stream error: %v", err), true, "", "")
- return
- }
-
- if len(response.Choices) == 0 {
- onError(fmt.Errorf("stream finished with no choices"), true, "", "")
- return
- }
-
- if len(response.Choices) > 1 {
- onError(fmt.Errorf("stream finished with more than one choice"), true, "", "")
- return
- }
-
- choice := response.Choices[0]
-
- if choice.FinishReason != "" {
- active.StreamCh <- shared.STREAM_DESCRIPTION_PHASE
- err := db.SetPlanStatus(planId, shared.PlanStatusDescribing, "")
- if err != nil {
- onError(fmt.Errorf("failed to set plan status to describing: %v", err), true, "", "")
- return
- }
-
- if len(convo) > 0 {
- // summarize in the background
- go summarizeConvo(summarizeConvoParams{
- planId: planId,
- convo: convo,
- summaries: summaries,
- promptMessage: promptMessage,
- currentOrgId: currentOrgId,
- })
- }
-
- assistantMsg, files, convoCommitMsg, err := storeAssistantReply()
-
- if err != nil {
- onError(fmt.Errorf("failed to store assistant message: %v", err), true, "", "")
- return
- }
-
- var description *db.ConvoMessageDescription
-
- if len(files) == 0 {
- description = &db.ConvoMessageDescription{
- OrgId: currentOrgId,
- PlanId: planId,
- ConvoMessageId: assistantMsg.Id,
- SummarizedToMessageId: summarizedToMessageId,
- MadePlan: false,
- }
- } else {
- Active.Update(planId, func(ap *types.ActivePlan) {
- ap.Files = files
- })
-
- description, err = genPlanDescription(planId, active.Ctx)
- if err != nil {
- onError(fmt.Errorf("failed to generate plan description: %v", err), true, assistantMsg.Id, convoCommitMsg)
- return
- }
-
- description.OrgId = currentOrgId
- description.ConvoMessageId = assistantMsg.Id
- description.SummarizedToMessageId = summarizedToMessageId
- description.MadePlan = true
- description.Files = files
- }
-
- err = db.StoreDescription(description)
-
- if err != nil {
- onError(fmt.Errorf("failed to store description: %v", err), false, assistantMsg.Id, convoCommitMsg)
- return
- }
-
- err = db.GitAddAndCommit(currentOrgId, planId, convoCommitMsg)
- if err != nil {
- onError(fmt.Errorf("failed to commit: %v", err), false, assistantMsg.Id, convoCommitMsg)
- return
- }
-
- if len(files) == 0 {
- active.StreamCh <- shared.STREAM_FINISHED
- active.StreamDoneCh <- nil
- } else {
- active.StreamCh <- shared.STREAM_BUILD_PHASE
- Build(currentOrgId, planId)
- }
- return
- }
-
- delta := choice.Delta
- content := delta.Content
- Active.Update(planId, func(active *types.ActivePlan) {
- active.Content += content
- active.NumTokens++
- })
-
- // log.Printf("%s", content)
- active.StreamCh <- content
- replyInfo.AddToken(content, true)
-
- }
- }
- }()
-}
-
-type summarizeConvoParams struct {
- planId string
- convo []*db.ConvoMessage
- summaries []*db.ConvoSummary
- promptMessage openai.ChatCompletionMessage
- currentOrgId string
-}
-
-func summarizeConvo(params summarizeConvoParams) error {
- planId := params.planId
- convo := params.convo
- summaries := params.summaries
- promptMessage := params.promptMessage
- currentOrgId := params.currentOrgId
-
- log.Println("Generating plan summary for planId:", planId)
-
- var summaryMessages []openai.ChatCompletionMessage
- var latestSummary *db.ConvoSummary
- var numMessagesSummarized int = 0
- var latestMessageSummarizedAt time.Time
- var latestMessageId string
- if len(summaries) > 0 {
- latestSummary = summaries[len(summaries)-1]
- numMessagesSummarized = latestSummary.NumMessages
- }
-
- if latestSummary == nil {
- for _, convoMessage := range convo {
- summaryMessages = append(summaryMessages, openai.ChatCompletionMessage{
- Role: convoMessage.Role,
- Content: convoMessage.Message,
- })
- latestMessageId = convoMessage.Id
- latestMessageSummarizedAt = convoMessage.CreatedAt
- }
- } else {
- summaryMessages = append(summaryMessages, openai.ChatCompletionMessage{
- Role: openai.ChatMessageRoleAssistant,
- Content: latestSummary.Summary,
- })
- latestMessageId = latestSummary.LatestConvoMessageId
- latestMessageSummarizedAt = latestSummary.LatestConvoMessageCreatedAt
- }
-
- summaryMessages = append(summaryMessages, promptMessage, openai.ChatCompletionMessage{
- Role: openai.ChatMessageRoleAssistant,
- Content: Active.Get(planId).Content,
- })
-
- summary, err := model.PlanSummary(model.PlanSummaryParams{
- Conversation: summaryMessages,
- LatestConvoMessageId: latestMessageId,
- LatestConvoMessageCreatedAt: latestMessageSummarizedAt,
- NumMessages: numMessagesSummarized + 1,
- OrgId: currentOrgId,
- PlanId: planId,
- })
-
- if err != nil {
- log.Printf("Error generating plan summary for plan %s: %v\n", planId, err)
- return err
- }
-
- log.Println("Generated plan summary for plan", planId)
-
- err = db.StoreSummary(summary)
-
- if err != nil {
- log.Printf("Error storing plan summary for plan %s: %v\n", planId, err)
- return err
- }
-
- return nil
-}
diff --git a/server/model/prompts/build.go b/server/model/prompts/build.go
deleted file mode 100644
index d42fb1cb..00000000
--- a/server/model/prompts/build.go
+++ /dev/null
@@ -1,233 +0,0 @@
-package prompts
-
-import (
- "encoding/json"
- "fmt"
-
- "github.com/plandex/plandex/shared"
- "github.com/sashabaranov/go-openai"
- "github.com/sashabaranov/go-openai/jsonschema"
-)
-
-func GetBuildSysPrompt(filePath, currentStatePrompt string) string {
- return fmt.Sprintf(`
-[YOUR INSTRUCTIONS]
-
-You are an AI replacer. You apply changes from a plan to a given code file using the 'writeReplacements' function. You call 'writeReplacements' with a valid JSON array of replacements.
-
-Each replacement is an object with 3 properties: 'old', 'new', and 'summary'. 'old' is the *exact* old text to replace. 'new' is the new text to replace it with. 'summary' is a brief 1 line summary of the change.
-
-Use your judgment on how to logically apply the changes from the plan in a series of replacements. Use both the code and the plan description to determine the correct order of replacements. BE COMPLETELY SURE that replacements are inserted logically at the correct locations in the file and do not break any syntax or logic rules of the programming language.
-
-Lean toward using fewer replacements. If you can apply all the changes in a single replacement, and that replacement isn't very long, do that. If you need to use multiple replacements, that's fine too, but try to use as few as possible.
-
-DO NOT INCLUDE any sections that are just comments, placeholders, references to the original file, or TODOs that are not yet implemented. Only include actual changes that move the plan forward and are ready to be applied to the file.
-
-These replacements will be applied automatically by a program to the file exactly as written, so the 'old' text must be an EXACT SUBSTRING of the **current state of the file**. The current state of the file will be provided below, labelled with '**Current state of file for %s:**'. It does *not* include any of the suggested changes from the latest response. The 'old' text MUST be an exact substring of the current state of the file, not the suggested changes from the latest response.
-
-Pay special attention to any special characters in the strings, extra spaces, or anything else that might cause 'old' not to be an exact substring.
-
-The 'old' text should be unique and unambiguous in the current file. It must not overlap with any other 'old' text in the list of replacements. Make the 'old' text as short as it can be while still being unique and unambiguous. If the 'old' text can be a single line, it should be. If it must be multiple lines, it should be as few lines as possible.
-
-The 'new' text must include the full text of the replacement without any placeholders or references to the original file. DO NOT INCLUDE text like "// ... existing code", "// ... rest of the file", or other equivalents with different wording/formatting/syntax in the 'new' text. Only include the actual code that should be inserted.
-
-For the 'new' text, apart from the exceptions I mentioned in the previous paragraph, do not make any additional modifications on top of the changes from the plan unless absolutely necessary to apply the change correctly. Don't add additional comments. Don't escape characters (like emoji or other characters) unless they are also escaped in the plan. Keep as closely as possible to the changes as suggested in the plan, down to specific characters and formatting.
-
-You MUST call only 'writeReplacements'--don't call any other function or produce any other output.
-
-Replacement examples below. Note: >>> and <<< indicate the start and end of an example response.
-
-1.)
-If the current file is:
-`+"```"+`
-package main
-
-import "fmt"
-
-func main() {
- fmt.Println("Hello, world!")
-}
-`+"```"+`
-
-And the previous response was:
-
->>>
-You can change the main.go file to print the current time instead of "Hello, world!".:
-
-- main.go:
-`+"```"+`
-func main() {
- fmt.Println(time.Now())
-}
-`+"```"+`
-
-You'll also need to import the time package:
-
-- main.go:
-`+"```"+`
-import (
- "fmt"
- "time"
-)
-`+"```"+`
-<<<
-
-Then you would call the 'writeReplacements' function like this:
-
-writeReplacements({
- replacements: [
- {
- old: "import \"fmt\"",
- new: "import (\n\t\"fmt\"\n\t\"time\"\n)",
- summary: "Import time package"
- },
- {
- old: "fmt.Println(\"Hello, world!\")",
- new: "fmt.Println(time.Now())",
- summary: "Print current time"
- }
- }
-})
-
-2.)
-If the current file is:
-`+"```"+`
-package helpers
-
-func Add(a, b int) int {
- return a + b
-}
-`+"```"+`
-
-And the previous response was:
-
->>>
-Add another function to the helpers.go file that subtracts two numbers:
-
-- helpers.go:
-`+"```"+`
-func Subtract(a, b int) int {
- return a - b
-}
-`+"```"+`
-<<<
-
-Then you would call the 'writeReplacements' function like this:
-
-writeReplacements({
- replacements: [
- {
- old: "\n}",
- new: "\n}\n\nfunc Subtract(a, b int) int {\n\treturn a - b\n}",
- summary: "Add Subtract function"
- }
- ]
-})
-
-3.)
-If the current file is:
-`+"```"+`
-package main
-
-import "fmt"
-
-func main() {
- fmt.Println("Hello, world!")
-}
-`+"```"+`
-
-And the previous response was:
-
->>>
-You can change the main.go file to print "I love you!" in addition to "Hello, world!".:
-
-- main.go:
-`+"```"+`
-func main() {
- fmt.Println("Hello, world!")
- fmt.Println("I love you!")
-}
-`+"```"+`
-<<<
-
-Then you would call the 'writeReplacements' function like this:
-
-writeReplacements({
- replacements: [
- {
- old: "fmt.Println(\"Hello, world!\")",
- new: "fmt.Println(\"Hello, world!\")\n\tfmt.Println(\"I love you!\")",
- summary: "Also print \"I love you!\""
- }
- ]
-})
-
-[END INSTRUCTIONS]
-%s
-`, filePath, currentStatePrompt)
-}
-
-func GetBuildCurrentStatePrompt(filePath, currentState string) string {
- if currentState == "" {
- return ""
- }
- return fmt.Sprintf("\n\n**Current state of file for %s:**\n```\n%s\n```", filePath, currentState) + "\n\n"
-}
-
-var ReplaceFn = openai.FunctionDefinition{
- Name: "writeReplacements",
- Parameters: &jsonschema.Definition{
- Type: jsonschema.Object,
- Properties: map[string]jsonschema.Definition{
- "replacements": {
- Type: jsonschema.Array,
- Description: "A list of replacements to apply to the file",
- Items: &jsonschema.Definition{
- Type: jsonschema.Object,
- Properties: map[string]jsonschema.Definition{
- "old": {
- Type: jsonschema.String,
- Description: "The old text to replace. Must be an exact substring of the current state of the file.",
- },
- "new": {
- Type: jsonschema.String,
- Description: "The new text to replace it with from the changes suggested in the previous response.",
- },
- "summary": {
- Type: jsonschema.String,
- Description: "A brief 1 line summary of the change.",
- },
- },
- Required: []string{"old", "new", "summary"},
- },
- },
- },
- Required: []string{"replacements"},
- },
-}
-
-func GetReplacePrompt(filePath string) string {
- return fmt.Sprintf(`
- Based on your instructions, apply the changes from the plan to %s. Call the 'writeReplacements' function with a JSON array of replacements to apply to the file from your previous response.`, filePath)
-}
-
-func GetCorrectReplacementPrompt(replacements []*shared.Replacement, currentState string) (string, error) {
- msg := "There were errors with the replacements you suggested."
- for i, replacement := range replacements {
-
- if replacement.Failed {
- bytes, err := json.Marshal(replacement)
- if err != nil {
- return "", fmt.Errorf("failed to marshal replacement: %w", err)
- }
-
- msg += fmt.Sprintf("\n- The replacement at index %d was invalid. The replacement you suggested was:\n\n```%s```\n\n", i, string(bytes))
-
- msg += fmt.Sprintf("\n- The string `%s` (which you set for the 'old' key of this replacement) was not found in the current state of the file.", replacement.Old)
- }
-
- }
- msg += "\n\nPlease review these errors and try again to call the 'writeReplacements' function with corrected replacements. Pay special attention to any special characters in the strings, extra spaces, or anything else that might cause the strings to not match exactly. You MUST call 'writeReplacements' with an updated list of replacements. Don't call any other function, produce any other output, or call 'writeReplacements' with the same list of replacements as before--it must be called with an updated list of replacements to fix the errors."
-
- return msg, nil
-}
diff --git a/server/model/prompts/create.go b/server/model/prompts/create.go
deleted file mode 100644
index 421cd8e8..00000000
--- a/server/model/prompts/create.go
+++ /dev/null
@@ -1,69 +0,0 @@
-package prompts
-
-import (
- "fmt"
-
- "github.com/plandex/plandex/shared"
-)
-
-const SysCreate = Identity + ` A plan is a set of files with an attached context.` +
-
- "Your instructions:\n\n```\n" +
-
- `First, decide if the user has a task for you.
-
- If the user doesn't have a task and is just asking a question or chatting, ignore the rest of the instructions below, and respond to the user in chat form. You can make reference to the context to inform your response, and you can include code in your response, but don't include labelled code blocks as described below, since that indicates that a plan is being created.
-
- If the user does have a task, create a plan for the task based on user-provided context using the following steps:
-
- 1. Decide whether you've been given enough information and context to make a good plan.
- - In general, lean toward giving the plan a try with whatever information and context you've been provided. That said, if you have very little to go on or something is clearly missing or unclear, ask the user for more information or context.
- a. If you don't have enough information or context to make a good plan:
- - Explicitly say "I need more information or context to make a plan for this task."
- - Ask the user for more information or context and stop there.
-
- 2. Decide whether this task is small enough to be completed in a single response.
- a. If so, write out the code to complete the task. Include only lines that will change and lines that are necessary to know where the changes should be applied. Precede the code block with the file path like this '- file_path:'--for example:
- - src/main.rs:
- - lib/term.go:
- - main.py:
- File paths should always come *before* the opening triple backticks of a code block. They should *not* be included in the code block itself.
- File paths should appear *immediately* before the opening triple backticks of a code block. There should be *no other lines* between the file path and the code block. Any explanations should come either *before the file path or after the code block.*
- b. If not:
- - Explicitly say "Let's break up this task."
- - Divide the task into smaller subtasks and list them in a numbered list. Stop there.
-
- Always precede code blocks in a plan with the file path as described above in 2a. Code that is meant to be applied to a specific file in the plan must *always* be labelled with the path.
-
- If code is being included for explanatory purposes and is not meant to be applied to a specific file, you MUST NOT label the code block in the format described in 2a. Instead, output the code without a label.
-
- Every file you reference in a plan should either exist in the context directly or be a new file that will be created in the same base directory a file in the context. For example, if there is a file in context at path 'lib/term.go', you can create a new file at path 'lib/utils_test.go' but *not* at path 'src/lib/term.go'. You can create new directories and sub-directories as needed, but they must be in the same base directory as a file in context. Don't ask the user to create new files or directories--you must do that yourself.
-
- For code in markdown blocks, always include the language name after the opening triple backticks.
-
- Don't include unnecessary comments in code. Lean towards no comments as much as you can. If you must include a comment to make the code understandable, be sure it is concise. Don't use comments to communicate with the user.
-
- An exception to the above instructions on comments are if a file block is empty because you removed everything in it. In that case, leave a brief one-line comment starting with 'Plandex: removed' that says what was removed so that the file block isn't empty.
-
- In code blocks, include the *minimum amount of code* necessary to describe the suggested changes. Include only lines that are changing and and lines that make it clear where the change should be applied. You can use comments like "// rest of the function..." or "// rest of the file..." to help make it clear where changes should be applied. You *must not* include large sections of the original file unless it helps make the suggested changes clear.
-
- Don't try to do too much in a single response. The code you include in file blocks will be parsed into replacements by an AI, and then applied to the file. If you include too much code, it may not be parsed correctly or the changes may be difficult to apply.
-
- If plan requires a number of small changes, then multiple changes can be included single response, but they should be broken up into separate file blocks.
-
- For changes that are larger or more complex, only include one change per response.
-
- In general, don't ask the user to take an action that you are able to do. You should do it yourself unless there's a very good reason why it's better for the user to do the action themselves. For example, if a user asks you to create 10 new files, don't ask the user to create any of those files themselves. As long as you have enough information to create them correctly, you should create them all.
-
- At the end of a plan, you can suggest additional iterations to make the plan better. You can also ask the user to load more files or information into context if it would help you make a better plan.
-
- Be aware that since the plan started, the context may have been updated. It may have been updated by the user implementing your suggestions, by the user implementing their own work, or by the user adding more files or information to context. Be sure to consider the current state of the context when continuing with the plan, and whether the plan needs to be updated to reflect the latest context. For example, if you are working on a plan that has been broken up into subtasks, and you've reached the point of implementing a particular subtask, first consider whether the subtask is still necessary looking at the files in context. If it has already been implemented or is no longer necessary, say so, revise the plan if needed, and move on. Otherwise, implement the subtask.
- ` +
- "\n```\n\n" +
- "User-provided context:"
-
-var CreateSysMsgNumTokens, _ = shared.GetNumTokens(SysCreate)
-
-const PromptWrapperFormatStr = "The user's latest prompt:\n```\n%s\n```\n\n Please respond according to the 'Your instructions' section above. If you're making a plan, remember to precede code blocks with the file path *exactly* as described in 2a, and do not use any other formatting for file paths."
-
-var PromptWrapperTokens, _ = shared.GetNumTokens(fmt.Sprintf(PromptWrapperFormatStr, ""))
diff --git a/server/model/prompts/describe.go b/server/model/prompts/describe.go
deleted file mode 100644
index 35b69d72..00000000
--- a/server/model/prompts/describe.go
+++ /dev/null
@@ -1,22 +0,0 @@
-package prompts
-
-import (
- "github.com/sashabaranov/go-openai"
- "github.com/sashabaranov/go-openai/jsonschema"
-)
-
-const SysDescribe = "You are an AI parser. You turn an AI's plan for a programming task into a structured description. You call the 'describePlan' function with a valid JSON object that includes the 'commitMsg' key. Only call the 'describePlan' function in your response. Don't call any other function."
-
-var DescribePlanFn = openai.FunctionDefinition{
- Name: "describePlan",
- Parameters: &jsonschema.Definition{
- Type: jsonschema.Object,
- Properties: map[string]jsonschema.Definition{
- "commitMsg": {
- Type: jsonschema.String,
- Description: "A good, succinct commit message for the changes proposed.",
- },
- },
- Required: []string{"commitMsg"},
- },
-}
diff --git a/server/model/prompts/name.go b/server/model/prompts/name.go
deleted file mode 100644
index 7570e43a..00000000
--- a/server/model/prompts/name.go
+++ /dev/null
@@ -1,30 +0,0 @@
-package prompts
-
-import (
- "github.com/sashabaranov/go-openai"
- "github.com/sashabaranov/go-openai/jsonschema"
-)
-
-type PlanNameRes struct {
- PlanName string `json:"PlanName"`
-}
-
-const SysPlanName = "You are an AI namer that creates a name for the plan. Most plans will be related to software development. Call the 'namePlan' function with a valid JSON object that includes the 'planName' key. Only call the 'namePlan' function in your response. Don't call any other function."
-
-var PlanNameFn = openai.FunctionDefinition{
- Name: "namePlan",
- Parameters: &jsonschema.Definition{
- Type: jsonschema.Object,
- Properties: map[string]jsonschema.Definition{
- "planName": {
- Type: jsonschema.String,
- Description: "A *short* lowercase file name for the plan content. Use dashes as word separators. No spaces, numbers, or special characters. **2-3 words max**.",
- },
- },
- Required: []string{"planName"},
- },
-}
-
-func GetPlanNamePrompt(text string) string {
- return SysPlanName + "\n\nContent:\n" + text
-}
diff --git a/server/model/prompts/shared.go b/server/model/prompts/shared.go
deleted file mode 100644
index 12bb9a65..00000000
--- a/server/model/prompts/shared.go
+++ /dev/null
@@ -1,3 +0,0 @@
-package prompts
-
-const Identity = "You are Plandex, an AI programming and system administration assistant. You and the programmer collaborate to create a 'plan' for the task at hand."
diff --git a/server/model/prompts/summary.go b/server/model/prompts/summary.go
deleted file mode 100644
index 263dcc86..00000000
--- a/server/model/prompts/summary.go
+++ /dev/null
@@ -1,51 +0,0 @@
-package prompts
-
-import (
- "github.com/sashabaranov/go-openai"
- "github.com/sashabaranov/go-openai/jsonschema"
-)
-
-const SysShortSummary = "You are an AI summarizer that summarizes text, including programs, documentation, websites, and more. Most text will be related to software development."
-
-var ShortSummaryFn = openai.FunctionDefinition{
- Name: "summarize",
- Parameters: &jsonschema.Definition{
- Type: jsonschema.Object,
- Properties: map[string]jsonschema.Definition{
- "summary": {
- Type: jsonschema.String,
- Description: "A brief summary of the text. A few sentences at most",
- },
- },
- Required: []string{"summary"},
- },
-}
-
-func GetShortSummaryPrompt(text string) string {
- return `
- Please summarize the text below using the 'summarize' function. Call 'summarize' with valid JSON that includes the 'summary' key. Only call the 'summarize' function in your reponse. Don't call any other function.
-
- Text:
-
- ` + text
-}
-
-const PlanSummary = `
-Based on the conversation so far, make a summary of the current state of the plan.
-
-- It should begin with a summary of the user's messages, with particular focus any tasks they have given you. Your summary of the tasks should reflect the latest version of each task--if they have changed over time, summarize the latest state of each task that was given and omit anything that is now obsolete. Condense this information as much as possible while still being clear and retaining the meaning of the original messages. If the user has sent messages like 'continue to the next step of the plan' that don't contain any new information relevant to the plan, you should omit them.
-
-- Next, if the plan includes a statement from the assistant to the effect of "I will break this large task into subtasks" and the plan has been broken down into subtasks, include those subtasks in the summary as a numbered list. Condense these as much as possible while still being clear and retaining the meaning of each subtask. At the end of the list, state which subtask is currently being worked on (unless they are all finished, in which case state that they are all finished).
-
-- Last, summarize the latest version of the plan and any changes you have suggested. If the some of the older changes have been overridden by newer changes, you should only include the newest changes and omit the older ones.
-
-- If your responses include code blocks labelled with file paths, include the latest state of your modifications to each file's code and label them with file paths in the same format as the original messages. Do not make new changes to the plan or to suggested code changes in your summary.
-
-- If code blocks can be converted to a textual summary without losing meaning or precision, summarize them. Otherwise, leave them as code.
-
-- If part of the plan has already been summarized, update the summary based on the latest messages while continuing the follow the above guidelines.
-
-- The summary should condense the conversation to save tokens, but still contain enough information about the state of the plan to be actionable and apply the suggested changes.
-
-Output only the summary of the current state of the plan and nothing else.
-`
diff --git a/server/model/summarize.go b/server/model/summarize.go
deleted file mode 100644
index 2cac6fae..00000000
--- a/server/model/summarize.go
+++ /dev/null
@@ -1,70 +0,0 @@
-package model
-
-import (
- "context"
- "fmt"
- "plandex-server/db"
- "plandex-server/model/prompts"
- "time"
-
- "github.com/sashabaranov/go-openai"
-)
-
-type PlanSummaryParams struct {
- Conversation []openai.ChatCompletionMessage
- LatestConvoMessageId string
- LatestConvoMessageCreatedAt time.Time
- NumMessages int
- OrgId string
- PlanId string
-}
-
-func PlanSummary(params PlanSummaryParams) (*db.ConvoSummary, error) {
- messages := []openai.ChatCompletionMessage{
- {
- Role: openai.ChatMessageRoleSystem,
- Content: prompts.Identity,
- },
- }
-
- messages = append(messages, params.Conversation...)
-
- messages = append(messages, openai.ChatCompletionMessage{
- Role: openai.ChatMessageRoleUser,
- Content: prompts.PlanSummary,
- })
-
- // fmt.Println("summarizing messages:")
- // spew.Dump(messages)
-
- resp, err := Client.CreateChatCompletion(
- context.Background(),
- openai.ChatCompletionRequest{
- Model: PlanSummaryModel,
- Messages: messages,
- },
- )
-
- if err != nil {
- fmt.Println("PlanSummary err:", err)
-
- return nil, err
- }
-
- if len(resp.Choices) == 0 {
- return nil, fmt.Errorf("no response from GPT")
- }
-
- content := resp.Choices[0].Message.Content
-
- return &db.ConvoSummary{
- OrgId: params.OrgId,
- PlanId: params.PlanId,
- Summary: content,
- Tokens: resp.Usage.CompletionTokens,
- LatestConvoMessageId: params.LatestConvoMessageId,
- LatestConvoMessageCreatedAt: params.LatestConvoMessageCreatedAt,
- NumMessages: params.NumMessages,
- }, nil
-
-}
diff --git a/server/routes.go b/server/routes.go
deleted file mode 100644
index ca553915..00000000
--- a/server/routes.go
+++ /dev/null
@@ -1,73 +0,0 @@
-package main
-
-import (
- "fmt"
- "net/http"
- "plandex-server/handlers"
-
- "github.com/gorilla/mux"
-)
-
-func InitRoutes() *mux.Router {
- r := mux.NewRouter()
-
- r.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
- 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")
-
- 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", handlers.ListPlansHandler).Methods("GET")
- r.HandleFunc("/projects/{projectId}/plans/archive", handlers.ListArchivedPlansHandler).Methods("GET")
- r.HandleFunc("/projects/{projectId}/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}/tell", handlers.TellPlanHandler).Methods("POST")
- r.HandleFunc("/plans/{planId}/build", handlers.BuildPlanHandler).Methods("PATCH")
- r.HandleFunc("/plans/{planId}/connect", handlers.ConnectPlanHandler).Methods("PATCH")
- r.HandleFunc("/plans/{planId}/stop", handlers.StopPlanHandler).Methods("DELETE")
-
- r.HandleFunc("/plans/{planId}/current_plan", handlers.CurrentPlanHandler).Methods("GET")
- r.HandleFunc("/plans/{planId}/apply", handlers.ApplyPlanHandler).Methods("PATCH")
- r.HandleFunc("/plans/{planId}/archive", handlers.ArchivePlanHandler).Methods("PATCH")
- r.HandleFunc("/plans/{planId}/reject_all", handlers.RejectAllChangesHandler).Methods("PATCH")
- r.HandleFunc("/plans/{planId}/results/{resultId}/reject", handlers.RejectResultHandler).Methods("PATCH")
- r.HandleFunc("/plans/{planId}/results/{resultId}/replacements/{replacementId}/reject", handlers.RejectReplacementHandler).Methods("PATCH")
-
- r.HandleFunc("/plans/{planId}/context", handlers.ListContextHandler).Methods("GET")
- r.HandleFunc("/plans/{planId}/context", handlers.LoadContextHandler).Methods("POST")
- r.HandleFunc("/plans/{planId}/context", handlers.UpdateContextHandler).Methods("PUT")
- r.HandleFunc("/plans/{planId}/context", handlers.DeleteContextHandler).Methods("DELETE")
-
- r.HandleFunc("/plans/{planId}/convo", handlers.ListConvoHandler).Methods("GET")
- r.HandleFunc("/plans/{planId}/rewind", handlers.RewindPlanHandler).Methods("PATCH")
- r.HandleFunc("/plans/{planId}/logs", handlers.ListLogsHandler).Methods("GET")
-
- return r
-}
diff --git a/server/types/active_plan.go b/server/types/active_plan.go
deleted file mode 100644
index 16b3eb4f..00000000
--- a/server/types/active_plan.go
+++ /dev/null
@@ -1,74 +0,0 @@
-package types
-
-import (
- "context"
- "plandex-server/db"
-
- "github.com/google/uuid"
-)
-
-type ActivePlan struct {
- Prompt string
- StreamCh chan string
- StreamDoneCh chan error
- Ctx context.Context
- CancelFn context.CancelFunc
- Contexts []*db.Context
- ContextsByPath map[string]*db.Context
- Content string
- NumTokens int
- PromptMessageNum int
- AssistantMessageId string
- Files []string
- BuildBuffers map[string]string
- BuiltFiles map[string]bool
- subscriptions map[string]chan string
-}
-
-func NewActivePlan(prompt string) *ActivePlan {
- ctx, cancel := context.WithCancel(context.Background())
-
- active := ActivePlan{
- Prompt: prompt,
- StreamCh: make(chan string),
- StreamDoneCh: make(chan error),
- Ctx: ctx,
- CancelFn: cancel,
- Files: []string{},
- BuiltFiles: map[string]bool{},
- Contexts: []*db.Context{},
- ContextsByPath: map[string]*db.Context{},
- BuildBuffers: map[string]string{},
- subscriptions: map[string]chan string{},
- }
-
- go func() {
- for {
- select {
- case <-active.Ctx.Done():
- return
- case msg := <-active.StreamCh:
- for _, ch := range active.subscriptions {
- ch <- msg
- }
- }
- }
- }()
-
- return &active
-}
-
-func (ap *ActivePlan) BuildFinished() bool {
- return len(ap.Files) == len(ap.BuiltFiles)
-}
-
-func (ap *ActivePlan) Subscribe() (string, chan string) {
- id := uuid.New().String()
- ch := make(chan string)
- ap.subscriptions[id] = ch
- return id, ch
-}
-
-func (ap *ActivePlan) Unsubscribe(id string) {
- delete(ap.subscriptions, id)
-}
diff --git a/server/types/auth.go b/server/types/auth.go
deleted file mode 100644
index 5b4dd530..00000000
--- a/server/types/auth.go
+++ /dev/null
@@ -1,18 +0,0 @@
-package types
-
-import "plandex-server/db"
-
-type ServerAuth struct {
- AuthToken *db.AuthToken
- User *db.User
- OrgId string
- Permissions map[string]bool
-}
-
-func (a *ServerAuth) HasPermission(permission string) bool {
- if a.Permissions == nil {
- return false
- }
-
- return a.Permissions[permission]
-}
diff --git a/server/types/model.go b/server/types/model.go
deleted file mode 100644
index c2f1255b..00000000
--- a/server/types/model.go
+++ /dev/null
@@ -1,11 +0,0 @@
-package types
-
-import "github.com/plandex/plandex/shared"
-
-type StreamedFile struct {
- Content string `json:"content"`
-}
-
-type StreamedReplacements struct {
- Replacements []*shared.Replacement `json:"replacements"`
-}
diff --git a/server/types/reply.go b/server/types/reply.go
deleted file mode 100644
index f04b5b7e..00000000
--- a/server/types/reply.go
+++ /dev/null
@@ -1,150 +0,0 @@
-package types
-
-import (
- "strings"
-)
-
-type replyInfo struct {
- lines []string
- currentFileLines []string
- lineIndex int
- maybeFilePath string
- currentFilePath string
- files map[string]bool
- fileContents map[string]string
- numTokens int
- numTokensByFile map[string]int
-}
-
-func NewReplyInfo() *replyInfo {
- info := &replyInfo{
- lines: []string{""},
- currentFileLines: []string{},
- files: make(map[string]bool),
- fileContents: make(map[string]string),
- numTokensByFile: make(map[string]int),
- }
-
- return info
-}
-
-func (r *replyInfo) AddToken(token string, addToTotal bool) {
- // fmt.Println("Adding chunk:", strconv.Quote(chunk)) // Logging the chunk that's being processed
-
- hasNewLine := false
- nextChunk := ""
-
- if addToTotal {
- r.numTokens++
-
- if r.currentFilePath != "" {
- r.numTokensByFile[r.currentFilePath]++
- }
- }
-
- if token == "\n" {
- // fmt.Println("Chunk is \\n, adding new line")
- r.lines = append(r.lines, "")
- hasNewLine = true
- r.lineIndex++
- } else {
- chunkLines := strings.Split(token, "\n")
-
- // fmt.Println("Chunk lines:", len(chunkLines))
-
- currentLine := r.lines[r.lineIndex]
- currentLine += chunkLines[0]
-
- // fmt.Println("Current line:", strconv.Quote(currentLine))
- r.lines[r.lineIndex] = currentLine
-
- if len(chunkLines) > 1 {
- r.lines = append(r.lines, chunkLines[1])
- r.lineIndex++
- hasNewLine = true
-
- if len(chunkLines) > 2 {
- tail := chunkLines[2:]
- nextChunk = "\n" + strings.Join(tail, "\n")
- defer func() {
- // fmt.Println("Recursive add next queued chunk:", strconv.Quote(nextChunk))
- r.AddToken(nextChunk, false)
- }()
- }
- }
- }
-
- if r.lineIndex == 0 || !hasNewLine {
- return
- }
-
- prevFullLine := r.lines[r.lineIndex-1]
- // fmt.Println("Previous full line:", strconv.Quote(prevFullLine)) // Logging the full line that's being checked
-
- prevFullLineTrimmed := strings.TrimSpace(prevFullLine)
-
- if r.maybeFilePath != "" {
- // fmt.Println("Maybe file path is:", r.maybeFilePath) // Logging the maybeFilePath
- if strings.HasPrefix(prevFullLineTrimmed, "```") {
- r.currentFilePath = r.maybeFilePath
- r.maybeFilePath = ""
- r.currentFileLines = []string{}
- // fmt.Println("Confirmed file path:", r.currentFilePath) // Logging the confirmed file path
- return
- } else if prevFullLineTrimmed != "" {
- // turns out previous maybeFilePath was not a file path since there's a non-empty line before finding opening ticks
- r.maybeFilePath = ""
- }
- }
-
- if r.currentFilePath == "" {
- // fmt.Println("Current file path is empty--checking for possible file path...")
-
- var gotPath string
- if (strings.HasPrefix(prevFullLineTrimmed, "-")) || strings.HasPrefix(prevFullLineTrimmed, "-file:") || strings.HasPrefix(prevFullLineTrimmed, "- file:") || (strings.HasPrefix(prevFullLineTrimmed, "**") && strings.HasSuffix(prevFullLineTrimmed, "**")) {
- p := strings.TrimPrefix(prevFullLineTrimmed, "**")
- p = strings.TrimPrefix(p, "-")
- p = strings.TrimSpace(p)
- p = strings.TrimSuffix(p, "**")
- p = strings.TrimPrefix(p, "file:")
- p = strings.TrimSuffix(p, ":")
- p = strings.TrimSpace(p)
- gotPath = p
- } else {
- // fmt.Println("No possible file path detected.", strconv.Quote(prevFullLineTrimmed))
- }
-
- if gotPath != "" {
- // fmt.Println("Detected possible file path:", gotPath) // Logging the possible file path
-
- if r.maybeFilePath == "" {
- r.maybeFilePath = gotPath
- } else {
- r.maybeFilePath = gotPath
- }
- }
- } else {
- if strings.HasPrefix(prevFullLineTrimmed, "```") {
- r.currentFilePath = ""
- // fmt.Println("Exited file block.")
- } else {
- r.files[r.currentFilePath] = true
- r.fileContents[r.currentFilePath] += prevFullLine + "\n"
- r.currentFileLines = append(r.currentFileLines, prevFullLine)
-
- // r.contentByFile[r.currentFilePath] += prevFullLine + "\n"
- // fmt.Printf("Added %d tokens to %s\n", tokens, r.currentFilePath) // Logging token addition
- }
- }
-}
-
-func (r *replyInfo) FinishAndRead() ([]string, map[string]string, map[string]int, int) {
- r.AddToken("\n", false)
-
- files := make([]string, 0, len(r.files))
- for file := range r.files {
- files = append(files, file)
- }
-
- return files, r.fileContents, r.numTokensByFile, r.numTokens
-}
diff --git a/server/types/reply_test.go b/server/types/reply_test.go
deleted file mode 100644
index 4d51aea7..00000000
--- a/server/types/reply_test.go
+++ /dev/null
@@ -1,108 +0,0 @@
-package types
-
-import (
- "fmt"
- "os"
- "testing"
-)
-
-type TestExample struct {
- N int
- TokensByFilePath map[string]int
-}
-
-// These aren't the real number of tokens
-// We're just splitting the file into chunks of 5 characters to simulate tokens
-var examples = []TestExample{
- {
- N: 1,
- TokensByFilePath: map[string]int{
- "cmd/checkout.go": 17,
- "cmd/apply.go": 41,
- },
- },
- {
- N: 2,
- TokensByFilePath: map[string]int{
- "cmd/context_rm.go": 51,
- "cmd/context_update.go": 41,
- },
- },
- {
- N: 3,
- TokensByFilePath: map[string]int{
- "cmd/context_rm.go": 51,
- "cmd/context_update.go": 41,
- },
- },
- {
- N: 4,
- TokensByFilePath: map[string]int{
- "server/types/section.go": 11,
- },
- },
- {
- N: 5,
- TokensByFilePath: map[string]int{
- "shared/types.go": 5,
- "cli/lib/conversation.go": 8,
- },
- },
- {
- N: 6,
- TokensByFilePath: map[string]int{
- "server/model/proposal/create.go": 32,
- },
- },
-}
-
-func TestReplyTokenCounter(t *testing.T) {
-
- for _, example := range examples {
- filePath := fmt.Sprintf("reply_test_examples/%d.md", example.N)
- fmt.Println(filePath)
-
- bytes, err := os.ReadFile(filePath)
- if err != nil {
- t.Error(err)
- }
-
- content := string(bytes)
-
- tokenSize := 5
-
- counter := NewReplyInfo()
-
- totalTokens := 0
- for i := 0; i < len(content); {
- end := i + tokenSize
- if end > len(content) {
- end = len(content)
- }
- chunk := content[i:end]
- counter.AddToken(chunk, true)
- totalTokens++
- i = end
- }
-
- files, fileContents, tokensByFilePath, totalCounted := counter.FinishAndRead()
-
- fmt.Printf("Total tokens counted: %d\n", totalCounted)
- fmt.Printf("%d files: %v\n", len(files), files)
- fmt.Printf("%d file content: %v\n", len(fileContents), fileContents)
- fmt.Println("Tokens by file path:")
- for filePath, tokens := range tokensByFilePath {
- fmt.Printf("%s: %d\n", filePath, tokens)
- }
-
- if totalCounted != totalTokens {
- t.Errorf("Expected %d tokens, got %d", totalTokens, totalCounted)
- }
-
- for filePath, tokens := range example.TokensByFilePath {
- if tokensByFilePath[filePath] != tokens {
- t.Errorf("Expected %d tokens for %s", tokens, filePath)
- }
- }
- }
-}
diff --git a/server/types/reply_test_examples/1.md b/server/types/reply_test_examples/1.md
deleted file mode 100644
index 2f65daa9..00000000
--- a/server/types/reply_test_examples/1.md
+++ /dev/null
@@ -1,78 +0,0 @@
-Thank you for the update. In order to handle errors from the apply command execution, we need to modify the 'checkout' command and the 'apply' command and function.
-
-Follow the steps below:
-
-1. Modify the 'apply' function to return an error.
-2. Change 'apply' command invocation in 'checkout' function to handle the returned error.
-
-The code changes are as follows:
-
-- file: cmd/apply.go
-
-```go
-package cmd
-
-// ... other imports ...
-
-func init() {
- RootCmd.AddCommand(applyCmd)
-}
-
-var applyCmd = &cobra.Command{
- Use: "apply [name]",
- Short: "Apply a plan to the project",
- Args: cobra.MaximumNArgs(1),
- RunE: apply, // We use RunE instead of Run, to allow us to return an error from the apply function
-}
-
-func apply(cmd *cobra.Command, args []string) error {
-
- // ... rest of the code ...
-
- if err != nil {
- // Return error to the caller instead of directly logging it
- return fmt.Errorf("Error processing files: %v", err)
- }
-
- // ... rest of the code ...
-
- if err != nil {
- // Return error to the caller instead of directly logging it
- return fmt.Errorf("Error executing plan: %v", err)
- }
-
- if copiedAny || didExec {
- fmt.Println("Plan applied successfully!")
- } else {
- return fmt.Errorf("This plan has no changes to apply.")
- }
-
- return nil
-}
-
-// ... rest of the code ...
-```
-
-- file: cmd/checkout.go
-
-```go
-package cmd
-
-// ... other imports ...
-
-func checkout(cmd *cobra.Command, args []string) {
-
- // ... rest of the code ...
-
- err = apply(cmd, args)
-
- if err != nil {
- fmt.Fprintln(os.Stderr, "Error committing plan: ", err)
- return
- }
-
- // ... rest of the code ...
-}
-```
-
-Next, compile and run your application to verify that any error from the 'apply' command would be gracefully handled by the 'checkout' command. Changes have been made in such a way that 'apply' command can still work standalone, besides working in sync with 'checkout' command.
diff --git a/server/types/reply_test_examples/2.md b/server/types/reply_test_examples/2.md
deleted file mode 100644
index 6eace5c3..00000000
--- a/server/types/reply_test_examples/2.md
+++ /dev/null
@@ -1,101 +0,0 @@
-Sure, here's how you could structure your 'context rm' command and 'context update' command using placeholders for the 'lib' functions that will handle the actual removal and updating of contexts:
-
-**cmd/context_rm.go**
-
-```go
-
-package cmd
-
-import (
- "fmt"
- "log"
-
- "github.com/spf13/cobra"
-)
-
-// contextRmCmd represents the delete command
-var contextRmCmd = &cobra.Command{
- Use: "rm [context_name]",
- Aliases: []string{"delete"},
- Short: "",
- Long: ``,
- Run: contextRm,
-}
-
-func contextRm(cmd *cobra.Command, args []string) {
- all, err := cmd.Flags().GetBool("all")
-
- if err != nil {
- log.Fatal("Error parsing all flag: ", err)
- }
-
- if all {
- // Placeholder for lib function
- err = lib.RemoveAllContexts()
- if err != nil {
- log.Fatal("Error removing all contexts: ", err)
- }
- } else if len(args) > 0 {
- for _, contextName := range args {
- // Placeholder for lib function
- err = lib.RemoveContext(contextName)
- if err != nil {
- fmt.Printf("Error removing context '%s': %v\n", contextName, err)
- }
- }
- } else {
- fmt.Println("Please provide a context name or use the --all flag to remove all contexts.")
- }
-}
-
-func init() {
- contextCmd.AddCommand(contextRmCmd)
- contextRmCmd.Flags().BoolP("all", "a", false, "remove all contexts")
-}
-```
-
-**cmd/context_update.go**
-
-```go
-
-package cmd
-
-import (
- "fmt"
- "log"
-
- "github.com/spf13/cobra"
-)
-
-// contextUpdateCmd represents the context command
-var contextUpdateCmd = &cobra.Command{
- Use: "update [file-or-urls...]",
- Short: "A brief description of your command",
- Long: `A longer description that spans multiple lines and likely contains examples
-and usage of using your command. For example:
-
-Cobra is a CLI library for Go that empowers applications.
-This application is a tool to generate the needed files
-to quickly create a Cobra application.`,
- Run: func(cmd *cobra.Command, args []string) {
- if len(args) == 0 {
- fmt.Println("Please provide one or more files or URLs to update.")
- return
- }
-
- for _, arg := range args {
- // Placeholder for lib function
- err := lib.UpdateContext(arg)
- if err != nil {
- fmt.Printf("Error updating context for '%s': %v\n", arg, err)
- }
- }
- },
-}
-
-func init() {
- contextCmd.AddCommand(contextUpdateCmd)
-}
-```
-
-In your next iteration, you could implement the functions in 'lib' package such as `RemoveAllContexts`, `RemoveContext`, and `UpdateContext`.
diff --git a/server/types/reply_test_examples/3.md b/server/types/reply_test_examples/3.md
deleted file mode 100644
index 6eace5c3..00000000
--- a/server/types/reply_test_examples/3.md
+++ /dev/null
@@ -1,101 +0,0 @@
-Sure, here's how you could structure your 'context rm' command and 'context update' command using placeholders for the 'lib' functions that will handle the actual removal and updating of contexts:
-
-**cmd/context_rm.go**
-
-```go
-
-package cmd
-
-import (
- "fmt"
- "log"
-
- "github.com/spf13/cobra"
-)
-
-// contextRmCmd represents the delete command
-var contextRmCmd = &cobra.Command{
- Use: "rm [context_name]",
- Aliases: []string{"delete"},
- Short: "",
- Long: ``,
- Run: contextRm,
-}
-
-func contextRm(cmd *cobra.Command, args []string) {
- all, err := cmd.Flags().GetBool("all")
-
- if err != nil {
- log.Fatal("Error parsing all flag: ", err)
- }
-
- if all {
- // Placeholder for lib function
- err = lib.RemoveAllContexts()
- if err != nil {
- log.Fatal("Error removing all contexts: ", err)
- }
- } else if len(args) > 0 {
- for _, contextName := range args {
- // Placeholder for lib function
- err = lib.RemoveContext(contextName)
- if err != nil {
- fmt.Printf("Error removing context '%s': %v\n", contextName, err)
- }
- }
- } else {
- fmt.Println("Please provide a context name or use the --all flag to remove all contexts.")
- }
-}
-
-func init() {
- contextCmd.AddCommand(contextRmCmd)
- contextRmCmd.Flags().BoolP("all", "a", false, "remove all contexts")
-}
-```
-
-**cmd/context_update.go**
-
-```go
-
-package cmd
-
-import (
- "fmt"
- "log"
-
- "github.com/spf13/cobra"
-)
-
-// contextUpdateCmd represents the context command
-var contextUpdateCmd = &cobra.Command{
- Use: "update [file-or-urls...]",
- Short: "A brief description of your command",
- Long: `A longer description that spans multiple lines and likely contains examples
-and usage of using your command. For example:
-
-Cobra is a CLI library for Go that empowers applications.
-This application is a tool to generate the needed files
-to quickly create a Cobra application.`,
- Run: func(cmd *cobra.Command, args []string) {
- if len(args) == 0 {
- fmt.Println("Please provide one or more files or URLs to update.")
- return
- }
-
- for _, arg := range args {
- // Placeholder for lib function
- err := lib.UpdateContext(arg)
- if err != nil {
- fmt.Printf("Error updating context for '%s': %v\n", arg, err)
- }
- }
- },
-}
-
-func init() {
- contextCmd.AddCommand(contextUpdateCmd)
-}
-```
-
-In your next iteration, you could implement the functions in 'lib' package such as `RemoveAllContexts`, `RemoveContext`, and `UpdateContext`.
diff --git a/server/types/reply_test_examples/4.md b/server/types/reply_test_examples/4.md
deleted file mode 100644
index 041a5933..00000000
--- a/server/types/reply_test_examples/4.md
+++ /dev/null
@@ -1,26 +0,0 @@
-Yes, it does. Let's start by defining the types for `Section` and `SectionizeResponse`. For the Section type, we would need `name`, `content`, and an optional `subSections` field (to store any potentially nested sections).
-
-Here is the structure we can follow:
-
-1. A `Section` struct which contains a `Name` for the section, `Content` of the section, and a slice of `Subsection` for possible subsections in that section.
-2. A `SectionizeResponse` struct which contains a slice of `Section`.
-
-In `server/types/` directory, create a new `section.go` file.
-
-- server/types/section.go
-
-```go
-package types
-
-type Section struct {
- Name string
- Content string
- Subsection []Section
-}
-
-type SectionizeResponse struct {
- Sections []Section
-}
-```
-
-Once you have checked and confirmed this task, I will proceed to the next task which is creating a sectionize function in the server model.
diff --git a/server/types/reply_test_examples/5.md b/server/types/reply_test_examples/5.md
deleted file mode 100644
index f68314f6..00000000
--- a/server/types/reply_test_examples/5.md
+++ /dev/null
@@ -1,39 +0,0 @@
-Given that a summarization utility exists, the plan can be further simplified to utilize that. Here is the updated plan:
-
-1. Update the shared/types.go file to introduce a new boolean field indicating if a message has been summarized.
-
- - shared/types.go:
-
- ```go
- type ChatCompletionMessage struct {
- // existing fields
- ...
- Summarized bool
- }
- ```
-
-2. Modify the loadConversation function in cli/lib/conversation.go to take advantage of this new field.
-
- - cli/lib/conversation.go:
- ```go
- // modified part of loadConversation
- ...
- messages = append(messages, openai.ChatCompletionMessage{
- Role: currentRole,
- Content: loadContent(filePath, currentRole),
- Summarized: checkIfMsgSummarized(filePath, currentRole)
- })
- ...
- ```
- - Add the helper functions, checkIfMsgSummarized to check if a given message has already been summarized.
-
-3. In the server/model/proposal/create.go, handle the token limit error by introducing a summarization step.
-
- - Before calling the CreateChatCompletionStream, check the number of tokens in the request if they exceed the limit.
- - If they do, find the pairs of conversation and attempt to summarize starting from the second.
- - Use the model.Summarize() function provided by the system in step 2 above to handle this summarization.
-
-4. Lastly, handle the superfluous WriteHeader call.
- - For the superfluous WriteHeader call, ensure that all response modifications (like setting headers) are made before calling WriteHeader() and before writing to the response body.
-
-Note: It's still necessary to track which parts of the conversation have already been summarized and avoid summarizing them again if the token limit is still exceeded. This can be achieved by storing a "summarized" flag in each chat message (ChatCompletionMessage).
diff --git a/server/types/reply_test_examples/6.md b/server/types/reply_test_examples/6.md
deleted file mode 100644
index 979f60e3..00000000
--- a/server/types/reply_test_examples/6.md
+++ /dev/null
@@ -1,50 +0,0 @@
-In the following implementation for error handling and conversation summarization in `server/model/proposal/create.go`, the changes will help anticipate any token limit errors. After collecting and formatting all the necessary context, we will check if the token number exceeds the permitted limit. If so, we will initialize a process for summarizing conversation pairs.
-
-Changes will include:
-
-- A check for the token limit before calling `CreateChatCompletionStream`
-- A mechanism to iterate through conversation pairs for summarization
-- Recursive calls of `CreateProposal` with summarized conversation, if necessary
-
--server/model/proposal/create.go:
-
-```go
-// Add this at the start of the CreateProposal function
-const maxTokens = 8192 // The maximum tokens allowed by the model
-
-...
-
-// After preparation of the main conversation context, we add checks for tokens
-tokenNumbers := GetTokenNumber(messages) // Assuming you have a function for this
-
-if tokenNumbers > maxTokens {
-
- // Iterate the Conversation pairs
- for i := 1; i < len(req.Conversation)-1; i++ {
-
- // Check if the assistant's part has been summarized before
- if req.Conversation[i].Role == openai.ChatMessageRoleAssistant && !req.Conversation[i].Summarized {
- // Summarize the conversation, assuming we have a function Summarize() returning summarized text
- summarizedContent := Summarize(req.Conversation[i].Content)
- req.Conversation[i].Content = summarizedContent
- req.Conversation[i].Summarized = true // Mark the message as summarized
- break
- }
- }
- // Recursive call to CreateProposal after summarizing
- err := CreateProposal(req, onStream)
- if err != nil {
- return fmt.Errorf("Error recreating proposal: %s\n", err)
- }
-}
-
-...
-
-// Proceed the rest of the function as usual
-```
-
-This block of code handles the error arising from exceeding the maximum tokens supported by the model. If the tokens exceeded are detected, we start the process of summarizing conversation pairs till we are within allowed token limits. This is implemented via a recursive call to `CreateProposal`.
-
-Lastly, you should address the "superfluous response.WriteHeader call" error. This issue is usually due to an unnecessary double setting of headers in HTTP responses - HTTP headers should only be written once. The fix would involve a careful review of your HTTP response handling process ensuring that the response's headers aren't set after `WriteHeader()` has been called or body written into.
-
-Please integrate these changes into your respective function to handle the errors as described. Additional iterations might be required to fine-tune and resolve adjacent issues arising from these changes. Please also ensure your token counting and text summarization functions are accurate and performant as they play a crucial role in this error handling process.
diff --git a/server/types/safe_map.go b/server/types/safe_map.go
deleted file mode 100644
index eda9cf71..00000000
--- a/server/types/safe_map.go
+++ /dev/null
@@ -1,56 +0,0 @@
-package types
-
-import "sync"
-
-type SafeMap[V any] struct {
- items map[string]V
- mu sync.Mutex
-}
-
-func NewSafeMap[V any]() *SafeMap[V] {
- return &SafeMap[V]{items: make(map[string]V)}
-}
-
-func (sm *SafeMap[V]) Get(key string) V {
- sm.mu.Lock()
- defer sm.mu.Unlock()
- return sm.items[key]
-}
-
-func (sm *SafeMap[V]) Set(key string, value V) {
- sm.mu.Lock()
- defer sm.mu.Unlock()
- sm.items[key] = value
-}
-
-func (sm *SafeMap[V]) Delete(key string) {
- sm.mu.Lock()
- defer sm.mu.Unlock()
- delete(sm.items, key)
-}
-
-func (sm *SafeMap[V]) Update(key string, fn func(V)) {
- sm.mu.Lock()
- defer sm.mu.Unlock()
- item := sm.items[key]
- fn(item)
- sm.items[key] = item
-}
-
-func (sm *SafeMap[V]) Items() map[string]V {
- sm.mu.Lock()
- defer sm.mu.Unlock()
- return sm.items
-}
-
-func (sm *SafeMap[V]) Keys() []string {
- sm.mu.Lock()
- defer sm.mu.Unlock()
- keys := make([]string, len(sm.items))
- i := 0
- for k := range sm.items {
- keys[i] = k
- i++
- }
- return keys
-}