Open source AI coding agent. Designed for large projects and real world tasks.
Go aiai-agentsai-developer-toolsai-toolsclicommand-linedeveloper-toolsgitgolanggpt-4llmopenaipolyglot-programmingterminalterminal-basedterminal-ui
lotsa updates. getting ready to rework updates
Dane Schneidere0fc89cb4c88
diff --git a/cli/cmd/convo.go b/cli/cmd/convo.goindex 590d4f26..a1f889bc 100644--- a/cli/cmd/convo.go+++ b/cli/cmd/convo.go@@ -78,11 +78,10 @@ func convo(cmd *cobra.Command, args []string) {return}- fmt.Print(markdownString)+ output :=+ fmt.Sprintf("\n%s", markdownString) ++ lib.GetDivisionLine() ++ color.New(color.Bold, color.FgCyan).Sprint(" Conversation size β") + fmt.Sprintf(" %d πͺ", totalTokens) + "\n\n"- fmt.Println(lib.GetDivisionLine())- fmt.Println()-- fmt.Println(color.New(color.Bold, color.FgCyan).Sprint(" Conversation size β") + fmt.Sprintf(" %d πͺ", totalTokens))- fmt.Println()+ lib.PageOutputReverse(output)}diff --git a/cli/cmd/diffs.go b/cli/cmd/diffs.goindex 38b7156c..16056e65 100644--- a/cli/cmd/diffs.go+++ b/cli/cmd/diffs.go@@ -99,7 +99,7 @@ func showDiffs() error {fmt.Println(string(output))}- err = lib.CopyDir(lib.PlanFilesDir, tempDir)+ err = lib.CopyDir(lib.DraftFilesDir, tempDir)if err != nil {return fmt.Errorf("error copying files to temp directory: %v", err)}diff --git a/cli/cmd/load.go b/cli/cmd/load.goindex 7383e627..a4cb2658 100644--- a/cli/cmd/load.go+++ b/cli/cmd/load.go@@ -1,7 +1,6 @@package cmdimport (- "fmt""plandex/lib""plandex/types"@@ -36,6 +35,5 @@ func contextLoad(cmd *cobra.Command, args []string) {NamesOnly: namesOnly,})- fmt.Println()lib.PrintCmds("", "ls", "tell")}diff --git a/cli/cmd/log.go b/cli/cmd/log.goindex 1d619dd0..cf38cd41 100644--- a/cli/cmd/log.go+++ b/cli/cmd/log.go@@ -1 +1,49 @@package cmd++import (+ "fmt"+ "os"+ "plandex/lib"++ "github.com/spf13/cobra"+)++// logCmd represents the log command+var logCmd = &cobra.Command{+ Use: "log [scope]",+ Aliases: []string{"history"},+ Short: "Show plan history",+ Long: `Show plan history. Pass an optional scope to log only a specific part of the plan. Valid scopes are "convo", "context", and "draft". If no scope is passed, the history of the entire plan will be output.`,+ Args: cobra.MaximumNArgs(1),+ Run: runLog,+}++func init() {+ // Add log command+ RootCmd.AddCommand(logCmd)+}++func runLog(cmd *cobra.Command, args []string) {+ var dir string+ switch {+ case len(args) == 0:+ dir = lib.CurrentPlanDir+ case args[0] == "convo":+ dir = lib.ConversationSubdir+ case args[0] == "context":+ dir = lib.ContextSubdir+ case args[0] == "draft":+ dir = lib.DraftSubdir+ default:+ fmt.Fprint(os.Stderr, "Invalid scope. Valid scopes are 'convo', 'context', and 'draft'")+ os.Exit(1)+ }++ history, err := lib.GetGitCommitHistory(dir)+ if err != nil {+ fmt.Printf("Error: %v\n", err)+ return+ }++ lib.PageOutput(history)+}diff --git a/cli/cmd/ls.go b/cli/cmd/ls.goindex cdfa6591..804730d6 100644--- a/cli/cmd/ls.go+++ b/cli/cmd/ls.go@@ -44,29 +44,7 @@ func context(cmd *cobra.Command, args []string) {for i, part := range context {totalTokens += part.NumTokens- var icon string- var t string- id := part.Name- switch part.Type {- case shared.ContextFileType:- icon = "π"- t = "file"- id = part.FilePath- case shared.ContextURLType:- icon = "π"- t = "url"- case shared.ContextDirectoryTreeType:- icon = "π "- t = "tree"- id = part.FilePath- case shared.ContextNoteType:- icon = "βοΈ "- t = "note"- case shared.ContextPipedDataType:- icon = "βοΈ "- t = "piped"- }-+ t, icon := lib.GetContextTypeAndIcon(part)addedAt, err := time.Parse(shared.TsFormat, part.AddedAt)if err != nil {fmt.Fprintln(os.Stderr, "Error parsing time:", err)@@ -81,7 +59,7 @@ func context(cmd *cobra.Command, args []string) {row := []string{strconv.Itoa(i + 1),- " " + icon + " " + id,+ " " + icon + " " + part.Name,t,strconv.Itoa(part.NumTokens), //+ " πͺ",format.Time(addedAt),diff --git a/cli/cmd/pwd.go b/cli/cmd/pwd.gonew file mode 100644index 00000000..58e10c77--- /dev/null+++ b/cli/cmd/pwd.go@@ -0,0 +1,30 @@+package cmd++import (+ "fmt"+ "os"+ "path/filepath"+ "plandex/lib"++ "github.com/spf13/cobra"+)++var pwdCmd = &cobra.Command{+ Use: "pwd",+ Short: "Get the current plan directory.",+ Long: "Use it like this `cd $(plandex pwd)` to go to the current plan directory.",+ Run: pwd,+}++func init() {+ RootCmd.AddCommand(pwdCmd)+}++func pwd(cmd *cobra.Command, args []string) {+ if lib.CurrentPlanName == "" {+ fmt.Fprintf(os.Stderr, "No current plan.\n")+ os.Exit(1)+ }+ fmt.Println(filepath.Join(lib.PlandexDir, lib.CurrentPlanName))++}diff --git a/cli/cmd/rewind.go b/cli/cmd/rewind.goindex ecbb9554..9b8ba9fb 100644--- a/cli/cmd/rewind.go+++ b/cli/cmd/rewind.go@@ -1,17 +1,25 @@package cmdimport (+ "fmt"+ "os"+ "plandex/lib"+ "strconv"+"github.com/spf13/cobra")// rewindCmd represents the rewind commandvar rewindCmd = &cobra.Command{- Use: "rewind [step]",+ Use: "rewind [scope] [steps-or-sha]",Aliases: []string{"rw"},Short: "Rewind the plan to an earlier state",- Long: `By default it rollback the conversation by one message. It can accept 'step' to rollback by more steps. It can also accept --sha to rollback to a specific version in the plan git history.`,- Args: cobra.MaximumNArgs(1),- Run: rewind,+ Long: `Rewind the plan to an earlier state. Pass an optional scope to rewind only a specific part of the plan. Valid scopes are "convo", "context", and "draft". If no scope is passed, the entire plan is rewound.++ You can also optionally pass a "steps" number or commit sha. If a steps number is passed, the plan will be rewound that many steps. If a commit sha is passed, the plan will be rewound to that commit. If neither a steps number nor a commit sha is passed, the target scope will be rewound by 1 step.+ `,+ Args: cobra.MaximumNArgs(2),+ Run: rewind,}var sha string@@ -25,6 +33,49 @@ func init() {}func rewind(cmd *cobra.Command, args []string) {- // Argument parsing and rewind logic will be implemented+ var dir string+ scope := "all"+ if len(args) > 0 {+ scope = args[0]+ }++ switch scope {+ case "convo":+ dir = lib.ConversationSubdir+ case "context":+ dir = lib.ContextSubdir+ case "draft":+ dir = lib.DraftSubdir+ default:+ dir = lib.CurrentPlanDir // Rewind the whole plan by default+ }++ // Check if either steps or sha is provided and not both+ stepsOrSHA := ""+ if len(args) > 1 {+ stepsOrSHA = args[1]+ }+ if steps, err := strconv.Atoi(stepsOrSHA); err == nil && steps > 0 {+ // Rewind by the specified number of steps+ if err := lib.GitRewindSteps(dir, steps); err != nil {+ fmt.Fprintln(os.Stderr, "Error rewinding steps:", err)+ os.Exit(1)+ }+ } else if sha := stepsOrSHA; sha != "" {+ // Rewind to the specified SHA+ if err := lib.GitRewindToSHA(dir, sha); err != nil {+ fmt.Fprintln(os.Stderr, "Error rewinding to SHA:", err)+ os.Exit(1)+ }+ } else if stepsOrSHA == "" {+ // No steps or SHA provided, rewind by 1 step by default+ if err := lib.GitRewindSteps(dir, 1); err != nil {+ fmt.Fprintln(os.Stderr, "Error rewinding 1 step:", err)+ os.Exit(1)+ }+ } else {+ fmt.Fprintln(os.Stderr, "Invalid steps or SHA. Steps must be a positive integer, and SHA must be a valid commit hash.")+ os.Exit(1)+ }}diff --git a/cli/cmd/rm.go b/cli/cmd/rm.goindex ddd73430..12f9f4f1 100644--- a/cli/cmd/rm.go+++ b/cli/cmd/rm.go@@ -5,7 +5,10 @@ import ("os""path/filepath""plandex/lib"+ "strconv"+ "strings"+ "github.com/olekukonko/tablewriter""github.com/plandex/plandex/shared""github.com/spf13/cobra")@@ -66,6 +69,11 @@ func contextRm(cmd *cobra.Command, args []string) {return}+ tableString := &strings.Builder{}+ table := tablewriter.NewWriter(tableString)+ table.SetHeader([]string{"Name", "Type", "πͺ"})+ table.SetAutoWrapText(false)+removedTokens := 0totalTokens := planState.ContextTokenstotalUpdatableTokens := planState.ContextUpdatableTokens@@ -76,6 +84,19 @@ func contextRm(cmd *cobra.Command, args []string) {if part.Type == shared.ContextFileType || part.Type == shared.ContextDirectoryTreeType || part.Type == shared.ContextURLType {totalUpdatableTokens -= part.NumTokens}++ t, icon := lib.GetContextTypeAndIcon(part)+ row := []string{+ " " + icon + " " + part.Name,+ t,+ "-" + strconv.Itoa(part.NumTokens),+ }++ table.Rich(row, []tablewriter.Colors{+ {tablewriter.FgHiRedColor, tablewriter.Bold},+ {tablewriter.FgHiRedColor},+ {tablewriter.FgHiRedColor},+ })}planState.ContextTokens = totalTokensplanState.ContextUpdatableTokens = totalUpdatableTokens@@ -94,6 +115,9 @@ func contextRm(cmd *cobra.Command, args []string) {suffix = "s"}msg := fmt.Sprintf("Removed %d piece%s of context | removed β %d πͺ | total β %d πͺ \n", len(toRemovePaths), suffix, removedTokens, totalTokens)+ table.Render()++ msg += "\n" + tableString.String()err = lib.GitCommitContextUpdate(msg)@@ -103,6 +127,7 @@ func contextRm(cmd *cobra.Command, args []string) {}fmt.Println("β " + msg)+} else {fmt.Println("π€·ββοΈ No context removed")}diff --git a/cli/cmd/update.go b/cli/cmd/update.goindex dfdf30f4..b8a13f94 100644--- a/cli/cmd/update.go+++ b/cli/cmd/update.go@@ -1,6 +1,7 @@package cmdimport (+ "fmt""plandex/lib""github.com/spf13/cobra"@@ -22,5 +23,5 @@ func init() {func update(cmd *cobra.Command, args []string) {updateRes := lib.MustUpdateContextWithOuput()table := lib.TableForContextUpdateRes(updateRes)- table.Render()+ fmt.Println(table)}diff --git a/cli/lib/context_display.go b/cli/lib/context_display.gonew file mode 100644index 00000000..dde1aa44--- /dev/null+++ b/cli/lib/context_display.go@@ -0,0 +1,27 @@+package lib++import "github.com/plandex/plandex/shared"++func GetContextTypeAndIcon(part *shared.ModelContextPart) (string, string) {+ var icon string+ var t string+ switch part.Type {+ case shared.ContextFileType:+ icon = "π"+ t = "file"+ case shared.ContextURLType:+ icon = "π"+ t = "url"+ case shared.ContextDirectoryTreeType:+ icon = "π "+ t = "tree"+ case shared.ContextNoteType:+ icon = "βοΈ "+ t = "note"+ case shared.ContextPipedDataType:+ icon = "βοΈ "+ t = "piped"+ }++ return t, icon+}diff --git a/cli/lib/context_load.go b/cli/lib/context_load.goindex 9275db66..e04522f2 100644--- a/cli/lib/context_load.go+++ b/cli/lib/context_load.go@@ -15,7 +15,10 @@ import ("sync""time"+ "strconv"+"github.com/briandowns/spinner"+ "github.com/olekukonko/tablewriter""github.com/plandex/plandex/shared")@@ -366,6 +369,32 @@ func MustLoadContext(resources []string, params *types.LoadContextParams) (int,wg.Wait()+ TableForLoadContext := func(contextParts []*shared.ModelContextPart) string {+ tableString := &strings.Builder{}+ table := tablewriter.NewWriter(tableString)+ table.SetHeader([]string{"Name", "Type", "πͺ"})+ table.SetAutoWrapText(false)++ for _, part := range contextParts {+ t, icon := GetContextTypeAndIcon(part)+ row := []string{+ " " + icon + " " + part.Name,+ t,+ "+" + strconv.Itoa(part.NumTokens),+ }++ table.Rich(row, []tablewriter.Colors{+ {tablewriter.FgHiGreenColor, tablewriter.Bold},+ {tablewriter.FgHiGreenColor},+ {tablewriter.FgHiGreenColor},+ })+ }++ table.Render()++ return tableString.String()+ }+if len(contextParts) == 0 {fmt.Println("π€·ββοΈ No context loaded")os.Exit(1)@@ -440,7 +469,6 @@ func MustLoadContext(resources []string, params *types.LoadContextParams) (int,log.Fatalf("Failed to get total tokens: %v", err)}- err = GitCommitContextUpdate(msg)if err != nil {s.Stop()ClearCurrentLine()@@ -456,5 +484,17 @@ func MustLoadContext(resources []string, params *types.LoadContextParams) (int,ClearCurrentLine()fmt.Println("β " + msg)+ if len(contextParts) > 0 {+ tableString := TableForLoadContext(contextParts)++ err = GitCommitContextUpdate(msg + "\n\n" + tableString)+ if err != nil {+ s.Stop()+ ClearCurrentLine()+ log.Fatalf("Failed to commit context update to git: %v", err)+ }+ fmt.Println(tableString)+ }+return tokensAdded, totalTokens}diff --git a/cli/lib/context_update.go b/cli/lib/context_update.goindex 5a73a144..2e9a9e32 100644--- a/cli/lib/context_update.go+++ b/cli/lib/context_update.go@@ -115,6 +115,8 @@ func MustUpdateContextWithOuput() *updateRes {}}+ msg += " in context"+action := "added"if tokensDiff < 0 {action = "removed"@@ -122,7 +124,7 @@ func MustUpdateContextWithOuput() *updateRes {absTokenDiff := int(math.Abs(float64(tokensDiff)))msg += fmt.Sprintf(" | %s β %d πͺ | total β %d πͺ", action, absTokenDiff, totalTokens)- err = GitCommitContextUpdate(msg)+ err = GitCommitContextUpdate(msg + "\n\n" + TableForContextUpdateRes(updateRes))stopFn()@@ -136,57 +138,47 @@ func MustUpdateContextWithOuput() *updateRes {return updateRes}-func TableForContextUpdateRes(updateRes *updateRes) *tablewriter.Table {+func TableForContextUpdateRes(updateRes *updateRes) string {updatedParts := updateRes.UpdatedPartstokenDiffsByName := updateRes.TokenDiffsByName- table := tablewriter.NewWriter(os.Stdout)+ if len(updatedParts) == 0 {+ return ""+ }++ tableString := &strings.Builder{}+ table := tablewriter.NewWriter(tableString)table.SetHeader([]string{"Name", "Type", "πͺ"})table.SetAutoWrapText(false)for _, part := range updatedParts {-- var icon string- var t string- id := part.Name- switch part.Type {- case shared.ContextFileType:- icon = "π"- t = "file"- id = part.FilePath- case shared.ContextURLType:- icon = "π"- t = "url"- case shared.ContextDirectoryTreeType:- icon = "π "- t = "tree"- id = part.FilePath- }-+ t, icon := GetContextTypeAndIcon(part)diff := tokenDiffsByName[part.Name]diffStr := "+" + strconv.Itoa(diff)- tableColor := []int{tablewriter.FgHiGreenColor, tablewriter.Bold}+ tableColor := tablewriter.FgHiGreenColorif diff < 0 {diffStr = strconv.Itoa(diff)- tableColor = []int{tablewriter.FgHiRedColor, tablewriter.Bold}+ tableColor = tablewriter.FgHiRedColor}row := []string{- " " + icon + " " + id,+ " " + icon + " " + part.Name,t,diffStr,}table.Rich(row, []tablewriter.Colors{- {tablewriter.FgHiWhiteColor},- {tablewriter.FgHiWhiteColor},- tableColor,+ {tableColor, tablewriter.Bold},+ {tableColor},+ {tableColor},})}- return table+ table.Render()++ return tableString.String()}func UpdateContext() (*updateRes, error) {diff --git a/cli/lib/conversation.go b/cli/lib/conversation.goindex 35ddda9b..28da44e1 100644--- a/cli/lib/conversation.go+++ b/cli/lib/conversation.go@@ -217,11 +217,11 @@ func appendConversation(params types.AppendConversationParams) error {var desc stringif t == "prompt" {- desc = "user prompt"+ desc = "π¬ user prompt"} else {- desc = "Plandex reply"+ desc = "π€ Plandex reply"}- err = GitCommitConvoUpdate(fmt.Sprintf("Message #%d | %s | %d tokens", params.PlanState.NumMessages, desc, tokens))+ err = GitCommitConvoUpdate(fmt.Sprintf("Message #%d | %s | %d πͺ", params.PlanState.NumMessages, desc, tokens))if err != nil {return fmt.Errorf("failed to commit conversation update: %s", err)@@ -280,7 +280,7 @@ func saveLatestConvoSummary(rootId string) error {return fmt.Errorf("failed to write summary file: %s", err)}- err = GitCommitConvoUpdate(fmt.Sprintf("Summarized up to message #%d | %d tokens", summary.NumMessages-1, summary.Tokens))+ err = GitCommitConvoUpdate(fmt.Sprintf("π€ Summarized up to message #%d | %d πͺ", summary.NumMessages-1, summary.Tokens))if err != nil {return fmt.Errorf("failed to commit conversation update: %s", err)diff --git a/cli/lib/fs.go b/cli/lib/fs.goindex 607b2730..d606513e 100644--- a/cli/lib/fs.go+++ b/cli/lib/fs.go@@ -17,10 +17,10 @@ var HomePlandexDir stringvar CacheDir stringvar CurrentPlanName string-var CurrentPlanRootDir string-var PlanSubdir string-var PlanFilesDir string-var PlanDescriptionsDir string+var CurrentPlanDir string+var DraftSubdir string+var DraftFilesDir string+var DescriptionsDir stringvar ConversationSubdir stringvar ContextSubdir string@@ -91,12 +91,12 @@ func LoadCurrentPlan() error {}CurrentPlanName = planSettings.Name- CurrentPlanRootDir = filepath.Join(PlandexDir, CurrentPlanName)- PlanSubdir = filepath.Join(CurrentPlanRootDir, "plan")- PlanFilesDir = filepath.Join(PlanSubdir, "files")- PlanDescriptionsDir = filepath.Join(PlanSubdir, "descriptions")- ConversationSubdir = filepath.Join(CurrentPlanRootDir, "conversation")- ContextSubdir = filepath.Join(CurrentPlanRootDir, "context")+ CurrentPlanDir = filepath.Join(PlandexDir, CurrentPlanName)+ DraftSubdir = filepath.Join(CurrentPlanDir, "draft")+ DraftFilesDir = filepath.Join(DraftSubdir, "files")+ DescriptionsDir = filepath.Join(CurrentPlanDir, "descriptions")+ ConversationSubdir = filepath.Join(CurrentPlanDir, "conversation")+ ContextSubdir = filepath.Join(CurrentPlanDir, "context")return nil}diff --git a/cli/lib/git.go b/cli/lib/git.goindex 66b325b9..509f3fec 100644--- a/cli/lib/git.go+++ b/cli/lib/git.go@@ -1,11 +1,16 @@package libimport (+ "bytes""fmt""os/exec""path/filepath"+ "strconv""strings""sync"+ "time"++ "github.com/fatih/color")var gitMutex sync.Mutex@@ -19,7 +24,7 @@ func InitGitRepo(dir string) error {return fmt.Errorf("error initializing git repository for dir: %s, err: %v, output: %s", dir, err, string(res))}- return GitAddAndCommit(dir, "Initial commit")+ return GitAddAndCommit(dir, "New plan")}func AddGitSubmodule(rootDir, submoduleDir string) error {@@ -100,13 +105,13 @@ func GitCommit(repoDir, commitMsg string, lockMutex bool) error {}func gitCommitRootUpdate(commitMsg string) error {- err := GitAdd(CurrentPlanRootDir, ".", true)+ err := GitAdd(CurrentPlanDir, ".", true)if err != nil {return fmt.Errorf("failed to root plan dir changes: %s", err)}// Commit these staged submodule changes in the root repo- err = GitCommit(CurrentPlanRootDir, commitMsg, true)+ err = GitCommit(CurrentPlanDir, commitMsg, true)if err != nil {return fmt.Errorf("failed to commit submodule updates in root dir: %s", err)}@@ -122,7 +127,7 @@ func GitCommitContextUpdate(commitMsg string) error {return fmt.Errorf("failed to commit context: %v", err)}- err = GitAdd(CurrentPlanRootDir, ContextSubdir, true)+ err = GitAdd(CurrentPlanDir, ContextSubdir, true)if err != nil {return fmt.Errorf("failed to stage submodule changes in context dir: %s", err)}@@ -137,7 +142,7 @@ func GitCommitConvoUpdate(commitMsg string) error {return fmt.Errorf("failed to commit convo update: %v", err)}- err = GitAdd(CurrentPlanRootDir, ConversationSubdir, true)+ err = GitAdd(CurrentPlanDir, ConversationSubdir, true)if err != nil {return fmt.Errorf("failed to stage submodule changes in convo dir: %s", err)}@@ -146,10 +151,111 @@ func GitCommitConvoUpdate(commitMsg string) error {}func GitCommitPlanUpdate(commitMsg string) error {- err := GitAddAndCommit(PlanSubdir, commitMsg)+ err := GitAddAndCommit(DraftSubdir, commitMsg)if err != nil {return fmt.Errorf("failed to commit files to plan dir: %s", err)}return gitCommitRootUpdate(commitMsg)}++// GetGitCommitHistory retrieves the git commit history for the given directory.+// It returns a formatted string with each commit's short SHA, timestamp, and message.+func GetGitCommitHistory(dir string) (string, error) {+ gitMutex.Lock()+ defer gitMutex.Unlock()++ 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()))+ return history, nil+}++// GitRewindSteps reverts the repository by a specified number of steps.+func GitRewindSteps(dir string, steps int) error {+ gitMutex.Lock()+ defer gitMutex.Unlock()++ res, err := exec.Command("git", "-C", dir, "reset", "--hard",+ fmt.Sprintf("HEAD~%d", steps)).CombinedOutput()++ if err != nil {+ return fmt.Errorf("error executing git reset for dir: %s, steps: %d, err: %v, output: %s", dir, steps, err, string(res))+ }++ return nil+}++// GitRewindToSHA reverts the repository to a specific commit SHA.+func GitRewindToSHA(dir, sha string) error {+ gitMutex.Lock()+ defer gitMutex.Unlock()++ res, err := exec.Command("git", "-C", dir, "reset", "--hard",+ sha).CombinedOutput()++ if err != nil {+ return fmt.Errorf("error executing git reset for dir: %s, sha: %s, err: %v, output: %s", dir, sha, err, string(res))+ }++ return nil+}++// processGitHistoryOutput processes the raw output from the git log command and returns a formatted string.+func processGitHistoryOutput(raw string) string {+ history := []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, fullEntry)+ }+ }++ return strings.Join(history, "\n\n")+}diff --git a/cli/lib/plan_files.go b/cli/lib/plan_files.goindex 68450000..46426b12 100644--- a/cli/lib/plan_files.go+++ b/cli/lib/plan_files.go@@ -45,7 +45,7 @@ func worker(dir string, srcPath string, info os.FileInfo, err error, doneCh chanfunc getCurrentPlanFiles() (shared.CurrentPlanFiles, error) {planFiles.data = make(map[string]string)- _, err := os.Stat(PlanFilesDir)+ _, err := os.Stat(DraftFilesDir)filesDirExists := !os.IsNotExist(err)numFiles := 0@@ -55,7 +55,7 @@ func getCurrentPlanFiles() (shared.CurrentPlanFiles, error) {if filesDirExists {// Enumerate all paths in [planDir]/files- err = filepath.Walk(PlanFilesDir, func(srcPath string, info os.FileInfo, err error) error {+ err = filepath.Walk(DraftFilesDir, func(srcPath string, info os.FileInfo, err error) error {if err != nil {return err}@@ -63,7 +63,7 @@ func getCurrentPlanFiles() (shared.CurrentPlanFiles, error) {return nil}numFiles++- go worker(PlanFilesDir, srcPath, info, err, doneCh)+ go worker(DraftFilesDir, srcPath, info, err, doneCh)return nil})}@@ -85,14 +85,14 @@ func getCurrentPlanFiles() (shared.CurrentPlanFiles, error) {}func GetCurrentPlanFilePaths() ([]string, error) {- _, err := os.Stat(PlanFilesDir)+ _, err := os.Stat(DraftFilesDir)filesDirExists := !os.IsNotExist(err)filePaths := make([]string, 0)if filesDirExists {// Enumerate all paths in [planDir]/files- err = filepath.Walk(PlanFilesDir, func(srcPath string, info os.FileInfo, err error) error {+ err = filepath.Walk(DraftFilesDir, func(srcPath string, info os.FileInfo, err error) error {if err != nil {return err}@@ -101,7 +101,7 @@ func GetCurrentPlanFilePaths() ([]string, error) {return nil}- relPath, err := filepath.Rel(PlanFilesDir, srcPath)+ relPath, err := filepath.Rel(DraftFilesDir, srcPath)if err != nil {return err}diff --git a/cli/lib/plans.go b/cli/lib/plans.goindex 71366717..938e10d4 100644--- a/cli/lib/plans.go+++ b/cli/lib/plans.go@@ -75,7 +75,7 @@ func CurrentPlanIsDraft() bool {return draftRegex.MatchString(CurrentPlanName)}-func RenameCurrentDraftPlan(name string) error {+func RenameCurrentDraftPlan(planState *types.PlanState, name string) error {if PlandexDir == "" {return fmt.Errorf("PlandexDir not set")}@@ -108,13 +108,9 @@ func RenameCurrentDraftPlan(name string) error {return fmt.Errorf("failed to load current plan: %w", err)}- planState, err := GetPlanState()- if err != nil {- return fmt.Errorf("failed to get plan state: %w", err)- }-planState.Name = nameerr = SetPlanState(planState, shared.StringTs())+if err != nil {return fmt.Errorf("failed to set plan state: %w", err)}@@ -187,7 +183,7 @@ func SetPlanState(state *types.PlanState, updatedAt string) error {state.UpdatedAt = updatedAt}- planStatePath := filepath.Join(CurrentPlanRootDir, "plan.json")+ planStatePath := filepath.Join(CurrentPlanDir, "plan.json")planStateBytes, err := json.MarshalIndent(state, "", " ")if err != nil {return fmt.Errorf("failed to marshal plan state: %s", err)@@ -196,6 +192,7 @@ func SetPlanState(state *types.PlanState, updatedAt string) error {if err != nil {return fmt.Errorf("failed to write plan state: %s", err)}+return nil}diff --git a/cli/lib/proposal.go b/cli/lib/proposal.goindex dca06faa..8c124ba0 100644--- a/cli/lib/proposal.go+++ b/cli/lib/proposal.go@@ -54,7 +54,7 @@ func Propose(prompt string) error {fmt.Fprintln(os.Stderr, "\nError getting file name for prompt:", err)return err}- err = RenameCurrentDraftPlan(format.GetFileNameWithoutExt(fileNameResp.FileName))+ err = RenameCurrentDraftPlan(planState, format.GetFileNameWithoutExt(fileNameResp.FileName))if err != nil {fmt.Fprintln(os.Stderr, "\nError renaming draft plan:", err)return err@@ -260,12 +260,12 @@ func Propose(prompt string) error {return}- err = os.MkdirAll(PlanDescriptionsDir, os.ModePerm)+ err = os.MkdirAll(DescriptionsDir, os.ModePerm)if err != nil {onError(fmt.Errorf("failed to create plan descriptions directory: %s", err))return}- descriptionsPath := filepath.Join(PlanDescriptionsDir, desc.ResponseTimestamp+".json")+ descriptionsPath := filepath.Join(DescriptionsDir, desc.ResponseTimestamp+".json")err = os.WriteFile(descriptionsPath, bytes, 0644)if err != nil {onError(fmt.Errorf("failed to write plan description to file: %s", err))@@ -506,8 +506,8 @@ func checkOutdatedContext(s *spinner.Spinner) (bool, error) {}color.New(color.FgHiCyan, color.Bold).Printf("%s in context %s modified π\n\n", msg, phrase)- table := TableForContextUpdateRes(outdatedRes)- table.Render()+ tableString := TableForContextUpdateRes(outdatedRes)+ fmt.Println(tableString)fmt.Println()diff --git a/cli/lib/stream.go b/cli/lib/stream.goindex 64f3fd91..2690212e 100644--- a/cli/lib/stream.go+++ b/cli/lib/stream.go@@ -66,7 +66,7 @@ func receiveFileToken(params *receiveFileChunkParams) (bool, error) {// log.Println("Parsed JSON. Streamed type: " + streamedType)- writeToPath := filepath.Join(PlanFilesDir, chunk.Path)+ writeToPath := filepath.Join(DraftFilesDir, chunk.Path)var content string@@ -100,7 +100,7 @@ func receiveFileToken(params *receiveFileChunkParams) (bool, error) {}if os.Getenv("GOENV") == "development" {- updatesPath := filepath.Join(CurrentPlanRootDir, "updates", chunk.Path)+ updatesPath := filepath.Join(CurrentPlanDir, "updates", chunk.Path)os.MkdirAll(filepath.Dir(updatesPath), os.ModePerm)os.WriteFile(updatesPath+"-"+"replacements"+"-"+shared.StringTs(), []byte(buffer), 0644)}@@ -143,7 +143,7 @@ func receiveFileToken(params *receiveFileChunkParams) (bool, error) {content = streamed.Contentif os.Getenv("GOENV") == "development" {- updatesPath := filepath.Join(CurrentPlanRootDir, "updates", chunk.Path)+ updatesPath := filepath.Join(CurrentPlanDir, "updates", chunk.Path)os.MkdirAll(filepath.Dir(updatesPath), os.ModePerm)os.WriteFile(updatesPath+"-"+"file"+"-"+shared.StringTs(), []byte(buffer), 0644)}@@ -180,7 +180,7 @@ func receiveFileToken(params *receiveFileChunkParams) (bool, error) {func writeTokenCounts(chunk *shared.PlanChunk, numTokensByPath map[string]int) error {currentPlanTokensByPath := make(map[string]int)- currrentPlanTokensPath := filepath.Join(CurrentPlanRootDir, "tokens.json")+ currrentPlanTokensPath := filepath.Join(CurrentPlanDir, "tokens.json")// Read the existing token counts if the file exists.if _, err := os.Stat(currrentPlanTokensPath); !os.IsNotExist(err) {@@ -220,7 +220,7 @@ func writeTokenCounts(chunk *shared.PlanChunk, numTokensByPath map[string]int) efunc loadCurrentPlanTokensByFilePath() (map[string]int, error) {currentPlanTokensByPath := make(map[string]int)- currrentPlanTokensPath := filepath.Join(CurrentPlanRootDir, "tokens.json")+ currrentPlanTokensPath := filepath.Join(CurrentPlanDir, "tokens.json")if _, err := os.Stat(currrentPlanTokensPath); os.IsNotExist(err) {// do nothing} else {diff --git a/cli/lib/term.go b/cli/lib/term.goindex db304906..c2a61d8d 100644--- a/cli/lib/term.go+++ b/cli/lib/term.go@@ -3,6 +3,7 @@ package libimport ("fmt""os"+ "os/exec""strings""github.com/eiannone/keyboard"@@ -80,6 +81,32 @@ func BackToMain() {fmt.Print("\x1b[?1049l\x1b[?25h")}+func PageOutput(output string) {+ cmd := exec.Command("less", "-R")+ cmd.Env = append(os.Environ(), "LESS=FRX", "LESSCHARSET=utf-8")+ cmd.Stdin = strings.NewReader(output)+ cmd.Stdout = os.Stdout+ cmd.Stderr = os.Stderr++ if err := cmd.Run(); err != nil {+ fmt.Fprintln(os.Stderr, "Failed to page output:", err)+ }+}++func PageOutputReverse(output string) {+ cmd := exec.Command("less", "-RX", "+G")+ cmd.Stdin = strings.NewReader(output)+ cmd.Stdout = os.Stdout+ cmd.Stderr = os.Stderr++ // Set the environment variables specifically for the less command+ cmd.Env = append(os.Environ(), "LESS=FRX", "LESSCHARSET=utf-8")++ if err := cmd.Run(); err != nil {+ fmt.Fprintln(os.Stderr, "Failed to page output with colors:", err)+ }+}+// Function for 'a' key actionfunc handleAbortKey(proposalId string) error {return Abort(proposalId)diff --git a/server/model/constants.go b/server/model/constants.godeleted file mode 100644index 8e079983..00000000--- a/server/model/constants.go+++ /dev/null@@ -1,6 +0,0 @@-package model--import "github.com/sashabaranov/go-openai"--const StrongModel = "gpt-4-1106-preview" //openai.GPT4-const WeakModel = openai.GPT3Dot5Turbodiff --git a/server/model/name.go b/server/model/name.goindex b3e66545..ec1b6dbd 100644--- a/server/model/name.go+++ b/server/model/name.go@@ -15,7 +15,7 @@ func FileName(text string) ([]byte, int, error) {resp, err := Client.CreateChatCompletion(context.Background(),openai.ChatCompletionRequest{- Model: WeakModel,+ Model: NameModel,Functions: []openai.FunctionDefinition{{Name: "nameFile",Parameters: &jsonschema.Definition{diff --git a/server/model/openai_models.go b/server/model/openai_models.gonew file mode 100644index 00000000..023b8dc6--- /dev/null+++ b/server/model/openai_models.go@@ -0,0 +1,35 @@+package model++import (+ "os"++ "github.com/sashabaranov/go-openai"+)++var PlannerModel = "gpt-4-1106-preview" //openai.GPT4+var PlanSummaryModel = PlannerModel+var BuilderModel = openai.GPT40613+var ShortSummaryModel = openai.GPT3Dot5Turbo+var NameModel = openai.GPT3Dot5Turbo+var CommitMsgModel = openai.GPT3Dot5Turbo++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/prompts/create.go b/server/model/prompts/create.gonew file mode 100644index 00000000..8228f001--- /dev/null+++ b/server/model/prompts/create.go@@ -0,0 +1,56 @@+package prompts++import (+ "fmt"++ "github.com/plandex/plandex/shared"+)++const SysCreate = shared.IdentityPrompt + ` 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.++ 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/utils.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 the file path as described above in 2a. Code must *always* be labelled with the path.++ Every file you reference 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/utils.go', you can create a new file at path 'lib/utils_test.go' but *not* at path 'src/lib/utils.go'.++ 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.++ 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.` ++ "\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. Remember to precede code blocks with the file path *exactly* as described in 2a. Do not use any other formatting for file paths."++var PromptWrapperTokens = shared.GetNumTokens(fmt.Sprintf(PromptWrapperFormatStr, ""))diff --git a/server/model/prompts/file.go b/server/model/prompts/file.gonew file mode 100644index 00000000..55245774--- /dev/null+++ b/server/model/prompts/file.go@@ -0,0 +1,29 @@+package prompts++import (+ "github.com/sashabaranov/go-openai"+ "github.com/sashabaranov/go-openai/jsonschema"+)++const SysWriteFile = `+[YOUR INSTRUCTIONS]++You are an AI plan builder. You apply changes from a plan to a given code file. Use 'writeEntireFile' function to write the full content of the file as raw text, including any updates from the previous response, to the file. Call 'writeEntireFile' with the entire updated file. Don't include any placeholders or references to the original file.++Again, make sure the output represents the ENTIRE FILE with all your suggested modifications from the plan applied to it. You MUST NOT include placeholders like '... Rest of the function' or '... Rest of the imports' or '... Rest of the file'. You MUST NOT include references to the original file like '... Rest of the file from the previous response'. You MUST output the ENTIRE file WITHOUT EXCEPTION even if it causes you to generate a large number of tokens. The entire file MUST be output as raw text. This is VERY IMPORTANT, as your output will replace the original file from the context. If any sections of the original file are missing in your output, the user's code will be broken. Please output the ENTIRE FILE with all suggested modifications applied to it.++[END INSTRUCTIONS]`++var WriteFileFn = openai.FunctionDefinition{+ Name: "writeEntireFile",+ Parameters: &jsonschema.Definition{+ Type: jsonschema.Object,+ Properties: map[string]jsonschema.Definition{+ "content": {+ Type: jsonschema.String,+ Description: "The full content of the file, including any updates from the previous response, as raw text",+ },+ },+ Required: []string{"content"},+ },+}diff --git a/server/model/prompts/replace.go b/server/model/prompts/replace.gonew file mode 100644index 00000000..221fdf41--- /dev/null+++ b/server/model/prompts/replace.go@@ -0,0 +1,170 @@+package prompts++import (+ "github.com/sashabaranov/go-openai"+ "github.com/sashabaranov/go-openai/jsonschema"+)++const SysReplace = `+[YOUR INSTRUCTIONS]++You are an AI replacer. You apply changes from a plan to a given code file using the 'writeReplacements' function.++Call 'writeReplacements' with a list of replacements to apply to the file. Each replacement is an object with two properties: 'old' and 'new'. 'old' is the old text to replace, and 'new' is the new text to replace it with. You can include as many replacements as you want. You must include at least one replacement.+- The 'new' text must include the full text of the replacement without any placeholders or references to the original file.+- The 'old' text *ABSOLUTELY MUST BE AN EXACT SUBSTRING* of the current state of the file.+- The 'old' text must not overlap with any other 'old' text in the list 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.++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)"+ },+ {+ old: "fmt.Println(\"Hello, world!\")",+ new: "fmt.Println(time.Now())"+ }+ }+})++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}"+ }+ ]+})++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!\")"+ }+ ]+})++[END INSTRUCTIONS]`++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",+ },+ "new": {+ Type: jsonschema.String,+ Description: "The new text to replace it with",+ },+ },+ Required: []string{"old", "new"},+ },+ },+ },+ Required: []string{"replacements"},+ },+}diff --git a/server/model/proposal/build.go b/server/model/proposal/build.goindex c31e4b95..08b4a914 100644--- a/server/model/proposal/build.go+++ b/server/model/proposal/build.go@@ -7,13 +7,13 @@ import ("fmt""os""plandex-server/model"+ "plandex-server/model/prompts""plandex-server/types""time""github.com/davecgh/go-spew/spew""github.com/plandex/plandex/shared""github.com/sashabaranov/go-openai"- "github.com/sashabaranov/go-openai/jsonschema")func buildPlan(proposalId string, fileContents map[string]string, numTokensByFile map[string]int, onStream types.OnStreamFunc) error {@@ -114,6 +114,7 @@ func buildPlan(proposalId string, fileContents map[string]string, numTokensByFil}fmt.Println("Getting file from model: " + filePath)+ fmt.Println("File context:", fileContext)fmtStr := "\nCurrent state of %s:\n```\n%s\n```"fmtArgs := []interface{}{filePath}@@ -129,21 +130,26 @@ func buildPlan(proposalId string, fileContents map[string]string, numTokensByFilvar msg stringif fileContext != nil {- msg = replacementSystemPrompt+ msg = prompts.SysReplace} else {- msg = writeFileOnlySystemPrompt+ msg = prompts.SysWriteFile}if fileContext != nil || currentState != "" {+ fmt.Println("Adding current state to message")msg += "\n\n" + fmt.Sprintf(fmtStr, fmtArgs...)++ fmt.Println("Message:")+ fmt.Println(msg)}fileMessages = append(fileMessages, openai.ChatCompletionMessage{Role: openai.ChatMessageRoleSystem,Content: msg,- })-- fileMessages = append(fileMessages, openai.ChatCompletionMessage{+ }, openai.ChatCompletionMessage{+ Role: openai.ChatMessageRoleUser,+ Content: proposal.Request.Prompt,+ }, openai.ChatCompletionMessage{Role: openai.ChatMessageRoleAssistant,Content: proposal.Content,})@@ -153,7 +159,7 @@ func buildPlan(proposalId string, fileContents map[string]string, numTokensByFilopenai.ChatCompletionMessage{Role: openai.ChatMessageRoleUser,Content: fmt.Sprintf(`- Based on your instructions, apply the changes from the plan to %s. You must call either the 'writeReplacements' function or the 'writeEntireFile' function, depending on which is a more efficient way to apply the changes. Don't call any other function.+ Based on your instructions, apply the changes from the plan to %s. You must call either the 'writeReplacements' function or the 'writeEntireFile' function, depending on which will apply the changes with fewer tokens.`, filePath),})} else {@@ -161,66 +167,28 @@ func buildPlan(proposalId string, fileContents map[string]string, numTokensByFilopenai.ChatCompletionMessage{Role: openai.ChatMessageRoleUser,Content: fmt.Sprintf(`- Based on your instructions, apply the changes from the plan to %s. You must call the 'writeEntireFile' function. Don't call any other function.+ Based on your instructions, apply the changes from the plan to %s. You must call the 'writeEntireFile' function with the ENTIRE FILE, including your suggested changes. Don't call any other function.`, filePath),})}fmt.Println("Calling model for file: " + filePath)+// for _, msg := range fileMessages {// fmt.Printf("%s: %s\n", msg.Role, msg.Content)// }- functions := []openai.FunctionDefinition{- {- Name: "writeEntireFile",- Parameters: &jsonschema.Definition{- Type: jsonschema.Object,- Properties: map[string]jsonschema.Definition{- "content": {- Type: jsonschema.String,- Description: "The full content of the file, including any updates from the previous response, as raw text",- },- },- Required: []string{"content"},- },- },- }+ functions := []openai.FunctionDefinition{prompts.WriteFileFn}if fileContext != nil {- functions = append(functions, 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",- },- "new": {- Type: jsonschema.String,- Description: "The new text to replace it with",- },- },- Required: []string{"old", "new"},- },- },- },- Required: []string{"replacements"},- },- })+ functions = append(functions, prompts.ReplaceFn)}modelReq := openai.ChatCompletionRequest{- Model: model.StrongModel,- Functions: functions,- Messages: fileMessages,+ Model: model.BuilderModel,+ Functions: functions,+ Messages: fileMessages,+ Temperature: 0.0,}stream, err := model.Client.CreateChatCompletionStream(ctx, modelReq)@@ -297,13 +265,9 @@ func buildPlan(proposalId string, fileContents map[string]string, numTokensByFildelta := response.Choices[0].Deltaif delta.FunctionCall == nil {- fmt.Println("Stream received data not for a function call")-spew.Dump(delta)continue} else {- fmt.Printf("Stream received data for function call: %s", delta.FunctionCall.Name)-content = delta.FunctionCall.Arguments}@@ -334,147 +298,3 @@ func buildPlan(proposalId string, fileContents map[string]string, numTokensByFilreturn nil}--const replacementSystemPrompt = `-[YOUR INSTRUCTIONS]--You apply changes from a plan to a given code file. You can either us the 'writeEntireFile' function to write the entire file, or the 'writeReplacements' function to write a list of replacements to apply to the file. Decide which is a more efficient way to apply the changes, and call the appropriate function.--A. If you are using the 'writeEntireFile' function, call it with the full content of the file as raw text, including any updates from the previous response. Call 'writeEntireFile' with the entire updated file. Don't include any placeholders or references to the original file.--B. If you are using the 'writeReplacements' function, call it with a list of replacements to apply to the file. Each replacement is an object with two properties: 'old' and 'new'. 'old' is the old text to replace, and 'new' is the new text to replace it with. You can include as many replacements as you want. You must include at least one replacement.-- The 'new' text must include the full text of the replacement without any placeholders or references to the original file.-- The 'old' text *ABSOLUTELY MUST BE AN EXACT SUBSTRING* of the current state of the file.-- The 'old' text must not overlap with any other 'old' text in the list of replacements.--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)"- },- {- old: "fmt.Println(\"Hello, world!\")",- new: "fmt.Println(time.Now())"- }- }-})--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}"- }- ]-})--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!\")"- }- ]-})--[END INSTRUCTIONS]`--const writeFileOnlySystemPrompt = `-[YOUR INSTRUCTIONS]--You apply changes from a plan to a given code file. Use 'writeEntireFile' function to write the full content of the file as raw text, including any updates from the previous response, to the file. Call 'writeEntireFile' with the entire updated file. Don't include any placeholders or references to the original file.--[END INSTRUCTIONS]`diff --git a/server/model/proposal/create.go b/server/model/proposal/create.goindex 6dbb2400..9d40b025 100644--- a/server/model/proposal/create.go+++ b/server/model/proposal/create.go@@ -11,6 +11,7 @@ import ("plandex-server/model""plandex-server/model/lib"+ "plandex-server/model/prompts""plandex-server/types""github.com/google/uuid"@@ -18,50 +19,6 @@ import ("github.com/sashabaranov/go-openai")-const systemMessageHead = shared.IdentityPrompt + ` A plan is a set of files with an attached context.` +-- "Your instructions:\n\n```\n" +-- `Based on user-provided context, create a plan for the task using the following steps:-- 1. Decide whether you've been given enough information and context to make a good plan.- a. If not:- - 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/utils.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 "I will break this large task into subtasks."- - Divide the task into smaller subtasks and list them in a numbered list. Stop there.-- Always precede code blocks the file path as described above in 2a. Code must *always* be labelled with the path.-- Every file you reference 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/utils.go', you can create a new file at path 'lib/utils_test.go' but *not* at path 'src/lib/utils.go'.-- 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.-- 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.` +- "\n```\n\n" +- "User-provided context:"--var systemHeadNumTokens = shared.GetNumTokens(systemMessageHead)--const promptWrapperFormatStr = "The user's latest prompt:\n```\n%s\n```\n\n Please respond according to the 'Your instructions' section above. Remember to precede code blocks with the file path *exactly* as described in 2a. Do not use any other formatting for file paths."--var promptWrapperTokens = shared.GetNumTokens(fmt.Sprintf(promptWrapperFormatStr, ""))-// Proposal function to create a new proposalfunc CreateProposal(req shared.PromptRequest, onStream types.OnStreamFunc) error {goEnv := os.Getenv("GOENV") // Fetch the GO_ENV environment variable@@ -100,7 +57,7 @@ func CreateProposal(req shared.PromptRequest, onStream types.OnStreamFunc) erroronStream(proposalId, nil)contextText, contextTokens := lib.FormatModelContext(req.ModelContext)- systemMessageText := systemMessageHead + contextText+ systemMessageText := prompts.SysCreate + contextTextsystemMessage := openai.ChatCompletionMessage{Role: openai.ChatMessageRoleSystem,Content: systemMessageText,@@ -110,11 +67,11 @@ func CreateProposal(req shared.PromptRequest, onStream types.OnStreamFunc) errorsystemMessage,}- promptTokens := promptWrapperTokens + shared.GetNumTokens(req.Prompt)- totalTokens := systemHeadNumTokens + contextTokens + promptTokens+ promptTokens := prompts.PromptWrapperTokens + shared.GetNumTokens(req.Prompt)+ totalTokens := prompts.CreateSysMsgNumTokens + contextTokens + promptTokens// print out breakdown of token usage- fmt.Printf("System message tokens: %d\n", systemHeadNumTokens)+ fmt.Printf("System message tokens: %d\n", prompts.CreateSysMsgNumTokens)fmt.Printf("Context tokens: %d\n", contextTokens)fmt.Printf("Prompt tokens: %d\n", promptTokens)fmt.Printf("Total tokens before convo: %d\n", totalTokens)@@ -199,7 +156,7 @@ func CreateProposal(req shared.PromptRequest, onStream types.OnStreamFunc) errorpromptMessage := openai.ChatCompletionMessage{Role: openai.ChatMessageRoleUser,- Content: fmt.Sprintf(promptWrapperFormatStr, req.Prompt),+ Content: fmt.Sprintf(prompts.PromptWrapperFormatStr, req.Prompt),}messages = append(messages, promptMessage)@@ -215,7 +172,7 @@ func CreateProposal(req shared.PromptRequest, onStream types.OnStreamFunc) errorreplyInfo := shared.NewReplyInfo()modelReq := openai.ChatCompletionRequest{- Model: model.StrongModel,+ Model: model.PlannerModel,Messages: messages,Stream: true,}diff --git a/server/model/proposal/describe.go b/server/model/proposal/describe.goindex e479adf6..21714813 100644--- a/server/model/proposal/describe.go+++ b/server/model/proposal/describe.go@@ -17,7 +17,7 @@ func genPlanDescriptionJson(proposalId string, ctx context.Context) (*shared.PlaplanDescResp, err := model.Client.CreateChatCompletion(ctx,openai.ChatCompletionRequest{- Model: model.WeakModel,+ Model: model.CommitMsgModel,Functions: []openai.FunctionDefinition{{Name: "describePlan",Parameters: &jsonschema.Definition{diff --git a/server/model/summarize.go b/server/model/summarize.goindex 0b39b8ee..e5e8758b 100644--- a/server/model/summarize.go+++ b/server/model/summarize.go@@ -15,7 +15,7 @@ func ShortSummary(text string) ([]byte, error) {resp, err := Client.CreateChatCompletion(context.Background(),openai.ChatCompletionRequest{- Model: WeakModel,+ Model: ShortSummaryModel,Functions: []openai.FunctionDefinition{{Name: "summarize",Parameters: &jsonschema.Definition{@@ -98,7 +98,7 @@ func PlanSummary(conversation []openai.ChatCompletionMessage, lastMessageTimestaresp, err := Client.CreateChatCompletion(context.Background(),openai.ChatCompletionRequest{- Model: StrongModel,+ Model: PlanSummaryModel,Messages: messages,},)@@ -119,6 +119,7 @@ func PlanSummary(conversation []openai.ChatCompletionMessage, lastMessageTimestaSummary: content,Tokens: resp.Usage.CompletionTokens,LastMessageTimestamp: lastMessageTimestamp,+ NumMessages: numMessages,}, nil}