Skip to content

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

remove sectionization logic + simpler ux + various improvements and cleanup

Dane Schneiderc66403c43a1c
diff --git a/cli/cmd/chat.go b/cli/cmd/chat.go
deleted file mode 100644
index 6defc2eb..00000000
--- a/cli/cmd/chat.go
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
-Copyright © 2023 NAME HERE <EMAIL ADDRESS>
-*/
-package cmd
-
-import (
- "fmt"
- "os"
- "plandex/lib"
-
- "github.com/spf13/cobra"
-)
-
-// chatCmd represents the prompt command
-var chatCmd = &cobra.Command{
- Use: "chat [prompt]",
- Short: "",
- Long: ``,
- Run: chat,
-}
-
-func chat(cmd *cobra.Command, args []string) {
- p := args[0]
-
- err := lib.Propose(p)
- if err != nil {
- fmt.Fprintln(os.Stderr, "Prompt error:", err)
- return
- }
-}
-
-func init() {
- RootCmd.AddCommand(chatCmd)
-
- // Here you will define your flags and configuration settings.
-
- // Cobra supports Persistent Flags which will work for this command
- // and all subcommands, e.g.:
- // chatCmd.PersistentFlags().String("foo", "", "A help for foo")
-
- // Cobra supports local flags which will only run when this command
- // is called directly, e.g.:
- // chatCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
-}
diff --git a/cli/cmd/context_ls.go b/cli/cmd/context_ls.go
index a1b12c79..7d29e4da 100644
--- a/cli/cmd/context_ls.go
+++ b/cli/cmd/context_ls.go
@@ -34,11 +34,10 @@ func contextLs(cmd *cobra.Command, args []string) {
totalTokens += part.NumTokens
if i != 0 {
- fmt.Print("\n\n")
+ fmt.Print("\n")
}
- fmt.Printf("Name: %s\n", part.Name)
-
+ fmt.Println("Index:", i)
if part.FilePath != "" {
fmt.Printf("File: %s\n", part.FilePath)
}
@@ -49,11 +48,9 @@ func contextLs(cmd *cobra.Command, args []string) {
fmt.Printf("Tokens: %d\n", part.NumTokens)
fmt.Printf("Updated: %s\n", part.UpdatedAt)
-
- fmt.Printf("Summary:\n%s", part.Summary)
}
- fmt.Printf("\n\nTotal tokens: %d\n", totalTokens)
+ fmt.Printf("\nTotal tokens: %d\n", totalTokens)
}
diff --git a/cli/cmd/current.go b/cli/cmd/current.go
index 02c475a9..1b868f32 100644
--- a/cli/cmd/current.go
+++ b/cli/cmd/current.go
@@ -8,9 +8,10 @@ import (
)
var currentCmd = &cobra.Command{
- Use: "current",
- Short: "Get the current plan",
- Run: current,
+ Use: "current",
+ Aliases: []string{"c"},
+ Short: "Get the current plan",
+ Run: current,
}
func init() {
@@ -18,5 +19,9 @@ func init() {
}
func current(cmd *cobra.Command, args []string) {
+ if lib.CurrentPlanName == "" {
+ fmt.Println("No current plan.")
+ return
+ }
fmt.Println(lib.CurrentPlanName)
}
diff --git a/cli/cmd/load.go b/cli/cmd/load.go
index 7a613c23..fa5812bb 100644
--- a/cli/cmd/load.go
+++ b/cli/cmd/load.go
@@ -10,11 +10,12 @@ import (
var note string
var contextLoadCmd = &cobra.Command{
- Use: "load [files-or-urls...]",
- Short: "Load context from various inputs",
- Long: `Load context from a file path, a directory, a URL, text, or piped data.`,
- Args: cobra.MinimumNArgs(1),
- Run: contextLoad,
+ Use: "load [files-or-urls...]",
+ Aliases: []string{"l"},
+ Short: "Load context from various inputs",
+ Long: `Load context from a file path, a directory, a URL, text, or piped data.`,
+ Args: cobra.MinimumNArgs(1),
+ Run: contextLoad,
}
func init() {
diff --git a/cli/cmd/new.go b/cli/cmd/new.go
index a31b9cb1..a8fa6a50 100644
--- a/cli/cmd/new.go
+++ b/cli/cmd/new.go
@@ -8,101 +8,68 @@ import (
"log"
"os"
"path/filepath"
- "time"
"plandex/lib"
- "plandex/types"
- "github.com/briandowns/spinner"
+ "github.com/fatih/color"
"github.com/spf13/cobra"
)
-var context []string
var name string
// newCmd represents the new command
var newCmd = &cobra.Command{
- Use: "new [prompt]",
- Short: "",
- Long: ``,
- Args: cobra.RangeArgs(0, 1),
- Run: new,
+ Use: "new",
+ Short: "Start a new plan.",
+ // Long: ``,
+ Args: cobra.ExactArgs(0),
+ Run: new,
}
func init() {
- addSharedContextFlags(newCmd)
- newCmd.Flags().StringSliceVarP(&context, "context", "c", []string{}, "Context to load into the new plan (file paths or urls)")
- newCmd.Flags().StringVarP(&name, "name", "n", "", "Name of the new plan")
RootCmd.AddCommand(newCmd)
+ newCmd.Flags().StringVarP(&name, "name", "n", "", "Name of the new plan")
}
-// const minActionDelay = 1000 * time.Millisecond
-
func new(cmd *cobra.Command, args []string) {
- var prompt string
- if len(args) > 0 {
- prompt = args[0]
- }
-
- if name == "" && prompt == "" {
- log.Fatalln("Error: either prompt or --name/-n flag must be provided")
- }
+ isDraft := false
if name == "" {
- summaryResp, err := lib.Api.Summarize(prompt)
- if err != nil {
- log.Fatalf("Failed to get a name for the prompt: %v", err)
- }
- name = lib.GetFileNameWithoutExt(summaryResp.FileName)
+ name = "draft"
+ isDraft = true
}
- fmt.Println("Creating plan '" + name + "'... ")
-
// Check git installed
if !lib.IsCommandAvailable("git") {
log.Fatalln("Error: git is required")
}
- // fmt.Fprintln(os.Stderr, "✅ Confirmed git is installed")
- // Search recursively upward for a .plandex directory
plandexDir, _, err := lib.FindOrCreatePlandex()
if err != nil {
fmt.Fprintln(os.Stderr, "Error finding or creating .plandex dir:", err)
return
}
- // if newd {
- // fmt.Fprintln(os.Stderr, "✅ Created .plandex directory at "+plandexDir)
- // } else {
- // fmt.Fprintln(os.Stderr, "✅ Found .plandex directory at "+plandexDir)
- // }
- // If 'name' directory already exists, tack on an integer to differentiate
- rootDir := filepath.Join(plandexDir, name)
- _, err = os.Stat(rootDir)
- exists := !os.IsNotExist(err)
-
- postfix := 1
- var nameWithPostfix string
- for exists {
- postfix += 1
- nameWithPostfix = fmt.Sprintf("%s.%d", name, postfix)
- rootDir = filepath.Join(plandexDir, nameWithPostfix)
- _, err = os.Stat(rootDir)
- exists = !os.IsNotExist(err)
+ err = lib.ClearDraftPlans()
+ if err != nil {
+ fmt.Fprintln(os.Stderr, "Error clearing draft plans:", err)
+ return
}
- if nameWithPostfix != "" {
- name = nameWithPostfix
+
+ name, err = lib.DedupPlanName(name)
+ if err != nil {
+ fmt.Fprintln(os.Stderr, "Error deduping plan name:", err)
+ return
}
- // Create current plan json file with current plan name
- planFilePath := filepath.Join(plandexDir, "current_plan.json")
- planFile, err := os.OpenFile(planFilePath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
+ rootDir := filepath.Join(plandexDir, name)
+
+ // Set the current plan to 'name'
+ err = lib.SetCurrentPlan(name)
if err != nil {
- fmt.Fprintln(os.Stderr, "Error creating current_plan.json:", err)
+ fmt.Fprintln(os.Stderr, "Error setting current plan:", err)
return
}
- defer planFile.Close()
- _, err = planFile.WriteString(fmt.Sprintf(`{"name": "%s"}`, name))
// Create 'name' directory inside .plandex
err = os.Mkdir(rootDir, os.ModePerm)
@@ -189,38 +156,13 @@ func new(cmd *cobra.Command, args []string) {
// fmt.Fprintln(os.Stderr, "✅ Initialized context and plan git repositories")
- err = lib.LoadCurrentPlan()
-
- if err != nil {
- fmt.Fprintln(os.Stderr, "Error setting current plan:", err)
- return
- }
-
- if len(context) > 0 {
- fmt.Println("Loading context... ")
- s := spinner.New(spinner.CharSets[14], 100*time.Millisecond)
- s.Start()
-
- lib.LoadContextOrDie(&types.LoadContextParams{
- Note: note,
- MaxTokens: maxTokens,
- Recursive: recursive,
- MaxDepth: maxDepth,
- NamesOnly: namesOnly,
- Truncate: truncate,
- Resources: context,
- })
-
- time.Sleep(500 * time.Millisecond)
- s.Stop()
+ if isDraft {
+ fmt.Println("✅ Started new plan")
+ } else {
+ fmt.Printf("✅ Started new plan: %s\n", color.New(color.Bold, color.FgHiWhite).Sprint(name))
}
- if prompt != "" {
- err = lib.Propose(prompt)
- if err != nil {
- fmt.Fprintln(os.Stderr, "Prompt error:", err)
- return
- }
- }
+ fmt.Println()
+ lib.PrintCmds("load", "tell")
}
diff --git a/cli/cmd/rm.go b/cli/cmd/rm.go
index 68c543e0..40e5c041 100644
--- a/cli/cmd/rm.go
+++ b/cli/cmd/rm.go
@@ -7,6 +7,7 @@ import (
"plandex/lib"
+ "github.com/fatih/color"
"github.com/spf13/cobra"
)
@@ -43,7 +44,7 @@ func del(cmd *cobra.Command, args []string) {
planDir := filepath.Join(plandexDir, name)
if _, err := os.Stat(planDir); os.IsNotExist(err) {
- fmt.Fprintln(os.Stderr, "Error: plan with name '"+name+"' does not exist")
+ fmt.Fprintf(os.Stderr, "Plan %s does not exist", color.New(color.Bold).Sprint(name))
return
}
@@ -53,7 +54,15 @@ func del(cmd *cobra.Command, args []string) {
return
}
- fmt.Fprintln(os.Stderr, "✅ Plan '"+name+"' has been deleted.")
+ if lib.CurrentPlanName == name {
+ err = os.Remove(filepath.Join(plandexDir, "current_plan.json"))
+ if err != nil {
+ fmt.Fprintln(os.Stderr, "Error deleting current plan:", err)
+ return
+ }
+ }
+
+ fmt.Printf("✅ Deleted plan %s\n", color.New(color.Bold).Sprint(name))
}
func delAll() {
diff --git a/cli/cmd/tell.go b/cli/cmd/tell.go
new file mode 100644
index 00000000..449a5836
--- /dev/null
+++ b/cli/cmd/tell.go
@@ -0,0 +1,135 @@
+/*
+Copyright © 2023 NAME HERE <EMAIL ADDRESS>
+*/
+package cmd
+
+import (
+ "fmt"
+ "os"
+ "os/exec"
+ "plandex/lib"
+ "strings"
+ "time"
+
+ "github.com/briandowns/spinner"
+ "github.com/spf13/cobra"
+)
+
+const defaultEditor = "nano"
+
+var promptFile string
+
+// tellCmd represents the prompt command
+var tellCmd = &cobra.Command{
+ Use: "tell [prompt]",
+ Aliases: []string{"t"},
+ Short: "Send a prompt for the current plan.",
+ // Long: ``,
+ Args: cobra.RangeArgs(0, 1),
+ Run: tell,
+}
+
+func init() {
+ RootCmd.AddCommand(tellCmd)
+
+ tellCmd.Flags().StringVarP(&promptFile, "file", "f", "", "File containing prompt")
+}
+
+func tell(cmd *cobra.Command, args []string) {
+ var prompt string
+
+ if len(args) > 0 {
+ prompt = args[0]
+ } else if promptFile != "" {
+ bytes, err := os.ReadFile(promptFile)
+ if err != nil {
+ fmt.Fprintln(os.Stderr, "Error reading prompt file:", err)
+ return
+ }
+ prompt = string(bytes)
+ } else {
+ editor := os.Getenv("EDITOR")
+ if editor == "" {
+ editor = os.Getenv("VISUAL")
+ if editor == "" {
+ editor = defaultEditor
+ }
+ }
+
+ tempFile, err := os.CreateTemp(os.TempDir(), "plandex_prompt_*")
+ if err != nil {
+ fmt.Fprintln(os.Stderr, "Failed to create temporary file:", err)
+ return
+ }
+
+ instruction := "Write your prompt below, then save and exit to send it to Plandex.\n\n"
+ _, err = tempFile.WriteString(instruction)
+
+ editorCmd := prepareEditorCommand(editor, tempFile.Name())
+ editorCmd.Stdin = os.Stdin
+ editorCmd.Stdout = os.Stdout
+ editorCmd.Stderr = os.Stderr
+ err = editorCmd.Run()
+ if err != nil {
+ fmt.Fprintln(os.Stderr, "Error opening editor:", err)
+ return
+ }
+
+ bytes, err := os.ReadFile(tempFile.Name())
+ if err != nil {
+ fmt.Fprintln(os.Stderr, "Error reading temporary file:", err)
+ return
+ }
+
+ prompt = string(bytes)
+
+ err = os.Remove(tempFile.Name())
+ if err != nil {
+ fmt.Fprintln(os.Stderr, "Error removing temporary file:", err)
+ return
+ }
+
+ prompt = strings.TrimPrefix(prompt, strings.TrimSpace(instruction))
+ prompt = strings.TrimSpace(prompt)
+
+ if prompt != "" {
+ fmt.Print("Prompt:\n\n")
+ fmt.Println(prompt)
+ }
+ }
+
+ if prompt == "" {
+ fmt.Fprintln(os.Stderr, "🤷‍♂️ No prompt to send.")
+ return
+ }
+
+ if lib.CurrentPlanIsDraft() {
+ s := spinner.New(spinner.CharSets[33], 100*time.Millisecond)
+ s.Start()
+
+ summaryResp, err := lib.Api.Summarize(prompt)
+ if err != nil {
+ fmt.Fprintln(os.Stderr, "\nError summarizing prompt:", err)
+ return
+ }
+ lib.RenameCurrentDraftPlan(lib.GetFileNameWithoutExt(summaryResp.FileName))
+ s.Stop()
+ }
+
+ err := lib.Propose(prompt)
+ if err != nil {
+ fmt.Fprintln(os.Stderr, "Prompt error:", err)
+ return
+ }
+}
+
+func prepareEditorCommand(editor string, filename string) *exec.Cmd {
+ switch editor {
+ case "vim":
+ return exec.Command(editor, "+normal G$", "+startinsert!", filename)
+ case "nano":
+ return exec.Command(editor, "+99999999", filename)
+ default:
+ return exec.Command(editor, filename)
+ }
+}
diff --git a/cli/lib/api.go b/cli/lib/api.go
index 7508bc67..8575e0fc 100644
--- a/cli/lib/api.go
+++ b/cli/lib/api.go
@@ -232,38 +232,6 @@ func (api *API) Summarize(text string) (*shared.SummarizeResponse, error) {
return &summarized, nil
}
-func (api *API) Sectionize(text string) (*shared.SectionizeResponse, error) {
- serverUrl := apiHost + "/sectionize"
-
- payload := shared.SectionizeRequest{
- Text: text,
- }
- jsonData, err := json.Marshal(payload)
- if err != nil {
- return nil, err
- }
-
- resp, err := http.Post(serverUrl, "application/json", bytes.NewBuffer(jsonData))
- if err != nil {
- return nil, err
- }
- defer resp.Body.Close()
-
- rawBody, err := io.ReadAll(resp.Body)
- if err != nil {
- return nil, err
- }
-
- var sectionized shared.SectionizeResponse
- err = json.Unmarshal(rawBody, &sectionized)
- if err != nil {
- fmt.Printf("Failed JSON: %s\n", rawBody) // Printing the JSON causing the failure
- return nil, err
- }
-
- return &sectionized, nil
-}
-
func readUntilSeparator(reader *bufio.Reader, separator string) (string, error) {
var result []byte
sepBytes := []byte(separator)
diff --git a/cli/lib/context_load.go b/cli/lib/context_load.go
index 30db0381..2e703d82 100644
--- a/cli/lib/context_load.go
+++ b/cli/lib/context_load.go
@@ -16,10 +16,13 @@ import (
"sync/atomic"
"time"
+ "github.com/briandowns/spinner"
"github.com/plandex/plandex/shared"
)
func LoadContextOrDie(params *types.LoadContextParams) (int, int) {
+ s := spinner.New(spinner.CharSets[33], 100*time.Millisecond)
+ s.Start()
var contextState shared.ModelContextState
contextStateFilePath := filepath.Join(ContextSubdir, "context.json")
@@ -112,8 +115,8 @@ func LoadContextOrDie(params *types.LoadContextParams) (int, int) {
fileName := GetFileNameWithoutExt(summaryResp.FileName)
contextPart := shared.ModelContextPart{
- Name: fmt.Sprintf("%d.%s", atomic.LoadUint32(&counter), fileName),
- Summary: summaryResp.Summary,
+ Name: fmt.Sprintf("%d.%s", atomic.LoadUint32(&counter), fileName),
+ // Summary: summaryResp.Summary,
Body: body,
Sha: sha,
NumTokens: numTokens,
@@ -187,8 +190,8 @@ func LoadContextOrDie(params *types.LoadContextParams) (int, int) {
fileName := GetFileNameWithoutExt(summaryResp.FileName)
contextPart := shared.ModelContextPart{
- Name: fmt.Sprintf("%d.%s", atomic.LoadUint32(&counter), fileName),
- Summary: summaryResp.Summary,
+ Name: fmt.Sprintf("%d.%s", atomic.LoadUint32(&counter), fileName),
+ // Summary: summaryResp.Summary,
Body: body,
Sha: sha,
NumTokens: numTokens,
@@ -264,8 +267,7 @@ func LoadContextOrDie(params *types.LoadContextParams) (int, int) {
}()
contextPart := shared.ModelContextPart{
- Name: fmt.Sprintf("%d-filenames", atomic.LoadUint32(&counter)),
- Summary: "filenames",
+ Name: fmt.Sprintf("%d-directory-layout", atomic.LoadUint32(&counter)),
Body: body,
Sha: sha,
NumTokens: numTokens,
@@ -322,55 +324,14 @@ func LoadContextOrDie(params *types.LoadContextParams) (int, int) {
}()
- errCh := make(chan error, 2)
- summaryCh := make(chan shared.SummarizeResponse, 1)
- // sectionizeCh := make(chan shared.SectionizeResponse, 1)
-
- go func() {
- resp, err := Api.Summarize(body)
- if err != nil {
- errCh <- fmt.Errorf("failed to summarize the file %s: %v", path, err)
- return
- }
- summaryCh <- *resp
- }()
-
- // go func() {
- // resp, err := Api.Sectionize(body)
- // if err != nil {
- // errCh <- fmt.Errorf("failed to sectionize the file %s: %v", path, err)
- // return
- // }
- // sectionizeCh <- *resp
- // }()
-
- // var sectionizeResp shared.SectionizeResponse
- var summaryResp shared.SummarizeResponse
-
- // Waiting for the summary response or error
- // for i := 0; i < 2; i++ {
- for i := 0; i < 1; i++ {
- select {
- case err := <-errCh:
- log.Fatalf("Failed to summarize or sectionize the file %s: %v", path, err)
- case summaryResp = <-summaryCh:
- // case sectionizeResp = <-sectionizeCh:
- case <-time.After(time.Second * 30): // adjust the timeout as necessary
- log.Fatalf("Timeout while waiting to receive the responses for file %s", path)
- }
- }
-
- // get just the filename
_, fileName := filepath.Split(path)
contextPart := shared.ModelContextPart{
Name: fmt.Sprintf("%d.%s", atomic.LoadUint32(&counter), fileName),
- Summary: summaryResp.Summary,
Body: body,
FilePath: path,
Sha: sha,
NumTokens: numTokens,
- // SectionEnds: sectionizeResp.SectionEnds,
UpdatedAt: StringTs(),
}
@@ -428,14 +389,14 @@ func LoadContextOrDie(params *types.LoadContextParams) (int, int) {
hash := sha256.Sum256([]byte(body))
sha := hex.EncodeToString(hash[:])
- summaryResp, err := Api.Summarize(body)
- if err != nil {
- log.Fatalf("Failed to summarize content from URL %s: %v", url, err)
- }
+ // summaryResp, err := Api.Summarize(body)
+ // if err != nil {
+ // log.Fatalf("Failed to summarize content from URL %s: %v", url, err)
+ // }
contextPart := shared.ModelContextPart{
- Name: fmt.Sprintf("%d.%s", atomic.LoadUint32(&counter), SanitizeAndClipURL(url, 70)),
- Summary: summaryResp.Summary,
+ Name: fmt.Sprintf("%d.%s", atomic.LoadUint32(&counter), SanitizeAndClipURL(url, 70)),
+ // Summary: summaryResp.Summary,
Body: body,
Sha: sha,
NumTokens: numTokens,
@@ -519,7 +480,7 @@ func LoadContextOrDie(params *types.LoadContextParams) (int, int) {
}
}
}
- msg += fmt.Sprintf(" into context (%d tokens)", tokensAdded)
+ msg += fmt.Sprintf(" into context (%d tokens added, %d tokens total)", tokensAdded, totalTokens)
if err != nil {
log.Fatalf("Failed to get total tokens: %v", err)
@@ -544,7 +505,8 @@ func LoadContextOrDie(params *types.LoadContextParams) (int, int) {
log.Fatalf("failed to commit submodule updates in root dir: %s\n", err)
}
- fmt.Fprint(os.Stderr, "\n✅ "+msg+"\n")
+ s.Stop()
+ fmt.Fprintln(os.Stderr, "✅ "+msg)
return tokensAdded, totalTokens
}
diff --git a/cli/lib/fs.go b/cli/lib/fs.go
index b88a5a96..dbc7ac82 100644
--- a/cli/lib/fs.go
+++ b/cli/lib/fs.go
@@ -57,7 +57,7 @@ func init() {
go func() {
defer wg.Done()
- PlandexDir, ProjectRoot = FindPlandex()
+ PlandexDir, ProjectRoot = findPlandex()
err = LoadCurrentPlan()
if err != nil {
@@ -125,19 +125,6 @@ func FindOrCreatePlandex() (string, bool, error) {
return dir, false, nil
}
-func FindPlandex() (string, string) {
- searchPath := Cwd
- for searchPath != "/" {
- dir := filepath.Join(searchPath, ".plandex")
- if _, err := os.Stat(dir); !os.IsNotExist(err) {
- return dir, searchPath
- }
- searchPath = filepath.Dir(searchPath)
- }
-
- return "", ""
-}
-
func CwdIsPlan() bool {
// check if parent directory of cwd is '.plandex'
parentDir := filepath.Dir(Cwd)
@@ -193,3 +180,16 @@ func FlattenPaths(fileOrDirPaths []string, params *types.LoadContextParams) []st
return resPaths
}
+
+func findPlandex() (string, string) {
+ searchPath := Cwd
+ for searchPath != "/" {
+ dir := filepath.Join(searchPath, ".plandex")
+ if _, err := os.Stat(dir); !os.IsNotExist(err) {
+ return dir, searchPath
+ }
+ searchPath = filepath.Dir(searchPath)
+ }
+
+ return "", ""
+}
diff --git a/cli/lib/plan.go b/cli/lib/plan_files.go
similarity index 100%
rename from cli/lib/plan.go
rename to cli/lib/plan_files.go
diff --git a/cli/lib/plans.go b/cli/lib/plans.go
new file mode 100644
index 00000000..d71258eb
--- /dev/null
+++ b/cli/lib/plans.go
@@ -0,0 +1,133 @@
+package lib
+
+import (
+ "fmt"
+ "os"
+ "path/filepath"
+ "regexp"
+)
+
+func SetCurrentPlan(name string) error {
+ if PlandexDir == "" {
+ return fmt.Errorf("PlandexDir not set")
+ }
+
+ currentPlanFilePath := filepath.Join(PlandexDir, "current_plan.json")
+ err := os.WriteFile(currentPlanFilePath, []byte(fmt.Sprintf(`{"name": "%s"}`, name)), 0644)
+ if err != nil {
+ return err
+ }
+
+ return nil
+}
+
+func ClearCurrentPlan() error {
+ if PlandexDir == "" {
+ return fmt.Errorf("PlandexDir not set")
+ }
+
+ currentPlanFilePath := filepath.Join(PlandexDir, "current_plan.json")
+ err := os.Remove(currentPlanFilePath)
+ if err != nil {
+ return err
+ }
+
+ return nil
+}
+
+var draftRegex = regexp.MustCompile("^draft(\\.[0-9]+)?$")
+
+func ClearDraftPlans() error {
+ if PlandexDir == "" {
+ return fmt.Errorf("PlandexDir not set")
+ }
+
+ files, err := os.ReadDir(PlandexDir)
+ if err != nil {
+ return err
+ }
+
+ for _, f := range files {
+ if draftRegex.MatchString(f.Name()) {
+ err = os.RemoveAll(filepath.Join(PlandexDir, f.Name()))
+ if err != nil {
+ return err
+ }
+ }
+ }
+
+ return nil
+}
+
+func CurrentPlanIsDraft() bool {
+ if PlandexDir == "" {
+ return false
+ }
+ if CurrentPlanName == "" {
+ return false
+ }
+
+ return draftRegex.MatchString(CurrentPlanName)
+}
+
+func RenameCurrentDraftPlan(name string) error {
+ if PlandexDir == "" {
+ return fmt.Errorf("PlandexDir not set")
+ }
+ if CurrentPlanName == "" {
+ return fmt.Errorf("CurrentPlanName not set")
+ }
+
+ if CurrentPlanIsDraft() {
+ oldPath := filepath.Join(PlandexDir, CurrentPlanName)
+ newPath := filepath.Join(PlandexDir, name)
+
+ err := os.Rename(oldPath, newPath)
+ if err != nil {
+ return err
+ }
+
+ err = SetCurrentPlan(name)
+ if err != nil {
+ return err
+ }
+ }
+
+ return nil
+}
+
+func DedupPlanName(name string) (string, error) {
+ if PlandexDir == "" {
+ return "", fmt.Errorf("PlandexDir not set")
+ }
+
+ // If 'name' directory already exists, tack on an integer to differentiate
+ planDir := filepath.Join(PlandexDir, name)
+ _, err := os.Stat(planDir)
+ if err != nil {
+ if !os.IsNotExist(err) {
+ return "", err
+ }
+ }
+ exists := !os.IsNotExist(err)
+
+ postfix := 1
+ var nameWithPostfix string
+ for exists {
+ postfix += 1
+ nameWithPostfix = fmt.Sprintf("%s.%d", name, postfix)
+ planDir = filepath.Join(PlandexDir, nameWithPostfix)
+ _, err = os.Stat(planDir)
+ if err != nil {
+ if !os.IsNotExist(err) {
+ return "", err
+ }
+ }
+ exists = !os.IsNotExist(err)
+ }
+ if nameWithPostfix != "" {
+ name = nameWithPostfix
+ }
+
+ return name, nil
+}
diff --git a/cli/lib/proposal.go b/cli/lib/proposal.go
index a1ab66b1..19077eca 100644
--- a/cli/lib/proposal.go
+++ b/cli/lib/proposal.go
@@ -22,10 +22,10 @@ type key struct {
func Propose(prompt string) error {
var err error
fmt.Println("Sending prompt... ")
- s := spinner.New(spinner.CharSets[14], 100*time.Millisecond)
+ s := spinner.New(spinner.CharSets[33], 100*time.Millisecond)
s.Start()
- time.Sleep(500 * time.Millisecond)
+ // time.Sleep(500 * time.Millisecond)
timestamp := StringTs()
reply := ""
@@ -52,7 +52,7 @@ func Propose(prompt string) error {
numStreamedTokensByPath := make(map[string]int)
replyTokenCounter := shared.NewReplyInfo()
- var tokensAddedByFile map[string]int
+ // var tokensAddedByFile map[string]int
// currentPlanTokensByFilePath, err := loadCurrentPlanTokensByFilePath()
// if err != nil {
@@ -111,7 +111,8 @@ func Propose(prompt string) error {
backToMain()
fmt.Print(termState)
var totalTokens int
- _, tokensAddedByFile, totalTokens = replyTokenCounter.FinishAndRead()
+ // _, tokensAddedByFile, totalTokens = replyTokenCounter.FinishAndRead()
+ _, _, totalTokens = replyTokenCounter.FinishAndRead()
err := appendConversation(types.AppendConversationParams{
Timestamp: timestamp,
Prompt: prompt,
@@ -261,7 +262,7 @@ func Propose(prompt string) error {
// contextPart, foundContext := contextByFilePath[filePath]
// filePathInPlan := isFilePathInPlan(filePath)
numStreamedTokens := numStreamedTokensByPath[filePath]
- added := tokensAddedByFile[filePath]
+ // added := tokensAddedByFile[filePath]
fmtStr := "- %s | %d tokens"
fmtArgs := []interface{}{filePath, numStreamedTokens}
@@ -270,10 +271,11 @@ func Propose(prompt string) error {
if finished {
fmtStr += " | done ✅"
- } else if added > 0 {
- fmtStr += " / %d estimated"
- fmtArgs = append(fmtArgs, added)
}
+ // else if added > 0 {
+ // fmtStr += " / %d estimated"
+ // fmtArgs = append(fmtArgs, added)
+ // }
clearCurrentLine()
fmt.Printf(fmtStr+"\n", fmtArgs...)
@@ -282,12 +284,6 @@ func Propose(prompt string) error {
if wroteFile {
// fmt.Printf("Wrote %d / %d files", len(finishedByPath), len(files))
if len(finishedByPath) == len(files) {
- // err = writeFilesFromSections(apiReq, finishedByPath)
- // if err != nil {
- // onError(err)
- // return
- // }
-
filesFinished = true
if streamFinished {
diff --git a/cli/lib/stream.go b/cli/lib/stream.go
index a4854f8b..3cc90034 100644
--- a/cli/lib/stream.go
+++ b/cli/lib/stream.go
@@ -56,17 +56,23 @@ func receiveFileToken(params *receiveFileChunkParams) (bool, error) {
var replacements shared.StreamedReplacements
err = json.Unmarshal([]byte(jsonBuffers[chunk.Path]), &replacements)
- if err == nil {
+ if err == nil && len(replacements.Replacements) > 0 {
streamedType = "replacements"
} else {
err = json.Unmarshal([]byte(jsonBuffers[chunk.Path]), &streamed)
- if err == nil {
+ if err == nil && streamed.Content != "" {
streamedType = "file"
}
}
if err == nil {
+ if streamedType == "" {
+ err = fmt.Errorf("failed to parse streamed data to a replacement or full file")
+ log.Println(err)
+ return false, err
+ }
+
// log.Println("Parsed JSON. Streamed type: " + streamedType)
var writeToPath string
@@ -104,6 +110,11 @@ func receiveFileToken(params *receiveFileChunkParams) (bool, error) {
content = string(bytes)
}
+ // Uncomment below for debugging updates
+ // updatesPath := filepath.Join(CurrentPlanRootDir, "updates", chunk.Path)
+ // os.MkdirAll(filepath.Dir(updatesPath), os.ModePerm)
+ // os.WriteFile(updatesPath+"-"+"replacements"+"-"+StringTs(), []byte(buffer), 0644)
+
// log.Println("Content before replacements: " + content)
// ensure replacements are ordered by index in content (error if not present)
@@ -140,10 +151,12 @@ func receiveFileToken(params *receiveFileChunkParams) (bool, error) {
// log.Println("Content after replacements: " + content)
} else if streamedType == "file" {
content = streamed.Content
- } else {
- err = fmt.Errorf("unknown streamed type: %s", streamedType)
- log.Println(err)
- return false, err
+
+ // Uncomment below for debugging updates
+ // updatesPath := filepath.Join(CurrentPlanRootDir, "updates", chunk.Path)
+ // os.MkdirAll(filepath.Dir(updatesPath), os.ModePerm)
+ // os.WriteFile(updatesPath+"-"+"file"+"-"+StringTs(), []byte(buffer), 0644)
+
}
err := os.MkdirAll(filepath.Dir(writeToPath), os.ModePerm)
@@ -232,11 +245,7 @@ func loadCurrentPlanTokensByFilePath() (map[string]int, error) {
currentPlanTokensByFilePath := make(map[string]int)
- for path, numTokens := range currentPlanTokensByPath {
- filePath, _, err := shared.SplitSectionPath(path)
- if err != nil {
- return nil, fmt.Errorf("error parsing section number: %v", err)
- }
+ for filePath, numTokens := range currentPlanTokensByPath {
currentPlanTokensByFilePath[filePath] += numTokens
}
diff --git a/cli/lib/term.go b/cli/lib/term.go
index d7096571..9bf3a14a 100644
--- a/cli/lib/term.go
+++ b/cli/lib/term.go
@@ -5,9 +5,30 @@ import (
"os"
"strings"
+ "github.com/fatih/color"
"golang.org/x/term"
)
+var cmdDesc = map[string][2]string{
+ "load": {"l", "load files/urls or pipe data into context"},
+ "tell": {"t", "describe a task, ask a question, or just chat"},
+}
+
+func PrintCmds(cmds ...string) {
+ for _, cmd := range cmds {
+ config, ok := cmdDesc[cmd]
+ if !ok {
+ continue
+ }
+
+ alias := config[0]
+ desc := config[1]
+ cmd = strings.Replace(cmd, alias, fmt.Sprintf("(%s)", alias), 1)
+
+ fmt.Printf("%s 👉 %s\n", color.New(color.Bold, color.BgCyan, color.FgHiWhite).Sprintf(" plandex %s ", cmd), desc)
+ }
+}
+
func alternateScreen() {
// Switch to alternate screen and hide the cursor
fmt.Print("\x1b[?1049h\x1b[?25l")
diff --git a/cli/types/types.go b/cli/types/types.go
index afc5e3cf..f009352f 100644
--- a/cli/types/types.go
+++ b/cli/types/types.go
@@ -27,7 +27,6 @@ type OnStreamPlan func(params OnStreamPlanParams)
type APIHandler interface {
Propose(prompt, parentProposalId string, onStream OnStreamPlan) (*shared.PromptRequest, error)
Summarize(text string) (*shared.SummarizeResponse, error)
- Sectionize(text string) (*shared.SectionizeResponse, error)
Abort(proposalId string) error
}
diff --git a/server/handlers/sectionize.go b/server/handlers/sectionize.go
deleted file mode 100644
index 7e8a55d1..00000000
--- a/server/handlers/sectionize.go
+++ /dev/null
@@ -1,50 +0,0 @@
-package handlers
-
-import (
- "encoding/json"
- "io"
- "log"
- "net/http"
-
- "plandex-server/model"
- "github.com/plandex/plandex/shared"
-)
-
-func SectionizeHandler(w http.ResponseWriter, r *http.Request) {
- log.Println("Received a request for SectionizeHandler")
-
- // Read the request body
- body, err := io.ReadAll(r.Body)
- if err != nil {
- log.Printf("Error reading request body: %v\n", err)
- http.Error(w, "Error reading request body", http.StatusInternalServerError)
- return
- }
- defer r.Body.Close()
-
- // Unmarshal the request body to obtain the 'text' that needs sectionizing
- var requestBody shared.SectionizeRequest
- if err := json.Unmarshal(body, &requestBody); err != nil {
- log.Printf("Error parsing request body: %v\n", err)
- http.Error(w, "Error parsing request body", http.StatusBadRequest)
- return
- }
-
- if requestBody.Text == "" {
- log.Println("Received an empty text field")
- http.Error(w, "text field is required", http.StatusBadRequest)
- return
- }
-
- // Call the model's Sectionize function and handle any returned errors
- modelRes, err := model.Sectionize(requestBody.Text)
- if err != nil {
- log.Printf("Error in sectionizing text: %v\n", err)
- http.Error(w, "Error in sectionizing text: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- log.Println("Successfully processed sectionize request")
- // Write the response from the model's Sectionize function back to the client
- w.Write(modelRes)
-}
diff --git a/server/main.go b/server/main.go
index c2ccbf9e..96370b1c 100644
--- a/server/main.go
+++ b/server/main.go
@@ -22,7 +22,6 @@ func main() {
r.HandleFunc("/abort-proposal", handlers.AbortProposalHandler).Methods("DELETE")
// r.HandleFunc("/revise-proposal", handlers.ReviseProposalHandler).Methods("PATCH")
r.HandleFunc("/summarize", handlers.SummarizeHandler).Methods("POST")
- r.HandleFunc("/sectionize", handlers.SectionizeHandler).Methods("POST") // Registering the new endpoint here
// Get port from the environment variable or default to 8088
port := os.Getenv("PORT")
@@ -32,4 +31,4 @@ func main() {
log.Printf("Plandex server is running on :%s", port)
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%s", port), r))
-}
\ No newline at end of file
+}
diff --git a/server/model/lib/context.go b/server/model/lib/context.go
index ca5494ac..bddf634c 100644
--- a/server/model/lib/context.go
+++ b/server/model/lib/context.go
@@ -16,19 +16,8 @@ func FormatModelContext(context shared.ModelContext) (string, int) {
var args []any
if part.FilePath != "" {
- if len(part.SectionEnds) > 0 {
-
- sections := shared.GetFullSections(part.Body, part.SectionEnds)
-
- for i, section := range sections {
- fmtStr += "\n\n- %s:\n\n```\n%s\n```"
- args = append(args, fmt.Sprintf("%s-%d", part.FilePath, i), section)
- }
-
- } else {
- fmtStr = "\n\n- %s:\n\n```\n%s\n```"
- args = append(args, part.FilePath, part.Body)
- }
+ fmtStr = "\n\n- %s:\n\n```\n%s\n```"
+ args = append(args, part.FilePath, part.Body)
} else if part.Url != "" {
fmtStr = "\n\n- %s:\n\n```\n%s\n```"
args = append(args, part.Url, part.Body)
diff --git a/server/model/lib/sections.go b/server/model/lib/sections.go
deleted file mode 100644
index e253f665..00000000
--- a/server/model/lib/sections.go
+++ /dev/null
@@ -1,37 +0,0 @@
-package lib
-
-import (
- "strings"
-)
-
-func GetSectionEnds(text string, lines []string) []int {
- var indexes []int
- currentPosition := 0 // Variable to keep track of the current position in the text
-
- for _, line := range lines {
- // Finding the index of the line in the text, starting from currentPosition
- index := strings.Index(text[currentPosition:], line)
-
- if index != -1 {
- // Since we are slicing the text, we need to add currentPosition to get the actual index
- index += currentPosition
-
- // Updating the currentPosition to be after the current match
- currentPosition = index + len(line)
-
- // Appending the actual index of the match
- indexes = append(indexes, index)
- }
- }
-
- return indexes[1:] // Removing the first index since it's always 0
-}
-
-func CleanSectionJson(json []byte) []byte {
- s := string(json)
-
- strings.ReplaceAll(s, `\n`, "")
- strings.ReplaceAll(s, `\t`, "")
-
- return []byte(s)
-}
diff --git a/server/model/proposal/confirm.go b/server/model/proposal/confirm.go
index e32f3d27..e932b25b 100644
--- a/server/model/proposal/confirm.go
+++ b/server/model/proposal/confirm.go
@@ -18,16 +18,13 @@ import (
const systemPrompt = `
[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.
+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.
If the current state of the file within the plan is included, apply your changes to the current state of the file.
-Decide whether it is more efficient to rewrite the entire file or a list of replacements. Do whichever will use fewer tokens to update the file. 'writeReplacement' is more efficient if you are only changing a small amount of text. 'writeEntireFile' is more efficient if you are changing a large amount of text.
-
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. Ouput the entire updated 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 must be a substring of the current file.
- The 'old' text must not overlap with any other 'old' text in the list of replacements.
@@ -212,7 +209,6 @@ func confirmProposal(proposalId string, onStream types.OnStreamFunc) error {
fmtArgs := []interface{}{filePath}
currentState := proposal.Request.CurrentPlan.Files[filePath]
- fmtStr += "\nCurrent state of %s:\n```\n%s\n```"
if currentState != "" {
fmtArgs = append(fmtArgs, currentState)
} else if fileContext != nil {
diff --git a/server/model/proposal/create.go b/server/model/proposal/create.go
index 73d2fb7f..d049259a 100644
--- a/server/model/proposal/create.go
+++ b/server/model/proposal/create.go
@@ -28,7 +28,7 @@ const systemMessageHead = `You are Plandex, an AI programming and system adminis
- 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. Precede the code block with the file path like this '- file_path:'--for example:
+ 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:
@@ -48,13 +48,15 @@ const systemMessageHead = `You are Plandex, an AI programming and system adminis
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\nPlease 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."
+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/sectionize.go b/server/model/sectionize.go
deleted file mode 100644
index d2f02500..00000000
--- a/server/model/sectionize.go
+++ /dev/null
@@ -1,121 +0,0 @@
-package model
-
-import (
- "context"
- "encoding/json"
- "fmt"
-
- "plandex-server/model/lib"
-
- "github.com/davecgh/go-spew/spew"
- "github.com/plandex/plandex/shared"
- "github.com/sashabaranov/go-openai"
- "github.com/sashabaranov/go-openai/jsonschema"
-)
-
-type sectionizeResult = struct {
- Sections []string `json:"sections"`
-}
-
-func Sectionize(text string) ([]byte, error) {
- resp, err := Client.CreateChatCompletion(
- context.Background(),
- openai.ChatCompletionRequest{
- Model: openai.GPT4,
- Functions: []openai.FunctionDefinition{{
- Name: "sectionized",
- Parameters: &jsonschema.Definition{
- Type: jsonschema.Object,
- Properties: map[string]jsonschema.Definition{
- "sections": {
- Type: jsonschema.Array,
- Description: "A list of sections.",
- Items: &jsonschema.Definition{
- Type: jsonschema.String,
- },
- },
- },
- Required: []string{"sections"},
- },
- }},
- Messages: []openai.ChatCompletionMessage{
- {
- Role: openai.ChatMessageRoleSystem,
- Content: `You are an AI specialized in breaking code up into sections based on purpose and functionality.
-
- Your instructions:
-
- 1. Break up the provided text into sections based on purpose and functionality.
- 1a. If the text is code, try to group together related operations.
- 1b. If the text is natural language, try to group together related ideas.
-
- 2. Call the 'sectionized' function with the the 'sections' parameter. For each section, provide a string containing *just the first several distinguishing tokens that begin the section.*
-
- When breaking up the text into sections, follow these guidelines.
- - Sections should be roughly 50-100 lines in size.
- - A long file should be broken up into no more than 5-7 sections.
- - A short file should have 2-3 sections.
- - Sections should be understandable in isolation.
- - If in doubt, lean towards fewer sections rather than more sections.
- - Blocks of code that are commented out should be given their own sections.
- - Lean towards not breaking up functions or methods into multiple sections unless they are very long.
- - Lean towards not breaking up variable definitions, type definitions, or control flow blocks into multiple sections unless they are very long.
- - Lean towards not breaking up comment blocks into multiple sections unless they are very long.
- - Lean towards not breaking up paragraphs into multiple sections unless they are very long.
- - Lean towards keeping 'header' information like package declarations, imports, and initialization logic together in one section unless it would be very long.
- - If there's no way to break up the text according to these instructions, call 'sectionized' with an empty array.
-
- Important: you *must always* call the 'sectionized' function and never call any other function.
- `,
- },
- {
- Role: openai.ChatMessageRoleUser,
- Content: fmt.Sprintf("Break up the following text into sections as described in your instructions above and call the 'sectionized' function with the result: \n\n%s",
- text),
- },
- },
- })
-
- if err != nil {
- return nil, err
- }
-
- spew.Dump(resp)
-
- var byteRes []byte
- for _, choice := range resp.Choices {
- if choice.FinishReason == "function_call" && choice.Message.Role == "assistant" && choice.Message.FunctionCall != nil && choice.Message.FunctionCall.Name == "sectionized" {
- fnCall := choice.Message.FunctionCall
- byteRes = []byte(fnCall.Arguments)
- }
- }
-
- if len(byteRes) == 0 {
- return nil, fmt.Errorf("no 'sectionized' function call found in response")
- }
-
- // Clean the body of the response
- cleanBody := lib.CleanSectionJson(byteRes)
-
- // validate the JSON response
- var res sectionizeResult
- err = json.Unmarshal(cleanBody, &res)
-
- if err != nil {
- fmt.Printf("Failed JSON: %s\n", cleanBody) // Printing the JSON causing the failure
- return nil, fmt.Errorf("error unmarshalling JSON: %w", err)
- }
-
- // spew.Dump(sectionizedResp)
-
- sectionizedResp := shared.SectionizeResponse{
- SectionEnds: lib.GetSectionEnds(text, res.Sections),
- }
-
- byteRes, err = json.Marshal(sectionizedResp)
- if err != nil {
- return nil, err
- }
-
- return byteRes, nil
-}
diff --git a/server/model/summarize.go b/server/model/summarize.go
index d89d4927..2c08e11c 100644
--- a/server/model/summarize.go
+++ b/server/model/summarize.go
@@ -22,20 +22,16 @@ func Summarize(text string) ([]byte, int, error) {
Parameters: &jsonschema.Definition{
Type: jsonschema.Object,
Properties: map[string]jsonschema.Definition{
- "name": {
- Type: jsonschema.String,
- Description: "A short name for the text based on the content.",
- },
"summary": {
Type: jsonschema.String,
Description: "A brief summary of the text. A few sentences at most",
},
"fileName": {
Type: jsonschema.String,
- Description: "A *short* file name for the text based on the content. Use dashes as word separators. No spaces or special characters. 3-5 words max.",
+ Description: "A *short* file name for the text based on the content. Use dashes as word separators. No spaces or special characters. A few words max.",
},
},
- Required: []string{"name", "summary", "fileName"},
+ Required: []string{"summary", "fileName"},
},
}},
Messages: []openai.ChatCompletionMessage{
diff --git a/shared/sections.go b/shared/sections.go
deleted file mode 100644
index 6ee72fe2..00000000
--- a/shared/sections.go
+++ /dev/null
@@ -1,54 +0,0 @@
-package shared
-
-import (
- "regexp"
- "strconv"
- "strings"
-)
-
-func GetFullSections(text string, sectionEnds []int) []string {
- var sections []string
- startIndex := 0
-
- for _, endIndex := range sectionEnds {
- // If endIndex goes beyond text length, clip it to text length
- if endIndex > len(text) {
- endIndex = len(text)
- }
-
- // Extract section and append to sections
- section := text[startIndex:endIndex]
- sections = append(sections, section)
-
- // Update startIndex for the next iteration
- startIndex = endIndex
- }
-
- // Adding the last section if there's any remaining text
- if startIndex < len(text) {
- sections = append(sections, text[startIndex:])
- }
-
- return sections
-}
-
-var sectionRegex = regexp.MustCompile(`-\d+$`)
-
-func SplitSectionPath(path string) (string, int, error) {
- var sectionNum int = -1
- var err error
- sectionNumStr := strings.ReplaceAll(sectionRegex.FindString(path), "-", "")
-
- if sectionNumStr == "" {
- return path, -1, nil
- }
-
- if sectionNumStr != "" {
- sectionNum, err = strconv.Atoi(sectionNumStr)
- if err != nil {
- return "", -1, err
- }
- }
-
- return path[:len(path)-(len(sectionNumStr)+1)], sectionNum, nil
-}
diff --git a/shared/types.go b/shared/types.go
index f639155a..1dc3e1b7 100644
--- a/shared/types.go
+++ b/shared/types.go
@@ -29,29 +29,18 @@ type SummarizeRequest struct {
}
type SummarizeResponse struct {
- Name string `json:"name"`
Summary string `json:"summary"`
FileName string `json:"fileName"`
}
-type SectionizeRequest struct {
- Text string `json:"text"`
-}
-
-type SectionizeResponse struct {
- SectionEnds []int `json:"sectionEnds"`
-}
-
type ModelContextPart struct {
- Name string `json:"name"`
- Summary string `json:"summary"`
- Body string `json:"body"`
- Url string `json:"url"`
- FilePath string `json:"filePath"`
- Sha string `json:"sha"`
- NumTokens int `json:"numTokens"`
- UpdatedAt string `json:"updatedAt"`
- SectionEnds []int `json:"sectionEnds"`
+ Name string `json:"name"`
+ Body string `json:"body"`
+ Url string `json:"url"`
+ FilePath string `json:"filePath"`
+ Sha string `json:"sha"`
+ NumTokens int `json:"numTokens"`
+ UpdatedAt string `json:"updatedAt"`
}
type ModelContext []ModelContextPart