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
added test mode with lorem ipsum. streaming file json works
Dane Schneiderfe18853f3837
diff --git a/cli/cmd/chat.go b/cli/cmd/chat.goindex 13732c61..6defc2eb 100644--- a/cli/cmd/chat.go+++ b/cli/cmd/chat.go@@ -22,7 +22,7 @@ var chatCmd = &cobra.Command{func chat(cmd *cobra.Command, args []string) {p := args[0]- err := lib.Propose(p, true)+ err := lib.Propose(p)if err != nil {fmt.Fprintln(os.Stderr, "Prompt error:", err)returndiff --git a/cli/cmd/new.go b/cli/cmd/new.goindex 754d4392..45365879 100644--- a/cli/cmd/new.go+++ b/cli/cmd/new.go@@ -47,7 +47,7 @@ func new(cmd *cobra.Command, args []string) {}if name == "" {- summaryResp, err := lib.ApiSummarize(prompt)+ summaryResp, err := lib.Api.Summarize(prompt)if err != nil {log.Fatalf("Failed to get a name for the prompt: %v", err)}@@ -201,7 +201,7 @@ func new(cmd *cobra.Command, args []string) {}if prompt != "" {- err = lib.Propose(prompt, false)+ err = lib.Propose(prompt)if err != nil {fmt.Fprintln(os.Stderr, "Prompt error:", err)returndiff --git a/cli/cmd/revise.go b/cli/cmd/revise.goindex 61d540c8..6e4a8c40 100644--- a/cli/cmd/revise.go+++ b/cli/cmd/revise.go@@ -22,7 +22,7 @@ var reviseCmd = &cobra.Command{func revise(cmd *cobra.Command, args []string) {p := args[0]- err := lib.Propose(p, false)+ err := lib.Propose(p)if err != nil {fmt.Fprintln(os.Stderr, "Prompt error:", err)returndiff --git a/cli/go.mod b/cli/go.modindex 4550498b..5b19600e 100644--- a/cli/go.mod+++ b/cli/go.mod@@ -18,6 +18,8 @@ require (github.com/gdamore/tcell/v2 v2.6.0 // indirectgithub.com/google/uuid v1.3.0 // indirectgithub.com/gorilla/css v1.0.0 // indirect+ github.com/hashicorp/errwrap v1.0.0 // indirect+ github.com/looplab/fsm v1.0.1 // indirectgithub.com/lucasb-eyer/go-colorful v1.2.0 // indirectgithub.com/mattn/go-colorable v0.1.12 // indirectgithub.com/mattn/go-isatty v0.0.18 // indirect@@ -41,7 +43,9 @@ require (github.com/briandowns/spinner v1.23.0github.com/charmbracelet/glamour v0.6.0github.com/charmbracelet/glow v1.5.1+ github.com/eiannone/keyboard v0.0.0-20220611211555-0d226195f203github.com/gizak/termui/v3 v3.1.0+ github.com/hashicorp/go-multierror v1.1.1github.com/inconshreveable/mousetrap v1.1.0 // indirectgithub.com/mattn/go-runewidth v0.0.15 // indirectgithub.com/pkoukk/tiktoken-go v0.1.5diff --git a/cli/go.sum b/cli/go.sumindex b62f49e4..44cfa9f8 100644--- a/cli/go.sum+++ b/cli/go.sum@@ -272,6 +272,8 @@ github.com/dlclark/regexp2 v1.10.0 h1:+/GIL799phkJqYW+3YbOd8LCcbHzT0Pbo8zl70MHsqgithub.com/dlclark/regexp2 v1.10.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk=github.com/dustin/go-humanize v1.0.1-0.20200219035652-afde56e7acac/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk=+github.com/eiannone/keyboard v0.0.0-20220611211555-0d226195f203 h1:XBBHcIb256gUJtLmY22n99HaZTz+r2Z51xUPi01m3wg=+github.com/eiannone/keyboard v0.0.0-20220611211555-0d226195f203/go.mod h1:E1jcSv8FaEny+OP/5k9UxZVw9YFWGj7eI4KR/iOBqCg=github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98=@@ -409,6 +411,7 @@ github.com/grpc-ecosystem/grpc-gateway v1.9.0/go.mod h1:vNeuVxBJEsws4ogUvrchl83tgithub.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw=github.com/hashicorp/consul/api v1.15.3/go.mod h1:/g/qgcoBcEXALCNZgRRisyTW0nY86++L0KbeAMXYCeY=github.com/hashicorp/consul/sdk v0.11.0/go.mod h1:yPkX5Q6CsxTFMjQQDJwzeNmUUF5NUGGbrDsv9wTb8cw=+github.com/hashicorp/errwrap v1.0.0 h1:hLrqtEDnRye3+sgx6z4qVLNuviH3MR5aQ0ykNJa/UYA=github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=github.com/hashicorp/go-cleanhttp v0.5.0/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80=github.com/hashicorp/go-cleanhttp v0.5.1/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80=@@ -423,6 +426,7 @@ github.com/hashicorp/go-msgpack v0.5.3/go.mod h1:ahLV/dePpqEmjfWmKiqvPkv/twdG7iPgithub.com/hashicorp/go-msgpack v0.5.5/go.mod h1:ahLV/dePpqEmjfWmKiqvPkv/twdG7iPBM1vqhUKIvfM=github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk=github.com/hashicorp/go-multierror v1.1.0/go.mod h1:spPvp8C1qA32ftKqdAHm4hHTbPw+vmowP0z+KUhOZdA=+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/hashicorp/go-retryablehttp v0.5.3/go.mod h1:9B5zBasrRhHXnJnui7y6sL7es7NDiJgTc6Er0maI1Xs=github.com/hashicorp/go-rootcerts v1.0.2/go.mod h1:pqUvnprVnM5bf7AOirdbb01K4ccR319Vf4pU3K5EGc8=@@ -474,6 +478,8 @@ github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=+github.com/looplab/fsm v1.0.1 h1:OEW0ORrIx095N/6lgoGkFkotqH6s7vaFPsgjLAaF5QU=+github.com/looplab/fsm v1.0.1/go.mod h1:PmD3fFvQEIsjMEfvZdrCDZ6y8VwKTwWNjlpEr6IKPO4=github.com/lucasb-eyer/go-colorful v1.0.3/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=diff --git a/cli/lib/api.go b/cli/lib/api.goindex e361f5dc..a5929786 100644--- a/cli/lib/api.go+++ b/cli/lib/api.go@@ -3,12 +3,12 @@ package libimport ("bufio""bytes"+ "context""encoding/json""fmt""io""net/http""plandex/types"- "strings""github.com/plandex/plandex/shared"openai "github.com/sashabaranov/go-openai"@@ -16,7 +16,12 @@ import (const apiHost = "http://localhost:8088"-func ApiPropose(prompt string, chatOnly bool, onStream types.OnStreamProposal) error {+// Check that API implements the types.APIHandler interface+var Api types.APIHandler = (*API)(nil)++type API struct{}++func (api *API) Propose(prompt string, onStream types.OnStreamPlan) error {serverUrl := apiHost + "/proposal"// Channels to receive data and errors@@ -31,13 +36,13 @@ func ApiPropose(prompt string, chatOnly bool, onStream types.OnStreamProposal) e// Goroutine for loading contextgo func() {- context, err := GetAllContext(false)+ modelContext, err := GetAllContext(false)if err != nil {fmt.Println("Error loading context:" + err.Error())contextErrChan <- errreturn}- contextChan <- context+ contextChan <- modelContext}()// Goroutine for loading conversation@@ -62,14 +67,14 @@ func ApiPropose(prompt string, chatOnly bool, onStream types.OnStreamProposal) eplanChan <- plan}()- var context shared.ModelContext+ var modelContext shared.ModelContextvar currentPlan shared.CurrentPlanFilesvar conversation []openai.ChatCompletionMessagevar err error// Using select to receive from either data or error channel for contextselect {- case context = <-contextChan:+ case modelContext = <-contextChan:case err = <-contextErrChan:return err}@@ -91,10 +96,9 @@ func ApiPropose(prompt string, chatOnly bool, onStream types.OnStreamProposal) epayload := shared.PromptRequest{Prompt: prompt,- ModelContext: context,+ ModelContext: modelContext,Conversation: conversation,CurrentPlan: currentPlan,- ChatOnly: chatOnly,}jsonData, err := json.Marshal(payload)@@ -115,40 +119,86 @@ func ApiPropose(prompt string, chatOnly bool, onStream types.OnStreamProposal) e}reader := bufio.NewReader(resp.Body)- buf := make([]byte, 32)+ streamState := shared.NewPlanStreamState()go func() {for {- n, err := reader.Read(buf)- if err == io.EOF {- fmt.Println("EOF")- onStream("", true, nil)+ s, err := readUntilSeparator(reader, shared.STREAM_MESSAGE_SEPARATOR)+ if err != nil {+ fmt.Println("Error reading line:", err)+ streamState.Event(context.Background(), shared.EVENT_ERROR)+ onStream(types.OnStreamPlanParams{Content: "", State: streamState, Err: err})resp.Body.Close()return}- if err != nil {- fmt.Println("Error reading line:", err)- onStream("", true, err)++ if s == shared.STREAM_FINISHED || s == shared.STREAM_ABORTED {+ var evt string+ if s == shared.STREAM_FINISHED {+ evt = shared.EVENT_FINISH+ } else {+ evt = shared.STATE_ABORTED+ }+ err := streamState.Event(context.Background(), evt)+ if err != nil {+ fmt.Printf("Error triggering state change %s: %s\n", evt, err)+ }+ onStream(types.OnStreamPlanParams{Content: "", State: streamState, Err: err})resp.Body.Close()return}- s := string(buf[:n])+ if s == shared.STREAM_DESCRIPTION_PHASE {+ err = streamState.Event(context.Background(), shared.EVENT_DESCRIBE)+ } else if s == shared.STREAM_BUILD_PHASE {+ err = streamState.Event(context.Background(), shared.EVENT_BUILD)+ }- if strings.Contains(s, shared.STREAM_FINISHED) {- onStream("", true, nil)+ if err != nil {+ fmt.Println("Error setting state:", err)+ onStream(types.OnStreamPlanParams{Content: "", State: streamState, Err: err})resp.Body.Close()return}- onStream(s, false, nil)+ onStream(types.OnStreamPlanParams{Content: s, State: streamState, Err: nil})}}()return nil}-func ApiSummarize(text string) (*shared.SummarizeResponse, error) {+func (api *API) Abort(proposalId string) error {+ serverUrl := apiHost + "/abort"++ req, err := http.NewRequest("GET", serverUrl, nil)+ if err != nil {+ return fmt.Errorf("failed to create request: %s\n", err)+ }++ q := req.URL.Query()+ q.Add("proposalId", proposalId)+ req.URL.RawQuery = q.Encode()++ resp, err := http.DefaultClient.Do(req)+ if err != nil {+ return fmt.Errorf("failed to send request to server: %s\n", err)+ }++ defer resp.Body.Close()++ // Check the response status code+ if resp.StatusCode != http.StatusOK {+ // Read the error message from the body+ errorBody, _ := io.ReadAll(resp.Body)+ return fmt.Errorf("server returned an error %d: %s", resp.StatusCode,+ string(errorBody))+ }++ return nil+}++func (api *API) Summarize(text string) (*shared.SummarizeResponse, error) {serverUrl := apiHost + "/summarize"payload := shared.SummarizeRequest{@@ -170,7 +220,7 @@ func ApiSummarize(text string) (*shared.SummarizeResponse, error) {return nil, err}- fmt.Println("ApiSummarize response body:")+ fmt.Println("Summarize response body:")fmt.Println(string(body))var summarized shared.SummarizeResponse@@ -181,3 +231,18 @@ func ApiSummarize(text string) (*shared.SummarizeResponse, error) {return &summarized, nil}++func readUntilSeparator(reader *bufio.Reader, separator string) (string, error) {+ var result []byte+ sepBytes := []byte(separator)+ for {+ b, err := reader.ReadByte()+ if err != nil {+ return string(result), err+ }+ result = append(result, b)+ if len(result) >= len(sepBytes) && bytes.HasSuffix(result, sepBytes) {+ return string(result[:len(result)-len(separator)]), nil+ }+ }+}diff --git a/cli/lib/context.go b/cli/lib/context.goindex a76059e6..a853ec06 100644--- a/cli/lib/context.go+++ b/cli/lib/context.go@@ -118,7 +118,7 @@ func LoadContextOrDie(params *types.LoadContextParams) {hash := sha256.Sum256([]byte(body))sha := hex.EncodeToString(hash[:])- summaryResp, err := ApiSummarize(body)+ summaryResp, err := Api.Summarize(body)if err != nil {log.Fatalf("Failed to summarize the text: %v", err)}@@ -192,7 +192,7 @@ func LoadContextOrDie(params *types.LoadContextParams) {hash := sha256.Sum256([]byte(body))sha := hex.EncodeToString(hash[:])- summaryResp, err := ApiSummarize(body)+ summaryResp, err := Api.Summarize(body)if err != nil {log.Fatalf("Failed to summarize piped data: %v", err)}@@ -237,7 +237,7 @@ func LoadContextOrDie(params *types.LoadContextParams) {go func() {defer wg.Done()- flattenedPaths := flattenPaths(inputFilePaths, params, 0)+ flattenedPaths := FlattenPaths(inputFilePaths, params, 0)if params.NamesOnly {body := strings.Join(flattenedPaths, "\n")@@ -330,7 +330,7 @@ func LoadContextOrDie(params *types.LoadContextParams) {}()- summaryResp, err := ApiSummarize(body)+ summaryResp, err := Api.Summarize(body)if err != nil {log.Fatalf("Failed to summarize the file %s: %v", path, err)}@@ -401,7 +401,7 @@ func LoadContextOrDie(params *types.LoadContextParams) {hash := sha256.Sum256([]byte(body))sha := hex.EncodeToString(hash[:])- summaryResp, err := ApiSummarize(body)+ summaryResp, err := Api.Summarize(body)if err != nil {log.Fatalf("Failed to summarize content from URL %s: %v", url, err)}@@ -524,7 +524,7 @@ func GetAllContext(metaOnly bool) ([]shared.ModelContextPart, error) {// Only process .meta files and then look for their corresponding .body filesif strings.HasSuffix(filename, ".meta") {- fmt.Fprintf(os.Stderr, "Reading meta context file %s\n", filename)+ // fmt.Fprintf(os.Stderr, "Reading meta context file %s\n", filename)metaContent, err := os.ReadFile(filepath.Join(ContextSubdir, filename))if err != nil {@@ -543,7 +543,7 @@ func GetAllContext(metaOnly bool) ([]shared.ModelContextPart, error) {bodyFilename := strings.TrimSuffix(filename, ".meta") + ".body"bodyPath := filepath.Join(ContextSubdir, bodyFilename)- fmt.Fprintf(os.Stderr, "Reading body context file %s\n", bodyPath)+ // fmt.Fprintf(os.Stderr, "Reading body context file %s\n", bodyPath)bodyContent, err := os.ReadFile(bodyPath)if err != nil {diff --git a/cli/lib/fs.go b/cli/lib/fs.goindex d272a950..fbca52a6 100644--- a/cli/lib/fs.go+++ b/cli/lib/fs.go@@ -20,6 +20,7 @@ var CacheDir stringvar CurrentPlanName stringvar CurrentPlanRootDir stringvar PlanSubdir string+var PlanFilesDir stringvar ConversationSubdir stringvar ContextSubdir string@@ -91,6 +92,7 @@ func LoadCurrentPlan() error {CurrentPlanName = planSettings.NameCurrentPlanRootDir = filepath.Join(PlandexDir, CurrentPlanName)PlanSubdir = filepath.Join(CurrentPlanRootDir, "plan")+ PlanFilesDir = filepath.Join(PlanSubdir, "files")ConversationSubdir = filepath.Join(CurrentPlanRootDir, "conversation")ContextSubdir = filepath.Join(CurrentPlanRootDir, "context")@@ -140,7 +142,7 @@ func CwdIsPlan() bool {return parentDir == PlandexDir}-func flattenPaths(fileOrDirPaths []string, params *types.LoadContextParams, depth int16) []string {+func FlattenPaths(fileOrDirPaths []string, params *types.LoadContextParams, depth int16) []string {var wg sync.WaitGroupresPathsChan := make(chan string, len(fileOrDirPaths))@@ -164,7 +166,7 @@ func flattenPaths(fileOrDirPaths []string, params *types.LoadContextParams, deptif info.IsDir() {if depth < params.MaxDepth {- for _, subPath := range flattenPaths([]string{path}, params, depth+1) {+ for _, subPath := range FlattenPaths([]string{path}, params, depth+1) {resPathsChan <- subPath}} else if params.NamesOnly {diff --git a/cli/lib/plan.go b/cli/lib/plan.goindex 2b155c81..d57c7b5b 100644--- a/cli/lib/plan.go+++ b/cli/lib/plan.go@@ -22,7 +22,7 @@ func (s *safePlanFiles) Add(key string, value string) {var planFiles safePlanFiles-func worker(filesDir string, srcPath string, info os.FileInfo, err error, errCh chan<- error) {+func worker(PlanFilesDir string, srcPath string, info os.FileInfo, err error, errCh chan<- error) {if err != nil {errCh <- errreturn@@ -32,7 +32,7 @@ func worker(filesDir string, srcPath string, info os.FileInfo, err error, errCh}// Compute relative path- relPath, err := filepath.Rel(filesDir, srcPath)+ relPath, err := filepath.Rel(PlanFilesDir, srcPath)if err != nil {errCh <- errreturn@@ -51,17 +51,16 @@ func worker(filesDir string, srcPath string, info os.FileInfo, err error, errChfunc getCurrentPlanFiles() (shared.CurrentPlanFiles, error) {planFiles.data = make(map[string]string)- filesDir := filepath.Join(CurrentPlanRootDir, "plan", "files")// Check if filesDir exists- _, err := os.Stat(filesDir)+ _, err := os.Stat(PlanFilesDir)exists := !os.IsNotExist(err)if exists {errCh := make(chan error)// Enumerate all paths in [planDir]/files- err = filepath.Walk(filesDir, func(srcPath string, info os.FileInfo, err error) error {- go worker(filesDir, srcPath, info, err, errCh)+ err = filepath.Walk(PlanFilesDir, func(srcPath string, info os.FileInfo, err error) error {+ go worker(PlanFilesDir, srcPath, info, err, errCh)return nil})diff --git a/cli/lib/prompt.go b/cli/lib/prompt.goindex 68609cd6..fb80cb23 100644--- a/cli/lib/prompt.go+++ b/cli/lib/prompt.go@@ -1,57 +1,118 @@package libimport (+ "bufio"+ "context"+ "encoding/json""fmt""os""path/filepath"+ "plandex/types"+ "regexp"+ "strconv""time"+ "github.com/looplab/fsm"+ "github.com/plandex/plandex/shared"+"github.com/briandowns/spinner")-func Propose(prompt string, chatOnly bool) error {+type key struct {+ value rune+}++type openFileState struct {+ file *os.File+ buffer string+ jsonBuffer string+ wrotePrefix bool+ setExecPerms bool+ numTokens int+ isNew bool+ finished bool+}++func Propose(prompt string) error {s := spinner.New(spinner.CharSets[14], 100*time.Millisecond) // Choose spinner styles.Start()- fmt.Fprintln(os.Stderr, "Sending prompt...")timestamp := StringTs()reply := ""done := make(chan struct{})- s.Stop()-- // Switch to alternate screen and hide the cursor- fmt.Print("\x1b[?1049h\x1b[?25l")-- backToMain := func() {- // Switch back to main screen and show the cursor on exit- fmt.Print("\x1b[?1049l\x1b[?25h")- }-termState := ""updateTimer := time.NewTimer(100 * time.Millisecond)defer updateTimer.Stop()- var pendingUpdate bool+ var proposalId string+ var terminalHasPendingUpdate bool+ var endedReply bool++ var descJson string+ var desc *shared.PlanDescription+ var state *fsm.FSM++ fileStates := make(map[string]*openFileState)++ defer clearFileStates(fileStates)go func() {for range updateTimer.C {- if pendingUpdate {+ if terminalHasPendingUpdate {// Clear screenfmt.Print("\x1b[2J")// Move cursor to top-leftfmt.Print("\x1b[H")mdFull, _ := GetMarkdown(reply)fmt.Println(mdFull)+ fmt.Printf(displayHotkeys())termState = mdFull- pendingUpdate = false+ terminalHasPendingUpdate = false}updateTimer.Reset(100 * time.Millisecond)}}()- err := ApiPropose(prompt, chatOnly, func(content string, isFinished bool, err error) {+ keyChan := make(chan *key, 1)+ ctx, cancelKeywatch := context.WithCancel(context.Background())+ errChn := make(chan error, 1)++ endReply := func() {+ time.Sleep(100 * time.Millisecond)+ backToMain()+ fmt.Print(termState)+ err := appendConversation(timestamp, prompt, reply)+ if err != nil {+ fmt.Printf("failed to append conversation: %s\n", err)+ }+ endedReply = true+ }++ running := false+ queue := make(chan types.OnStreamPlanParams, 1)++ var handleStream types.OnStreamPlan+ handleStream = func(params types.OnStreamPlanParams) {+ if running {+ queue <- params+ return+ }++ defer func() {+ if len(queue) > 0 {+ params := <-queue+ handleStream(params)+ } else {+ running = false+ }+ }()++ state = params.State+ err := params.Err+ content := params.Content+onError := func(err error) {backToMain()fmt.Fprintln(os.Stderr, "Error:", err)@@ -63,25 +124,216 @@ func Propose(prompt string, chatOnly bool) error {return}- if isFinished {+ if proposalId == "" {+ if content == "" {+ onError(fmt.Errorf("proposal id not sent in first chunk"))+ return+ } else {+ proposalId = content+ s.Stop()+ // Switch to alternate screen and hide the cursor+ fmt.Print("\x1b[?1049h\x1b[?25l")++ return+ }+ }++ switch state.Current() {+ case shared.STATE_REPLYING, shared.STATE_REVISING:+ reply += content+ terminalHasPendingUpdate = true++ case shared.STATE_FINISHED:+ if !endedReply {+ endReply()+ }++ fmt.Println("Done")+close(done)return++ case shared.STATE_DESCRIBING:+ if content == shared.STREAM_DESCRIPTION_PHASE {+ endReply()++ } else {+ descJson = content+ err := json.Unmarshal([]byte(descJson), &desc)+ if err != nil {+ onError(fmt.Errorf("error parsing plan description: %v", err))+ return+ }++ if desc.MadePlan && (len(desc.Files) > 0 || desc.HasExec) {+ fmt.Println("Writing files:")+ for _, filePath := range desc.Files {+ fmt.Println(filePath)+ }+ if desc.HasExec {+ fmt.Println("exec.sh")+ }+ }+ }++ case shared.STATE_BUILDING:+ if content == shared.STREAM_BUILD_PHASE {+ // plan build mode started++ } else {+ var chunk shared.PlanChunk+ err := json.Unmarshal([]byte(content), &chunk)+ if err != nil {+ onError(fmt.Errorf("error parsing plan chunk: %v", err))+ return+ }++ err = writeChunkToFile(fileStates, chunk)+ if err != nil {+ onError(fmt.Errorf("error writing plan chunk to file. chunk: %v, err: %v", chunk, err))+ return+ }+ }}- reply += content- pendingUpdate = true- })+ }++ err := Api.Propose(prompt, handleStream)if err != nil {backToMain()return fmt.Errorf("failed to send prompt to server: %s\n", err)}- // block until streaming is done- <-done+ go func(ctx context.Context, errChn chan error) {+ for {+ select {+ case <-ctx.Done():+ return+ default:+ k, err := getUserInput()+ if err != nil {+ errChn <- err+ return+ }+ keyChan <- &key{k}+ }+ }+ }(ctx, errChn)++ handleKey := func(k *key) error {+ return handleKeyPress(k.value, proposalId)+ }++Loop:+ for {+ select {+ case k := <-keyChan:+ if err := handleKey(k); err != nil {+ cancelKeywatch()+ return err+ }+ case <-done: // Evidence of operation completion+ cancelKeywatch()+ break Loop+ case err := <-errChn: // Listening for errors+ cancelKeywatch()+ return err+ }+ }++ return nil+}++func Abort(proposalId string) error {+ err := Api.Abort(proposalId)+ return err+}++// Function for 'a' key action+func handleAbortKey(proposalId string) error {+ return Abort(proposalId)+}++// Function for 'r' key action+func handleReviseKey(proposalId string) error {+ // Terminate current operation+ err := Api.Abort(proposalId)+ if err != nil {+ return err+ }++ // Prompt the user for new message+ fmt.Println(">\"")+ reader := bufio.NewReader(os.Stdin)+ newMessage, _ := reader.ReadString('"')++ // Propose the new message+ err = Propose(newMessage)+ if err != nil {+ return err+ }++ fmt.Println("Revision proposed.")+ return nil+}++func handleKeyPress(input rune, proposalId string) error {+ switch input {+ case 'a':+ return handleAbortKey(proposalId)+ case 'r':+ return handleReviseKey(proposalId)+ default:+ return fmt.Errorf("invalid key pressed: %s", string(input))+ }+}++func displayHotkeys() string {+ return `+ ────────────────────────+ ` + "\x1b[1m(a)\x1b[0m" + `bort ` + "\x1b[1m(r)\x1b[0m" + `evise+ ────────────────────────+ `+}++func backToMain() {+ // Switch back to main screen and show the cursor on exit+ fmt.Print("\x1b[?1049l\x1b[?25h")+}++func gitCommit(commitMsg string) error {++ err := GitAddAndCommit(ConversationSubdir, commitMsg)+ if err != nil {+ return fmt.Errorf("failed to commit files to conversation dir: %s\n", err)+ }++ err = GitAddAndCommit(PlanSubdir, commitMsg)+ if err != nil {+ return fmt.Errorf("failed to commit files to plan dir: %s\n", err)+ }++ // Stage changes in the submodules in the root repo+ err = GitAdd(CurrentPlanRootDir, ConversationSubdir, true)+ if err != nil {+ return fmt.Errorf("failed to stage submodule changes in conversation dir: %s\n", err)+ }++ err = GitAdd(CurrentPlanRootDir, PlanSubdir, true)+ if err != nil {+ return fmt.Errorf("failed to stage submodule changes in plan dir: %s\n", err)+ }- backToMain()- fmt.Print(termState)+ // Commit these staged submodule changes in the root repo+ err = GitCommit(CurrentPlanRootDir, commitMsg, true)+ if err != nil {+ return fmt.Errorf("failed to commit submodule updates in root dir: %s\n", err)+ }++ return nil+}+func appendConversation(timestamp, prompt, reply string) error {// Create or append to conversation fileresponseTimestamp := StringTs()conversationFilePath := filepath.Join(ConversationSubdir, fmt.Sprintf("%s.md", timestamp))@@ -104,83 +356,157 @@ func Propose(prompt string, chatOnly bool) error {return nil}-func Confirm(proposalId string) error {-- // if len(response.Files) > 0 {- // filesDir := filepath.Join(PlanSubdir, "files")- // err = os.MkdirAll(filesDir, os.ModePerm)-- // if err != nil {- // return fmt.Errorf("failed to create files directory: %s\n", err)- // }-- // for path, contents := range response.Files {- // filePath := filepath.Join(filesDir, path)- // dir := filepath.Dir(filePath)-- // err = os.MkdirAll(dir, os.ModePerm)- // if err != nil {- // return fmt.Errorf("failed to create directory: %s\n", err)- // }-- // err = os.WriteFile(filePath, []byte(contents), 0644)- // if err != nil {- // return fmt.Errorf("failed to write file: %s\n", err)- // }- // }- // }-- // if response.Exec != "" {- // // write to exec.sh file- // execFilePath := filepath.Join(PlanSubdir, "exec.sh")- // execFile, err := os.OpenFile(execFilePath, os.O_CREATE|os.O_WRONLY, 0644)- // if err != nil {- // return fmt.Errorf("failed to write exec file: %s\n", err)- // }- // defer execFile.Close()-- // _, err = execFile.WriteString(response.Exec)- // if err != nil {- // return fmt.Errorf("failed to write exec file: %s\n", err)- // }-- // err = os.Chmod(execFilePath, 0755)- // if err != nil {- // return fmt.Errorf("failed to make exec file executable: %s\n", err)- // }- // }-- // err = GitAddAndCommit(ConversationSubdir, response.CommitMsg)- // if err != nil {- // return fmt.Errorf("failed to commit files to conversation dir: %s\n", err)- // }-- // err = GitAddAndCommit(PlanSubdir, response.CommitMsg)- // if err != nil {- // return fmt.Errorf("failed to commit files to plan dir: %s\n", err)- // }-- // // Stage changes in the submodules in the root repo- // err = GitAdd(CurrentPlanRootDir, ConversationSubdir, true)- // if err != nil {- // return fmt.Errorf("failed to stage submodule changes in conversation dir: %s\n", err)- // }-- // err = GitAdd(CurrentPlanRootDir, PlanSubdir, true)- // if err != nil {- // return fmt.Errorf("failed to stage submodule changes in plan dir: %s\n", err)- // }-- // // Commit these staged submodule changes in the root repo- // err = GitCommit(CurrentPlanRootDir, response.CommitMsg, true)- // if err != nil {- // return fmt.Errorf("failed to commit submodule updates in root dir: %s\n", err)- // }+var jsonStartRegex = regexp.MustCompile(`\{\s*?"content"\s*?:\s*"`)++func writeChunkToFile(+ fileStates map[string]*openFileState,+ chunk shared.PlanChunk) error {+ var filePath string+ if chunk.IsExec {+ filePath = filepath.Join(PlanSubdir, "exec.sh")+ } else {+ filePath = filepath.Join(PlanFilesDir, chunk.FilePath)+ }++ state, ok := fileStates[filePath]+ if !ok {+ state = &openFileState{isNew: true}+ fileStates[filePath] = state+ }++ if state.finished {+ return nil+ }++ err := os.MkdirAll(filepath.Dir(filePath), os.ModePerm)+ if err != nil {+ return fmt.Errorf("failed to create directory: %s\n", err)+ }++ file := state.file+ if file == nil {+ var openFlags int+ if state.isNew {+ openFlags = os.O_TRUNC | os.O_CREATE | os.O_WRONLY+ } else {+ openFlags = os.O_APPEND | os.O_CREATE | os.O_WRONLY+ }++ file, err = os.OpenFile(filePath, openFlags,+ 0644)+ if err != nil {+ return fmt.Errorf("failed to open plan file '%s': %v\n", filePath,+ err)+ }++ // don't cache the file handle on first chunk because we need to first clear the file+ // the second chunk will instantiate a new appending file handle and cache it+ // subsequent chunks will used the cached appending file handle+ if state.isNew {+ state.isNew = false+ defer file.Close()+ } else {+ state.file = file+ }+ }++ state.jsonBuffer += chunk.Content++ if state.wrotePrefix {+ var streamed shared.StreamedFile+ err = json.Unmarshal([]byte(state.jsonBuffer), &streamed)++ if err == nil {+ // get diff between full content and current buffer+ diff := streamed.Content[len(state.buffer):]+ cleaned := cleanJsonString(diff)++ state.finished = true++ _, err = file.WriteString(cleaned)+ if err != nil {+ return fmt.Errorf("failed to write to plan file '%s': %v\n", filePath, err)+ }+ } else {+ cleaned := cleanJsonString(chunk.Content)++ state.buffer += cleaned++ _, err := file.WriteString(cleaned)+ if err != nil {+ return fmt.Errorf("failed to write to plan file '%s': %v\n", filePath, err)+ }+ }++ } else {+ // Check if buffer matches start of JSON syntax+ if jsonStartRegex.MatchString(state.jsonBuffer) {+ // replace the json start regex in buffer+ s := jsonStartRegex.ReplaceAllString(state.jsonBuffer, "")+ cleaned := cleanJsonString(s)++ _, err := file.WriteString(cleaned)+ if err != nil {+ return fmt.Errorf("failed to write to plan file '%s': %v\n", filePath, err)+ }++ state.buffer = cleaned+ state.wrotePrefix = true+ }+ }++ if chunk.IsExec && !state.setExecPerms {+ err = os.Chmod(filePath, 0755)+ if err != nil {+ return fmt.Errorf("failed to make exec file executable: %s\n", err)+ }+ state.setExecPerms = true+ }++ state.numTokens += 1+ fileStates[filePath] = statereturn nil}-func Abort(proposalId string) error {+func cleanJsonString(s string) string {+ // replace escaped quotes with unescaped quotes+ s = regexp.MustCompile(`\\\"`).ReplaceAllString(s, `"`)- return nil+ // replace escaped backslashes with unescaped backslashes+ s = regexp.MustCompile(`\\\\`).ReplaceAllString(s, `\`)++ // replace escaped newlines with unescaped newlines+ s = regexp.MustCompile(`\\n`).ReplaceAllString(s, "\n")++ // replace escaped tabs with unescaped tabs+ s = regexp.MustCompile(`\\t`).ReplaceAllString(s, "\t")++ // replace escaped carriage returns with unescaped carriage returns+ s = regexp.MustCompile(`\\r`).ReplaceAllString(s, "\r")++ // replace escaped backspaces with unescaped backspaces+ s = regexp.MustCompile(`\\b`).ReplaceAllString(s, "\b")++ // replace escaped form feeds with unescaped form feeds+ s = regexp.MustCompile(`\\f`).ReplaceAllString(s, "\f")++ // replace escaped forward slashes with unescaped forward slashes+ s = regexp.MustCompile(`\\\/`).ReplaceAllString(s, "/")++ // replace escaped unicode characters with unescaped unicode characters+ s = regexp.MustCompile(`\\u([0-9a-fA-F]{4})`).ReplaceAllStringFunc(s, func(match string) string {+ unicode, _ := strconv.ParseInt(match[2:], 16, 32)+ return string(rune(unicode))+ })++ return s+}++func clearFileStates(fileStates map[string]*openFileState) {+ for path, state := range fileStates {+ state.file.Close()+ fmt.Println("closed file", path)+ delete(fileStates, path)+ }}diff --git a/cli/lib/url.go b/cli/lib/url.goindex 1936e965..e684d85d 100644--- a/cli/lib/url.go+++ b/cli/lib/url.go@@ -78,8 +78,10 @@ func SanitizeAndClipURL(url string, maxLength int) string {sanitized = strings.ReplaceAll(sanitized, "%", "_")sanitized = strings.ReplaceAll(sanitized, "*", "_")sanitized = strings.ReplaceAll(sanitized, " ", "_")-- return sanitized[:maxLength]+ if len(sanitized) > maxLength {+ return sanitized[:maxLength]+ }+ return sanitized}func IsValidURL(str string) bool {diff --git a/cli/lib/utils.go b/cli/lib/utils.goindex 34a3b92a..6306d7b7 100644--- a/cli/lib/utils.go+++ b/cli/lib/utils.go@@ -1,9 +1,12 @@package libimport (+ "fmt""path/filepath""strings""time"++ "github.com/eiannone/keyboard")func StringTs() string {@@ -32,3 +35,19 @@ func GetFileNameWithoutExt(path string) string {return name}++func getUserInput() (rune, error) {+ if err := keyboard.Open(); err != nil {+ return 0, fmt.Errorf("failed to open keyboard: %s\n", err)+ }+ defer func() {+ _ = keyboard.Close()+ }()++ char, _, err := keyboard.GetKey()+ if err != nil {+ return 0, fmt.Errorf("failed to read keypress: %s\n", err)+ }++ return char, nil+}diff --git a/cli/types/types.go b/cli/types/types.goindex 44a21885..839f0497 100644--- a/cli/types/types.go+++ b/cli/types/types.go@@ -1,6 +1,9 @@package types-import "github.com/plandex/plandex/shared"+import (+ "github.com/looplab/fsm"+ "github.com/plandex/plandex/shared"+)type LoadContextParams struct {Note string@@ -12,5 +15,17 @@ type LoadContextParams struct {Resources []string}-type OnStreamProposal func(content string, isFinished bool, err error)-type OnStreamPlan func(planChunk *shared.PlanChunk, isFinished bool, err error)+type OnStreamPlanParams struct {+ Content string+ State *fsm.FSM+ Err error+}++type OnStreamPlan func(params OnStreamPlanParams)++// APIHandler is an interface that represents the public API functions+type APIHandler interface {+ Propose(prompt string, onStream OnStreamPlan) error+ Summarize(text string) (*shared.SummarizeResponse, error)+ Abort(proposalId string) error+}diff --git a/server/go.mod b/server/go.modindex 76f1d012..5894b445 100644--- a/server/go.mod+++ b/server/go.mod@@ -10,4 +10,9 @@ require (github.com/sashabaranov/go-openai v1.15.1)+require (+ github.com/drhodes/golorem v0.0.0-20220328165741-da82e5b29246+ github.com/looplab/fsm v1.0.1 // indirect+)+replace github.com/plandex/plandex/shared => ../shareddiff --git a/server/go.sum b/server/go.sumindex 85290fa0..fbade34a 100644--- a/server/go.sum+++ b/server/go.sum@@ -1,8 +1,12 @@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/drhodes/golorem v0.0.0-20220328165741-da82e5b29246 h1:m0+1paUpmLlBpUxldAEvJZVCrNQpt2iyecCw4TdHdOc=+github.com/drhodes/golorem v0.0.0-20220328165741-da82e5b29246/go.mod h1:NsKVpF4h4j13Vm6Cx7Kf0V03aJKjfaStvm5rvK4+FyQ=github.com/google/uuid v1.3.1 h1:KjJaJ9iWZ3jOFZIf1Lqf4laDRCasjl0BCmnEGxkdLb4=github.com/google/uuid v1.3.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI=github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So=+github.com/looplab/fsm v1.0.1 h1:OEW0ORrIx095N/6lgoGkFkotqH6s7vaFPsgjLAaF5QU=+github.com/looplab/fsm v1.0.1/go.mod h1:PmD3fFvQEIsjMEfvZdrCDZ6y8VwKTwWNjlpEr6IKPO4=github.com/sashabaranov/go-openai v1.15.1 h1:BAV5LCVEzvZ3rN/Lh5NRVs2z6AahPt/jn5s2/cEEG0M=github.com/sashabaranov/go-openai v1.15.1/go.mod h1:lj5b/K+zjTSFxVLijLSTDZuP7adOgerWeFyZLUhAKRg=diff --git a/server/handlers/proposal.go b/server/handlers/proposal.goindex e2702cde..22ff83e0 100644--- a/server/handlers/proposal.go+++ b/server/handlers/proposal.go@@ -1,14 +1,12 @@package handlersimport (- "context""encoding/json""fmt""io""log""net/http""plandex-server/model/proposal"- "sync""github.com/plandex/plandex/shared")@@ -42,71 +40,49 @@ func ProposalHandler(w http.ResponseWriter, r *http.Request) {w.Header().Set("Transfer-Encoding", "chunked")w.Header().Set("Content-Type", "text/plain; charset=utf-8")- var cancel *context.CancelFuncvar isResponseClosed bool- var mu sync.Mutexdone := make(chan struct{})- onStream := func(content string, finished bool, err error) {+ // this is called serially; no need for mutex on 'isResponseClosed'+ onStream := func(content string, err error) {if isResponseClosed {return}if err != nil {- mu.Lock()isResponseClosed = true- mu.Unlock()- if cancel != nil {- (*cancel)()- }-log.Printf("Error writing stream content to client: %v\n", err)-- w.WriteHeader(http.StatusInternalServerError)- w.Write([]byte(err.Error()))-close(done)-- return- }-- if finished {- mu.Lock()- isResponseClosed = true- mu.Unlock()- if cancel != nil {- (*cancel)()- }- w.Write([]byte(shared.STREAM_FINISHED))- close(done)-return}// stream content to clientif content != "" {- _, err = w.Write([]byte(content))- if flusher, ok := w.(http.Flusher); ok {- flusher.Flush()- }+ // fmt.Println("writing stream content to client:", content)+ bytes := []byte(content + shared.STREAM_MESSAGE_SEPARATOR)+ _, err = w.Write(bytes)if err != nil {- mu.Lock()isResponseClosed = true- mu.Unlock()log.Printf("Error writing stream content to client: %v\n", err)- if cancel != nil {- (*cancel)()- }close(done)return}-+ if flusher, ok := w.(http.Flusher); ok {+ flusher.Flush()+ }}+ if content == shared.STREAM_FINISHED {+ isResponseClosed = true+ close(done)+ fmt.Println("proposal stream finished")+ return+ }}- cancel, err = proposal.CreateProposal(requestBody, onStream)+ fmt.Println("creating proposal and starting stream")+ err = proposal.CreateProposal(requestBody, onStream)if err != nil {log.Printf("Error creating proposal: %v\n", err)@@ -117,88 +93,7 @@ func ProposalHandler(w http.ResponseWriter, r *http.Request) {// block until streaming is done<-done-}--func ConfirmProposalHandler(w http.ResponseWriter, r *http.Request) {- log.Println("Received a request for ConfirmProposalHandler")-- proposalId := r.URL.Query().Get("proposalId")-- if proposalId == "" {- log.Println("Received empty proposalId field")- http.Error(w, "proposalId field is required", http.StatusBadRequest)- return- }-- w.Header().Set("Transfer-Encoding", "chunked")- w.Header().Set("Content-Type", "text/plain; charset=utf-8")-- var cancel *context.CancelFunc- var err error- var isResponseClosed bool-- onStream := func(planChunk *shared.PlanChunk, finished bool, err error) {- if isResponseClosed {- return- }-- if err != nil {- isResponseClosed = true- if cancel != nil {- (*cancel)()- }- log.Printf("Error writing plan chunk to client. chunk: , err: %v\n", planChunk, err)- w.WriteHeader(http.StatusInternalServerError)- w.Write([]byte(fmt.Sprintf("%v: %v", planChunk, err)))- return- }-- if finished {- isResponseClosed = true- if cancel != nil {- (*cancel)()- }- w.WriteHeader(http.StatusOK)- w.Write([]byte(shared.STREAM_FINISHED))-- return- }-- // stream content to client- if planChunk != nil {- // convert plan chunk to json- json, err := json.Marshal(planChunk)- if err != nil {- isResponseClosed = true- if cancel != nil {- (*cancel)()- }- log.Printf("Error marshalling plan chunk to json. chunk: , err: %v\n", planChunk, err)- w.WriteHeader(http.StatusInternalServerError)- w.Write([]byte(fmt.Sprintf("%v: %v", planChunk, err)))- return- }-- _, err = w.Write([]byte(json))-- if err != nil {- isResponseClosed = true- log.Printf("Error writing stream content to client: %v\n", err)- if cancel != nil {- (*cancel)()- }- return- }- }- }-- cancel, err = proposal.ConfirmProposal(proposalId, onStream)-- if err != nil {- log.Printf("Error confirming proposal: %v\n", err)- http.Error(w, "Error confirming proposal: "+err.Error(), http.StatusInternalServerError)- return- }+ fmt.Println("done")}diff --git a/server/main.go b/server/main.goindex 897c0a83..8f98eb28 100644--- a/server/main.go+++ b/server/main.go@@ -19,7 +19,6 @@ func main() {r := mux.NewRouter()r.HandleFunc("/proposal", handlers.ProposalHandler).Methods("POST")- r.HandleFunc("/confirm-proposal", handlers.ConfirmProposalHandler).Methods("PATCH")r.HandleFunc("/abort-proposal", handlers.AbortProposalHandler).Methods("DELETE")// r.HandleFunc("/revise-proposal", handlers.ReviseProposalHandler).Methods("PATCH")diff --git a/server/model/proposal/abort.go b/server/model/proposal/abort.goindex eac80b37..06d27929 100644--- a/server/model/proposal/abort.go+++ b/server/model/proposal/abort.go@@ -3,21 +3,23 @@ package proposalimport "fmt"func AbortProposal(proposalId string) error {- mu.Lock()- proposal, ok := proposalsMap[proposalId]-- if !ok {- mu.Unlock()+ proposal := proposals.Get(proposalId)+ if proposal == nil {return fmt.Errorf("proposal not found")}- if proposal.Cancel != nil {- (*proposal.Cancel)()+ aborted := proposal.Abort()+ if aborted {+ proposals.Set(proposalId, proposal)}- proposal.Aborted = true-- mu.Unlock()+ plan := plans.Get(proposalId)+ if plan != nil {+ aborted := plan.Abort()+ if aborted {+ plans.Set(proposalId, plan)+ }+ }return nil}diff --git a/server/model/proposal/confirm.go b/server/model/proposal/confirm.goindex 4353b77d..2ba86ddb 100644--- a/server/model/proposal/confirm.go+++ b/server/model/proposal/confirm.go@@ -5,136 +5,59 @@ import ("encoding/json""errors""fmt"- "io"+ "os""plandex-server/model""plandex-server/types""strings"- "sync""time"+ lorem "github.com/drhodes/golorem""github.com/plandex/plandex/shared""github.com/sashabaranov/go-openai""github.com/sashabaranov/go-openai/jsonschema")-type firstParseResponse struct {- Summary string `json:"summary"`- CommitMsg string `json:"commitMsg"`- Files []string `json:"files"`-}--type parseFileResponse struct {- Content string `json:"content"`-}--func ConfirmProposal(proposalId string, onStream types.OnStreamPlanFunc) (*context.CancelFunc, error) {- mu.Lock()- proposal, ok := proposalsMap[proposalId]- mu.Unlock()- if !ok {- return nil, errors.New("proposal not found")- }-- ctx, cancel := context.WithCancel(context.Background())- var wg sync.WaitGroup-- var proposalContent string- mu.Lock()- proposal.Cancel = &cancel- proposalsMap[proposalId] = proposal- proposalContent = proposal.Content- mu.Unlock()-- setError := func(err error) {- mu.Lock()- proposal := proposalsMap[proposalId]- proposal.ProposalError = err- proposalsMap[proposalId] = proposal- mu.Unlock()- }-- firstParseResp, err := model.Client.CreateChatCompletion(- ctx,- openai.ChatCompletionRequest{- Model: openai.GPT3Dot5Turbo,- Functions: []openai.FunctionDefinition{{- Name: "parse",- Parameters: &jsonschema.Definition{- Type: jsonschema.Object,- Properties: map[string]jsonschema.Definition{- "summary": {- Type: jsonschema.String,- Description: "High-level summary of changed proposed in previous response without code or commands.",- },- "commitMsg": {- Type: jsonschema.String,- Description: "A brief commit message for the changes proposed in AI's plan from previous response.",- },- "files": {- Type: jsonschema.Array,- Description: "An array of file paths in AI's plan from previous response that should be created or updated.",- Items: &jsonschema.Definition{- Type: jsonschema.String,- },- },- },- Required: []string{"summary", "commitMsg", "files"},- },- }},- Messages: []openai.ChatCompletionMessage{- {- Role: openai.ChatMessageRoleSystem,- Content: "You are an AI parser. You turn an AI's plan for a programming task into a high-level summary, a set of files and an exec script. You call the 'parse' function with these arguments: summary, commitMsg, files. Only call the 'parse' function in your response. Don't call any other function.",- },- {- Role: openai.ChatMessageRoleAssistant,- Content: proposalContent,- },- },- },- )-- if err != nil {- fmt.Printf("Error during first parse completion: %v\n", err)- setError(err)- return nil, err+func confirmProposal(proposalId string, onStream types.OnStreamFunc) error {+ goEnv := os.Getenv("GOENV")+ if goEnv == "test" {+ streamFilesLoremIpsum(onStream)+ return nil}- var firstParseStrRes string- for _, choice := range firstParseResp.Choices {- if choice.FinishReason == "function_call" && choice.Message.FunctionCall != nil && choice.Message.FunctionCall.Name == "parse" {- fnCall := choice.Message.FunctionCall- firstParseStrRes = fnCall.Arguments- }+ proposal := proposals.Get(proposalId)+ if proposal == nil {+ return errors.New("proposal not found")}- if firstParseStrRes == "" {- err = fmt.Errorf("no parse function call found in response")- setError(err)- return nil, err+ if !proposal.IsFinished() {+ return errors.New("proposal not finished")}- firstParseByteRes := []byte(firstParseStrRes)- var firstParsePromptResp firstParseResponse- err = json.Unmarshal(firstParseByteRes, &firstParsePromptResp)- if err != nil {- fmt.Printf("Error unmarshalling first parse response: %v\n", err)- fmt.Printf("JSON causing the error: %s\n", firstParseByteRes)- setError(err)- return nil, err- }+ ctx, cancel := context.WithCancel(context.Background())- for _, filePath := range firstParsePromptResp.Files {- wg.Add(1)+ plans.Set(proposalId, &types.Plan{+ ProposalId: proposalId,+ NumFiles: len(proposal.PlanDescription.Files),+ HasExec: proposal.PlanDescription.HasExec,+ Files: map[string]string{},+ FileErrs: map[string]error{},+ FilesFinished: map[string]bool{},+ ProposalStage: types.ProposalStage{+ CancelFn: &cancel,+ },+ })+ for _, filePath := range proposal.PlanDescription.Files {onError := func(err error) {- setError(err)- onStream(&shared.PlanChunk{FilePath: filePath}, true, err)+ fmt.Printf("Error for file %s: %v\n", filePath, err)+ plans.Update(proposalId, func(p *types.Plan) {+ p.FileErrs[filePath] = err+ p.SetErr(err)+ })+ onStream("", err)}go func(filePath string) {- defer wg.Done()-fmt.Println("Getting file from model: " + filePath)// get relevant file context (if any)@@ -156,7 +79,7 @@ func ConfirmProposal(proposalId string, onStream types.OnStreamPlanFunc) (*contefileMessages = append(fileMessages, openai.ChatCompletionMessage{Role: openai.ChatMessageRoleAssistant,- Content: proposalContent,+ Content: proposal.Content,},openai.ChatCompletionMessage{Role: openai.ChatMessageRoleUser,@@ -204,9 +127,7 @@ func ConfirmProposal(proposalId string, onStream types.OnStreamPlanFunc) (*contereturncase <-timer.C:// Timer triggered because no new chunk was received in time- fmt.Println("\nStream timeout due to inactivity")- err = fmt.Errorf("stream timeout due to inactivity")- onError(err)+ onError(fmt.Errorf("stream timeout due to inactivity"))returndefault:response, err := stream.Recv()@@ -219,57 +140,100 @@ func ConfirmProposal(proposalId string, onStream types.OnStreamPlanFunc) (*contetimer.Reset(model.OPENAI_STREAM_CHUNK_TIMEOUT)}- if errors.Is(err, io.EOF) {- fmt.Println("\nStream finished")- return- }-if err != nil {- fmt.Printf("\nStream error: %v\n", err)- onError(err)+ onError(fmt.Errorf("Stream error: %v", err))return}if len(response.Choices) == 0 {- fmt.Println("\nStream finished")+ onError(fmt.Errorf("Stream error: no choices"))return}- // TODO handle different finish reasons- if response.Choices[0].FinishReason != "" {- fmt.Println("\nStream finished")+ choice := response.Choices[0]++ if choice.FinishReason != "" {+ if choice.FinishReason == openai.FinishReasonFunctionCall {+ // parse the writeFile function call+ plan := plans.Get(proposalId)+ var resp shared.StreamedFile+ err := json.Unmarshal([]byte(plan.Files[filePath]), &resp)+ if err != nil {+ onError(fmt.Errorf("error parsing writeFile function call: %v", err))+ return+ }++ finished := false+ plans.Update(proposalId, func(plan *types.Plan) {+ plan.FilesFinished[filePath] = true++ if plan.DidFinish() {+ plan.Finish()+ finished = true+ }+ })++ if finished {+ fmt.Println("Stream finished")+ onStream(shared.STREAM_FINISHED, nil)+ return+ }++ } else {+ onError(fmt.Errorf("Stream finished without 'writeFile' function call. Reason: %s", choice.FinishReason))+ return+ }+return}var content stringdelta := response.Choices[0].Delta- if delta.FunctionCall != nil && delta.FunctionCall.Name == "writeFile" {- content = delta.FunctionCall.Arguments- } else {+ if delta.FunctionCall == nil {+ fmt.Printf("\nStream received data not for 'writeFile' function call")+ continue+ } else {+ content = delta.FunctionCall.Arguments}+ plans.Update(proposalId, func(p *types.Plan) {+ p.Files[filePath] += content+ })+chunk := &shared.PlanChunk{FilePath: filePath,Content: content,IsExec: false,}- fmt.Printf("%s: %s", filePath, content)- onStream(chunk, false, nil)+ // fmt.Printf("%s: %s", filePath, content)+ chunkJson, err := json.Marshal(chunk)+ if err != nil {+ onError(fmt.Errorf("error marshalling plan chunk: %v", err))+ return+ }+ onStream(string(chunkJson), nil)}}}()}(filePath)}- wg.Add(1)+ if !proposal.PlanDescription.HasExec {+ fmt.Println("No exec.sh to parse")+ return nil+ }+onExecErr := func(err error) {- setError(err)- onStream(&shared.PlanChunk{IsExec: true}, true, err)+ plans.Update(proposalId, func(p *types.Plan) {+ p.ExecErr = err+ p.SetErr(err)+ })++ onStream("", err)}go func() {- defer wg.Done()fmt.Println("Getting exec.sh from model: ")// Define the model request for exec.sh@@ -291,16 +255,16 @@ func ConfirmProposal(proposalId string, onStream types.OnStreamPlanFunc) (*conteMessages: []openai.ChatCompletionMessage{{Role: openai.ChatMessageRoleSystem,- Content: "You are an AI parser. You turn an AI's plan for a programming task into executable shell commands. Call the 'writeExec' function with the entire shell script as raw text, based on your previous response. Only call the 'writeExec' function in your response. Don't call any other function.",+ Content: "You are an AI parser that extracts shell commands from an AI-generated programming plan. Call the 'writeExec' function with any commands in '- exec' blocks in the previous response and combine them into a single shell script--pass only the raw text of the shell script to 'writeExec'. Only call the 'writeExec' function in your response. Don't call any other function.",},{Role: openai.ChatMessageRoleAssistant,- Content: proposalContent,+ Content: proposal.Content,},{Role: openai.ChatMessageRoleUser,Content: fmt.Sprintf(`- Based on your previous response, call the 'writeExec' function with the shell script that includes any commands that should be executed after any relevant files are created and/or updated. If no commands should be executed, pass only 'no exec commands' to the 'writeExec' function. Otherwise, pass the full script as raw text to the function and output nothing else.+ Based on your previous response, call the 'writeExec' function with a script that should be run after any relevant files are created and/or updated. If no commands should be executed, pass only 'no exec commands' to the 'writeExec' function. Otherwise, pass the full script as raw text to the function and output nothing else.`),},},@@ -341,30 +305,55 @@ func ConfirmProposal(proposalId string, onStream types.OnStreamPlanFunc) (*contetimer.Reset(model.OPENAI_STREAM_CHUNK_TIMEOUT)}- if errors.Is(err, io.EOF) {- fmt.Println("\nStream finished for exec.sh")- return- }-if err != nil {- fmt.Printf("\nStream error for exec.sh: %v\n", err)- onExecErr(err)+ onExecErr(fmt.Errorf("Stream error for exec.sh: %v", err))return}- // TODO handle different finish reasons- if response.Choices[0].FinishReason != "" {- fmt.Println("\nStream finished")+ if len(response.Choices) == 0 {+ onExecErr(fmt.Errorf("Stream error for exec.sh: no choices"))return}- if len(response.Choices) == 0 {- fmt.Println("\nStream finished for exec.sh")+ choice := response.Choices[0]++ if choice.FinishReason != "" {+ if choice.FinishReason == openai.FinishReasonFunctionCall {+ // parse the writeExec function call+ plan := plans.Get(proposalId)+ var resp shared.StreamedFile+ err := json.Unmarshal([]byte(plan.Exec), &resp)+ if err != nil {+ onExecErr(fmt.Errorf("error parsing writeExec function call: %v", err))+ return+ }++ finished := false+ plans.Update(proposalId, func(plan *types.Plan) {+ plan.ExecFinished = true++ if plan.DidFinish() {+ plan.Finish()+ finished = true+ }+ })++ if finished {+ fmt.Println("Stream finished")+ onStream(shared.STREAM_FINISHED, nil)+ return+ }++ } else {+ onExecErr(fmt.Errorf("Stream finished without 'writeExec' function call. Reason: %s", choice.FinishReason))+ return+ }+return}var content string- delta := response.Choices[0].Delta+ delta := choice.Deltaif delta.FunctionCall != nil && delta.FunctionCall.Name == "writeExec" {content = delta.FunctionCall.Arguments}@@ -376,24 +365,66 @@ func ConfirmProposal(proposalId string, onStream types.OnStreamPlanFunc) (*contefmt.Println("No commands to execute for exec.sh")} else {fmt.Println("Commands to execute for exec.sh")- onStream(&shared.PlanChunk{- IsExec: true,- Content: content,- }, false, nil)++ chunk := shared.PlanChunk{IsExec: true, Content: content}+ chunkJson, err := json.Marshal(chunk)+ if err != nil {+ onExecErr(fmt.Errorf("error marshalling exec.sh chunk: %v", err))+ return+ }++ onStream(string(chunkJson), nil)}}}}()- // Wait for all streams to finish and then inform the caller- go func() {- wg.Wait()- mu.Lock()- delete(proposalsMap, proposalId)- mu.Unlock()- onStream(nil, true, nil)- }()+ return nil+}++func streamFilesLoremIpsum(onStream types.OnStreamFunc) {+ writeChunk := func(filePath string, isExec bool, content string) {+ chunk := shared.PlanChunk{FilePath: filePath, Content: content, IsExec: isExec}+ chunkJson, _ := json.Marshal(chunk)+ onStream(string(chunkJson), nil)+ time.Sleep(50 * time.Millisecond) // Adding a small delay between files for effect+ }- return &cancel, nil+ // For each file in the proposal, stream some unstyled lorem ipsum content+ files := []string{"file1.txt", "file2.txt"}+ for _, filePath := range files {+ text := strings.Join([]string{lorem.Paragraph(2, 3), lorem.Paragraph(2, 3), lorem.Paragraph(2, 3)}, "\n\n")+ streamedFile := shared.StreamedFile{Content: text}+ fileContent, _ := json.Marshal(streamedFile)++ for _, line := range strings.Split(string(fileContent), "\n") {+ for _, word := range strings.Split(line, " ") {+ writeChunk(filePath, false, word+" ")+ }+ writeChunk(filePath, false, "\n")+ }+ }++ // For the exec.sh script, generate a script that echoes some lorem ipsum content++ echoContent := `#!/bin/sh+echo "` + lorem.Sentence(5, 6) + `"` ++ `+ echo "` + lorem.Sentence(5, 6) + `"` ++ `+ echo "hi"`++ fmt.Println("exec.sh content: " + echoContent)++ streamedFile := shared.StreamedFile{Content: echoContent}+ fileContent, _ := json.Marshal(streamedFile)++ for _, line := range strings.Split(string(fileContent), "\n") {+ for _, word := range strings.Split(line, " ") {+ writeChunk("", true, word+" ")+ }+ writeChunk("", true, "\n")+ }+ onStream(shared.STREAM_FINISHED, nil)}diff --git a/server/model/proposal/create.go b/server/model/proposal/create.goindex 3468d463..e505aea4 100644--- a/server/model/proposal/create.go+++ b/server/model/proposal/create.go@@ -2,38 +2,65 @@ package proposalimport ("context"- "errors"+ "encoding/json""fmt"- "io"- "sync"+ "os"+ "strings""time""plandex-server/model""plandex-server/types"+ lorem "github.com/drhodes/golorem""github.com/google/uuid""github.com/plandex/plandex/shared""github.com/sashabaranov/go-openai"+ "github.com/sashabaranov/go-openai/jsonschema")-// map to store the proposals-var (- proposalsMap = make(map[string]*types.Proposal)- mu sync.Mutex-)+const systemMessageHead = `+ You are Plandex, an AI programming and system administration assistant. You offer a structured, versioned, and iterative approach to AI-driven development.++ You and the programmer collaborate to create a 'plan' for the task at hand. A plan is a set of files and an 'exec' script with an attached context.++ 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 and commands to complete the task.+ 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.++ When suggesting changes that would modify files from the context or create new files, always precede them with the file path like this '- file_path:'.++ Code should always be inside a file block labelled with the path. You can have multiple blocks labelled with the same file 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 as the context file paths.++ Don't include unnecessary comments in code. Only add comments if they make the code significantly more readable. Make comments concise.++ When suggesting commands that should be run, always precede them with '- exec:'. For code or commands in markdown blocks, always include the language name after the opening triple backticks.++ 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.++ Context from the user:`// Proposal function to create a new proposal-func CreateProposal(req shared.PromptRequest, onStream types.OnStreamProposalFunc) (*context.CancelFunc, error) {- contextText := model.FormatModelContext(req.ModelContext)+func CreateProposal(req shared.PromptRequest, onStream types.OnStreamFunc) error {+ goEnv := os.Getenv("GOENV") // Fetch the GO_ENV environment variable- systemMessageText := `- You are Plandex, an AI programming and system administration assistant.- You help programmers with tasks, especially those that involve multiple files and shell commands. You offer a structured, versioned, and iterative approach to AI-driven development.- You and the programmer collaborate to create a 'plan' for the task at hand. A plan is a set of files and an 'exec' script with an attached context.- Based on user-provided context, please create a plan for the task. When suggesting changes that would modify files from the context or create new files, always precede them with the file path.- For code in markdown blocks, always include the language name after the opening triple backticks.- Context from the user:` + contextText+ fmt.Println("GOENV: " + goEnv)+ if goEnv == "test" {+ streamLoremIpsum(onStream)+ return nil+ }++ contextText := model.FormatModelContext(req.ModelContext)+ systemMessageText := systemMessageHead + contextTextsystemMessage := openai.ChatCompletionMessage{Role: openai.ChatMessageRoleSystem,Content: systemMessageText,@@ -52,27 +79,30 @@ func CreateProposal(req shared.PromptRequest, onStream types.OnStreamProposalFunContent: req.Prompt,})- for _, message := range messages {- fmt.Printf("%s: %s\n", message.Role, message.Content)- }+ // for _, message := range messages {+ // fmt.Printf("%s: %s\n", message.Role, message.Content)+ // }- proposalId, err := uuid.NewRandom()+ proposalUUID, err := uuid.NewRandom()if err != nil {fmt.Printf("Failed to generate proposal id: %v\n", err)- return nil, err+ return err}+ proposalId := proposalUUID.String()++ onStream(proposalId, nil)ctx, cancel := context.WithCancel(context.Background())// store the proposal- mu.Lock()- proposalsMap[proposalId.String()] = &types.Proposal{- Id: proposalId.String(),- Cancel: &cancel,+ proposals.Set(proposalId, &types.Proposal{+ Id: proposalId,ModelContext: &req.ModelContext,Content: "",- }- mu.Unlock()+ ProposalStage: types.ProposalStage{+ CancelFn: &cancel,+ },+ })modelReq := openai.ChatCompletionRequest{Model: openai.GPT4,@@ -83,29 +113,17 @@ func CreateProposal(req shared.PromptRequest, onStream types.OnStreamProposalFunstream, err := model.Client.CreateChatCompletionStream(ctx, modelReq)if err != nil {fmt.Printf("Error creating proposal GPT4 stream: %v\n", err)- mu.Lock()- delete(proposalsMap, proposalId.String()) // Remove the proposal from the map- mu.Unlock()- return nil, err- }-- onFinish := func() {- mu.Lock()- proposal := proposalsMap[proposalId.String()]- proposal.FinishedProposal = true- proposalsMap[proposalId.String()] = proposal- mu.Unlock()- onStream("", true, nil)+ proposals.Delete(proposalId)+ return err}onError := func(err error) {fmt.Printf("\nStream error: %v\n", err)- mu.Lock()- proposal := proposalsMap[proposalId.String()]- proposal.ProposalError = err- proposalsMap[proposalId.String()] = proposal- mu.Unlock()- onStream("", true, err)++ proposals.Update(proposalId, func(proposal *types.Proposal) {+ proposal.SetErr(err)+ })+ onStream("", err)}go func() {@@ -136,43 +154,216 @@ func CreateProposal(req shared.PromptRequest, onStream types.OnStreamProposalFuntimer.Reset(model.OPENAI_STREAM_CHUNK_TIMEOUT)}- if errors.Is(err, io.EOF) {- fmt.Println("\nStream finished")- onFinish()+ if err != nil {+ onError(fmt.Errorf("stream error: %v", err))return}- if err != nil {- onError(err)+ if len(response.Choices) == 0 {+ onError(fmt.Errorf("stream finished with no choices"))return}- if len(response.Choices) == 0 {- fmt.Println("\nStream finished")- onFinish()+ if len(response.Choices) > 1 {+ onError(fmt.Errorf("stream finished with more than one choice"))return}- // TODO handle different finish reasons- if response.Choices[0].FinishReason != "" {- fmt.Println("\nStream finished")- onFinish()+ choice := response.Choices[0]++ if choice.FinishReason != "" {+ onStream(shared.STREAM_DESCRIPTION_PHASE, nil)++ planDescription, planDescriptionJson, err := genPlanDescriptionJson(proposalId, ctx)++ if err != nil {+ onError(fmt.Errorf("failed to generate plan description json: %v", err))+ return+ }++ proposals.Update(proposalId, func(proposal *types.Proposal) {+ proposal.Finish(planDescription)+ })++ onStream(planDescriptionJson, nil)++ if planDescription.MadePlan && (len(planDescription.Files) > 0 || planDescription.HasExec) {+ onStream(shared.STREAM_BUILD_PHASE, nil)+ err = confirmProposal(proposalId, onStream)+ if err != nil {+ onError(fmt.Errorf("failed to confirm proposal: %v", err))+ }+ } else {+ onStream(shared.STREAM_FINISHED, nil)+ }++ return}- content := response.Choices[0].Delta.Content+ delta := choice.Delta+ content := delta.Content+ proposals.Update(proposalId, func(proposal *types.Proposal) {+ proposal.Content += content+ })- // add to the proposal- mu.Lock()- proposal := proposalsMap[proposalId.String()]- proposal.Content += content- proposalsMap[proposalId.String()] = proposal- mu.Unlock()+ // fmt.Printf("%s", content)+ onStream(content, nil)- fmt.Printf("%s", content)- onStream(content, false, nil)}}}()- return &cancel, nil+ return nil+}++func genPlanDescriptionJson(proposalId string, ctx context.Context) (*shared.PlanDescription, string, error) {+ proposal := proposals.Get(proposalId)++ planDescResp, err := model.Client.CreateChatCompletion(+ ctx,+ openai.ChatCompletionRequest{+ Model: openai.GPT4,+ Functions: []openai.FunctionDefinition{{+ Name: "describePlan",+ Parameters: &jsonschema.Definition{+ Type: jsonschema.Object,+ Properties: map[string]jsonschema.Definition{+ "madePlan": {+ Type: jsonschema.Boolean,+ Description: "Whether a plan was made that includes code or commands. Should be false if 'subtasks' is true",+ },+ "subtasks": {+ Type: jsonschema.Boolean,+ Description: "Whether the task is too large to be completed in a single response and was broken up into subtasks. If 'madePlan' is true, this should be false",+ },+ "commitMsg": {+ Type: jsonschema.String,+ Description: "A good commit message for the changes proposed. If 'madePlan' is false, this should be an empty string",+ },+ "files": {+ Type: jsonschema.Array,+ Description: "An array of file paths to be created or updated in the plan. If 'madePlan' is false, this should be an empty array.",+ Items: &jsonschema.Definition{+ Type: jsonschema.String,+ },+ },+ "hasExec": {+ Type: jsonschema.Boolean,+ Description: "Whether the plan includes any 'exec' blocks that include shell commands. If 'madePlan' is false, this should be false",+ },+ },+ Required: []string{"madePlan", "subtasks", "commitMsg", "files", "hasExec"},+ },+ }},+ Messages: []openai.ChatCompletionMessage{+ {+ Role: openai.ChatMessageRoleSystem,+ Content: "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 arguments 'madePlan', 'subtasks', 'commitMsg', 'files', and 'hasExec'. Only call the 'describePlan' function in your response. Don't call any other function.",+ },+ {+ Role: openai.ChatMessageRoleAssistant,+ Content: proposal.Content,+ },+ },+ },+ )++ var planDescStrRes string+ var planDesc shared.PlanDescription++ if err != nil {+ fmt.Printf("Error during plan description model call: %v\n", err)+ planDesc = shared.PlanDescription{}+ bytes, err := json.Marshal(planDesc)+ return &planDesc, string(bytes), err+ }++ for _, choice := range planDescResp.Choices {+ if choice.FinishReason == "function_call" &&+ choice.Message.FunctionCall != nil &&+ choice.Message.FunctionCall.Name == "describePlan" {+ fnCall := choice.Message.FunctionCall+ planDescStrRes = fnCall.Arguments+ }+ }++ if planDescStrRes == "" {+ fmt.Println("no describePlan function call found in response")+ planDesc = shared.PlanDescription{}+ bytes, err := json.Marshal(planDesc)+ return &planDesc, string(bytes), err+ }++ planDescByteRes := []byte(planDescStrRes)++ err = json.Unmarshal(planDescByteRes, &planDesc)+ if err != nil {+ fmt.Printf("Error unmarshalling plan description response: %v\n", err)+ return nil, "", err+ }++ bytes, err := json.Marshal(planDesc)+ if err != nil {+ fmt.Printf("Error marshalling plan description: %v\n", err)+ return nil, "", err+ }++ return &planDesc, string(bytes), nil+}++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(2, 3), lorem.Paragraph(2, 3), lorem.Paragraph(2, 3)}+ 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"},+ HasExec: true,+ }+ planDescriptionBytes, _ := json.Marshal(planDescription)+ planDescriptionJson := string(planDescriptionBytes)+ time.Sleep(2000 * time.Millisecond)++ onStream(planDescriptionJson, nil)++ onStream(shared.STREAM_BUILD_PHASE, nil)+ confirmProposal("", onStream)+}diff --git a/server/model/proposal/state.go b/server/model/proposal/state.gonew file mode 100644index 00000000..ab65ef58--- /dev/null+++ b/server/model/proposal/state.go@@ -0,0 +1,10 @@+package proposal++import (+ "plandex-server/types"+)++var (+ proposals types.SafeMap[types.Proposal] = *types.NewSafeMap[types.Proposal]()+ plans types.SafeMap[types.Plan] = *types.NewSafeMap[types.Plan]()+)diff --git a/server/types/plan.go b/server/types/plan.gonew file mode 100644index 00000000..b80961bd--- /dev/null+++ b/server/types/plan.go@@ -0,0 +1,22 @@+package types++type Plan struct {+ ProposalId string+ NumFiles int+ Files map[string]string+ HasExec bool+ Exec string+ ExecErr error+ ExecFinished bool+ FilesFinished map[string]bool+ FileErrs map[string]error+ ProposalStage+}++func (s *Plan) DidFinish() bool {+ if s.HasExec && !s.ExecFinished {+ return false+ }++ return len(s.FilesFinished) == int(s.NumFiles)+}diff --git a/server/types/proposal.go b/server/types/proposal.gonew file mode 100644index 00000000..1b7464a4--- /dev/null+++ b/server/types/proposal.go@@ -0,0 +1,31 @@+package types++import (+ "github.com/plandex/plandex/shared"+)++type Proposal struct {+ Id string+ ModelContext *shared.ModelContext+ Content string+ ProposalStage+ PlanDescription *shared.PlanDescription+}++type OnStreamFunc func(content string, err error)++func (s *Proposal) Finish(desc *shared.PlanDescription) bool {+ if desc == nil {+ return false+ }++ stopped := s.ProposalStage.Finish()+ if stopped {+ s.PlanDescription = desc+ }+ return stopped+}++func (s *Proposal) IsFinished() bool {+ return s.ProposalStage.Finished && s.PlanDescription != nil+}diff --git a/server/types/proposal_stage.go b/server/types/proposal_stage.gonew file mode 100644index 00000000..54dc94b9--- /dev/null+++ b/server/types/proposal_stage.go@@ -0,0 +1,61 @@+package types++import "context"++type ProposalStage struct {+ CancelFn *context.CancelFunc+ Finished bool+ Err error+ Aborted bool+}++func (s *ProposalStage) Abort() bool {+ if s.IsStopped() {+ return false+ }++ if s.CancelFn != nil {+ (*s.CancelFn)()+ }+ s.Aborted = true+ return true+}++func (s *ProposalStage) Finish() bool {+ if s.IsStopped() {+ return false+ }++ if s.CancelFn != nil {+ (*s.CancelFn)()+ }+ s.Finished = true+ return true+}++func (s *ProposalStage) IsStopped() bool {+ return s.Finished || s.Aborted || s.Err != nil+}++func (s *ProposalStage) Cancel() bool {+ if s.IsStopped() {+ return false+ }++ if s.CancelFn == nil {+ return false+ }++ (*s.CancelFn)()++ return true+}++func (s *ProposalStage) SetErr(err error) bool {+ if s.IsStopped() {+ return false+ }++ s.Err = err+ return s.Cancel()+}diff --git a/server/types/safe_map.go b/server/types/safe_map.gonew file mode 100644index 00000000..11d423ba--- /dev/null+++ b/server/types/safe_map.go@@ -0,0 +1,38 @@+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+}diff --git a/server/types/types.go b/server/types/types.godeleted file mode 100644index 1810f6a2..00000000--- a/server/types/types.go+++ /dev/null@@ -1,30 +0,0 @@-package types--import (- "context"-- "github.com/plandex/plandex/shared"-)--type Proposal struct {- Id string- Cancel *context.CancelFunc- ModelContext *shared.ModelContext- Content string- FinishedProposal bool- ProposalError error- Aborted bool- ConvertPlanError error-}--type OnStreamProposalFunc func(- content string,- finished bool,- err error,-)--type OnStreamPlanFunc func(- chunk *shared.PlanChunk,- finished bool,- err error,-)diff --git a/shared/const.go b/shared/const.godeleted file mode 100644index 92ff17c7..00000000--- a/shared/const.go+++ /dev/null@@ -1,3 +0,0 @@-package shared--const STREAM_FINISHED = "@@_PLANDEX_STREAM_FINISHED_@@"diff --git a/shared/go.mod b/shared/go.modindex f935bc71..d553c4d8 100644--- a/shared/go.mod+++ b/shared/go.mod@@ -2,4 +2,7 @@ module sharedgo 1.21.0-require github.com/sashabaranov/go-openai v1.15.1+require (+ github.com/looplab/fsm v1.0.1+ github.com/sashabaranov/go-openai v1.15.1+)diff --git a/shared/go.sum b/shared/go.sumindex dc20bd21..ec921fdc 100644--- a/shared/go.sum+++ b/shared/go.sum@@ -1,2 +1,4 @@+github.com/looplab/fsm v1.0.1 h1:OEW0ORrIx095N/6lgoGkFkotqH6s7vaFPsgjLAaF5QU=+github.com/looplab/fsm v1.0.1/go.mod h1:PmD3fFvQEIsjMEfvZdrCDZ6y8VwKTwWNjlpEr6IKPO4=github.com/sashabaranov/go-openai v1.15.1 h1:BAV5LCVEzvZ3rN/Lh5NRVs2z6AahPt/jn5s2/cEEG0M=github.com/sashabaranov/go-openai v1.15.1/go.mod h1:lj5b/K+zjTSFxVLijLSTDZuP7adOgerWeFyZLUhAKRg=diff --git a/shared/stream.go b/shared/stream.gonew file mode 100644index 00000000..522bbb37--- /dev/null+++ b/shared/stream.go@@ -0,0 +1,50 @@+package shared++import "github.com/looplab/fsm"++const STREAM_MESSAGE_SEPARATOR = "@@PX@@"+const STREAM_FINISHED = "@@PXEND@@"+const STREAM_DESCRIPTION_PHASE = "@@PXDESC@@"+const STREAM_BUILD_PHASE = "@@PXBUILD@@"+const STREAM_ABORTED = "@@PXABORT@@"++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"++const STATE_REPLYING = "replying"+const STATE_DESCRIBING = "describing"+const STATE_BUILDING = "building"+const STATE_FINISHED = "finished"+const STATE_ABORTED = "aborted"+const STATE_REVISING = "revising"+const STATE_CANCELED = "canceled"+const STATE_ERROR = "error"++func NewPlanStreamState() *fsm.FSM {+ sm := fsm.NewFSM(+ STATE_REPLYING,+ fsm.Events{+ // Define state transitions+ {Name: EVENT_DESCRIBE, Src: []string{STATE_REPLYING, STATE_REPLYING}, Dst: STATE_DESCRIBING},+ {Name: EVENT_BUILD, Src: []string{STATE_DESCRIBING}, Dst: STATE_BUILDING},+ {Name: EVENT_FINISH, Src: []string{STATE_DESCRIBING, STATE_BUILDING}, Dst: STATE_FINISHED},+ {Name: EVENT_ABORT, Src: []string{STATE_REPLYING, STATE_DESCRIBING, STATE_BUILDING, STATE_REVISING},+ 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, STATE_REVISING}},+ },+ fsm.Callbacks{},+ )++ return sm+}++type StreamedFile struct {+ Content string `json:"content"`+}diff --git a/shared/types.go b/shared/types.goindex b74e3a13..5b1e50ae 100644--- a/shared/types.go+++ b/shared/types.go@@ -14,7 +14,6 @@ type PromptRequest struct {ModelContext ModelContext `json:"modelContext"`Conversation []openai.ChatCompletionMessageCurrentPlan CurrentPlanFiles `json:"currentPlan"`- ChatOnly bool}type SummarizeRequest struct {@@ -59,11 +58,20 @@ type PlanSettings struct {}type PlanChunk struct {+ Type string `json:"type"`FilePath string `json:"filePath"`Content string `json:"content"`IsExec bool `json:"isExec"`}+type PlanDescription struct {+ MadePlan bool `json:"madePlan"`+ Subtasks bool `json:"subtasks"`+ CommitMsg string `json:"commitMsg"`+ Files []string `json:"files"`+ HasExec bool `json:"hasExec"`+}+// type Plan struct {// Id string// Name string