Skip to content

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

context ls improvements, directory handling

Dane Schneidere8049c2d8bca
diff --git a/cli/cmd/load.go b/cli/cmd/load.go
index d9c971e9..daa1489c 100644
--- a/cli/cmd/load.go
+++ b/cli/cmd/load.go
@@ -29,7 +29,7 @@ func init() {
contextLoadCmd.Flags().StringVarP(&note, "note", "n", "", "Add a note to the context")
contextLoadCmd.Flags().BoolVarP(&recursive, "recursive", "r", false, "Search directories recursively")
contextLoadCmd.Flags().IntVarP(&maxDepth, "depth", "d", -1, "Maximum depth for recursive directory search (-1 means no limit)")
- contextLoadCmd.Flags().BoolVar(&namesOnly, "names", false, "Only process file names")
+ contextLoadCmd.Flags().BoolVar(&namesOnly, "tree", false, "Load directory tree with file names only")
contextLoadCmd.Flags().BoolVar(&truncate, "truncate", false, "Truncate contents if tokens exceed maximum")
contextLoadCmd.Flags().IntVar(&maxTokens, "max", -1, "Maximum limit for number of tokens")
diff --git a/cli/cmd/ls.go b/cli/cmd/ls.go
index d7e5f855..52cce62f 100644
--- a/cli/cmd/ls.go
+++ b/cli/cmd/ls.go
@@ -31,7 +31,7 @@ func context(cmd *cobra.Command, args []string) {
totalTokens := 0
table := tablewriter.NewWriter(os.Stdout)
- table.SetHeader([]string{"#" /*"Type",*/, "Name", "πŸͺ™", "Added", "Updated"})
+ table.SetHeader([]string{"#", "Name", "Type", "πŸͺ™", "Added", "Updated"})
table.SetAutoWrapText(false)
if len(context) == 0 {
@@ -45,16 +45,27 @@ func context(cmd *cobra.Command, args []string) {
totalTokens += part.NumTokens
// var contextType string
- var id string
- if part.FilePath != "" {
- // contextType = "file"
- id = " πŸ“„ " + part.FilePath
- } else if part.Url != "" {
- // contextType = "url"
- id = " 🌎 " + part.Url
- } else {
- // contextType = "text"
- id = " ✏️ " + part.Name
+ var icon string
+ var t string
+ id := part.Name
+ switch part.Type {
+ case shared.ContextFileType:
+ icon = "πŸ“„"
+ t = "file"
+ id = part.FilePath
+ case shared.ContextURLType:
+ icon = "🌎"
+ t = "url"
+ case shared.ContextDirectoryTreeType:
+ icon = "πŸ—‚ "
+ t = "tree"
+ id = part.FilePath
+ case shared.ContextNoteType:
+ icon = "✏️ "
+ t = "note"
+ case shared.ContextPipedDataType:
+ icon = "↔️ "
+ t = "piped"
}
addedAt, err := time.Parse(shared.TsFormat, part.AddedAt)
@@ -71,19 +82,19 @@ func context(cmd *cobra.Command, args []string) {
row := []string{
strconv.Itoa(i),
- // contextType,
- id,
+ " " + icon + " " + id,
+ t,
strconv.Itoa(part.NumTokens), //+ " πŸͺ™",
format.Time(addedAt),
format.Time(updatedAt),
}
table.Rich(row, []tablewriter.Colors{
{tablewriter.FgHiWhiteColor, tablewriter.Bold},
- // {tablewriter.FgHiWhiteColor},
{tablewriter.FgHiGreenColor, tablewriter.Bold},
{tablewriter.FgHiWhiteColor},
{tablewriter.FgHiWhiteColor},
{tablewriter.FgHiWhiteColor},
+ {tablewriter.FgHiWhiteColor},
})
}
diff --git a/cli/lib/context_load.go b/cli/lib/context_load.go
index 60a15dc1..9c082552 100644
--- a/cli/lib/context_load.go
+++ b/cli/lib/context_load.go
@@ -35,6 +35,8 @@ func LoadContextOrDie(params *types.LoadContextParams) (int, int) {
planState, err := GetPlanState()
if err != nil {
+ s.Stop()
+ ClearCurrentLine()
log.Fatalf("Failed to get plan state: %v", err)
}
@@ -68,6 +70,7 @@ func LoadContextOrDie(params *types.LoadContextParams) (int, int) {
s.Stop()
ClearCurrentLine()
fmt.Fprintf(os.Stderr, "The total number of tokens (%d) exceeds the maximum allowed (%d). Truncating input text.\n", totalTokens, maxTokens)
+ s.Start()
numTokens = maxTokens - (totalTokens - numTokens)
// If the number of tokens is less than or equal to 0, then we can stop processing files
@@ -79,6 +82,8 @@ func LoadContextOrDie(params *types.LoadContextParams) (int, int) {
totalTokens = maxTokens
} else {
+ s.Stop()
+ ClearCurrentLine()
log.Fatalf("The total number of tokens (%d) exceeds the maximum allowed (%d)", totalTokens, maxTokens)
}
@@ -90,13 +95,16 @@ func LoadContextOrDie(params *types.LoadContextParams) (int, int) {
fileNameResp, err := Api.FileName(body)
if err != nil {
- log.Fatalf("Failed to summarize the text: %v", err)
+ s.Stop()
+ ClearCurrentLine()
+ log.Fatalf("Failed to get a file name for the text: %v", err)
}
fileName := format.GetFileNameWithoutExt(fileNameResp.FileName)
ts := shared.StringTs()
contextPart := shared.ModelContextPart{
+ Type: shared.ContextNoteType,
Name: fileName,
Body: body,
Sha: sha,
@@ -116,12 +124,16 @@ func LoadContextOrDie(params *types.LoadContextParams) (int, int) {
hasPipeData := false
fileInfo, err := os.Stdin.Stat()
if err != nil {
+ s.Stop()
+ ClearCurrentLine()
log.Fatalf("Failed to stat stdin: %v", err)
}
if fileInfo.Mode()&os.ModeNamedPipe != 0 {
reader := bufio.NewReader(os.Stdin)
pipedData, err := io.ReadAll(reader)
if err != nil {
+ s.Stop()
+ ClearCurrentLine()
log.Fatalf("Failed to read piped data: %v", err)
}
@@ -147,6 +159,7 @@ func LoadContextOrDie(params *types.LoadContextParams) (int, int) {
s.Stop()
ClearCurrentLine()
fmt.Fprintf(os.Stderr, "The total number of tokens (%d) exceeds the maximum allowed (%d). Truncating piped data.\n", totalTokens, maxTokens)
+ s.Start()
numTokens = maxTokens - (totalTokens - numTokens)
if numTokens <= 0 {
@@ -157,6 +170,8 @@ func LoadContextOrDie(params *types.LoadContextParams) (int, int) {
totalTokens = maxTokens
} else {
+ s.Stop()
+ ClearCurrentLine()
log.Fatalf("The total number of tokens (%d) exceeds the maximum allowed (%d)", totalTokens, maxTokens)
}
}
@@ -167,13 +182,16 @@ func LoadContextOrDie(params *types.LoadContextParams) (int, int) {
fileNameResp, err := Api.FileName(body)
if err != nil {
- log.Fatalf("Failed to summarize piped data: %v", err)
+ s.Stop()
+ ClearCurrentLine()
+ log.Fatalf("Failed to get a file name for piped data: %v", err)
}
fileName := format.GetFileNameWithoutExt(fileNameResp.FileName)
ts := shared.StringTs()
contextPart := shared.ModelContextPart{
+ Type: shared.ContextPipedDataType,
Name: fileName,
Body: body,
Sha: sha,
@@ -205,133 +223,170 @@ func LoadContextOrDie(params *types.LoadContextParams) (int, int) {
}
if len(inputFilePaths) > 0 {
- wg.Add(1)
+ if params.NamesOnly {
+ for _, inputFilePath := range inputFilePaths {
+ wg.Add(1)
- go func() {
- defer wg.Done()
+ go func(inputFilePath string) {
+ defer wg.Done()
- flattenedPaths := FlattenPaths(inputFilePaths, params)
+ flattenedPaths, err := ParseInputPaths([]string{inputFilePath}, params)
+ if err != nil {
+ s.Stop()
+ ClearCurrentLine()
+ log.Fatalf("Failed to parse input paths: %v", err)
+ }
- if params.NamesOnly {
- body := strings.Join(flattenedPaths, "\n")
- bytes := []byte(body)
+ body := strings.Join(flattenedPaths, "\n")
+ bytes := []byte(body)
+
+ hash := sha256.Sum256(bytes)
+ sha := hex.EncodeToString(hash[:])
+ numTokens := shared.GetNumTokens(body)
+
+ totalTokensMutex.Lock()
+ func() {
+ defer totalTokensMutex.Unlock()
+ totalTokens += numTokens
+ tokensAdded += numTokens
+ if totalTokens > maxTokens {
+
+ if params.Truncate {
+ s.Stop()
+ ClearCurrentLine()
+ fmt.Fprintf(os.Stderr, "The total number of tokens (%d) exceeds the maximum allowed (%d). Truncating directory tree.\n", totalTokens, maxTokens)
+ s.Start()
+ numTokens = maxTokens - (totalTokens - numTokens)
+
+ // If the number of tokens is less than or equal to 0, then we can stop processing files
+ if numTokens <= 0 {
+ return
+ }
- hash := sha256.Sum256(bytes)
- sha := hex.EncodeToString(hash[:])
- numTokens := shared.GetNumTokens(body)
+ body = body[:numTokens]
+ totalTokens = maxTokens
- totalTokensMutex.Lock()
- func() {
- defer totalTokensMutex.Unlock()
- totalTokens += numTokens
- tokensAdded += numTokens
- if totalTokens > maxTokens {
+ } else {
+ s.Stop()
+ ClearCurrentLine()
+ log.Fatalf("The total number of tokens (%d) exceeds the maximum allowed (%d)", totalTokens, maxTokens)
+ }
- if params.Truncate {
- s.Stop()
- ClearCurrentLine()
- fmt.Fprintf(os.Stderr, "The total number of tokens (%d) exceeds the maximum allowed (%d). Truncating directory layout.\n", totalTokens, maxTokens)
- numTokens = maxTokens - (totalTokens - numTokens)
+ }
- // If the number of tokens is less than or equal to 0, then we can stop processing files
- if numTokens <= 0 {
- return
- }
+ }()
- body = body[:numTokens]
- totalTokens = maxTokens
+ ts := shared.StringTs()
- } else {
- log.Fatalf("The total number of tokens (%d) exceeds the maximum allowed (%d)", totalTokens, maxTokens)
- }
+ // get last portion of directory path
+ name := filepath.Base(inputFilePath)
+ if name == "." {
+ name = "cwd"
+ }
+ if name == ".." {
+ name = "parent"
+ }
+ contextPart := shared.ModelContextPart{
+ Type: shared.ContextDirectoryTreeType,
+ Name: name,
+ FilePath: inputFilePath,
+ Body: body,
+ Sha: sha,
+ NumTokens: numTokens,
+ AddedAt: ts,
+ UpdatedAt: ts,
}
- }()
+ contextPartsMutex.Lock()
+ contextParts = append(contextParts, contextPart)
+ contextPartsMutex.Unlock()
- ts := shared.StringTs()
- contextPart := shared.ModelContextPart{
- Name: "directory layout",
- Body: body,
- Sha: sha,
- NumTokens: numTokens,
- AddedAt: ts,
- UpdatedAt: ts,
- }
+ }(inputFilePath)
- contextPartsMutex.Lock()
- contextParts = append(contextParts, contextPart)
- contextPartsMutex.Unlock()
+ }
- } else {
- for _, path := range flattenedPaths {
- wg.Add(1)
+ } else {
+ flattenedPaths, err := ParseInputPaths(inputFilePaths, params)
+ if err != nil {
+ s.Stop()
+ ClearCurrentLine()
+ log.Fatalf("Failed to parse input paths: %v", err)
+ }
- go func(path string) {
- defer wg.Done()
+ for _, path := range flattenedPaths {
+ wg.Add(1)
- fileContent, err := os.ReadFile(path)
- if err != nil {
- log.Fatalf("Failed to read the file %s: %v", path, err)
- }
+ go func(path string) {
+ defer wg.Done()
- body := string(fileContent)
- hash := sha256.Sum256(fileContent)
- sha := hex.EncodeToString(hash[:])
- numTokens := shared.GetNumTokens(body)
-
- totalTokensMutex.Lock()
- func() {
- defer totalTokensMutex.Unlock()
- totalTokens += numTokens
- tokensAdded += numTokens
- if totalTokens > maxTokens {
-
- if params.Truncate {
- s.Stop()
- ClearCurrentLine()
- fmt.Fprintf(os.Stderr, "The total number of tokens (%d) exceeds the maximum allowed (%d). Truncating the file %s.\n", totalTokens, maxTokens, path)
- numTokens = maxTokens - (totalTokens - numTokens)
-
- // If the number of tokens is less than or equal to 0, then we can stop processing files
- if numTokens <= 0 {
- return
- }
-
- body = body[:numTokens]
- totalTokens = maxTokens
-
- } else {
- log.Fatalf("The total number of tokens (%d) exceeds the maximum allowed (%d)", totalTokens, maxTokens)
+ fileContent, err := os.ReadFile(path)
+ if err != nil {
+ s.Stop()
+ ClearCurrentLine()
+ log.Fatalf("Failed to read the file %s: %v", path, err)
+ }
+
+ body := string(fileContent)
+ hash := sha256.Sum256(fileContent)
+ sha := hex.EncodeToString(hash[:])
+ numTokens := shared.GetNumTokens(body)
+
+ totalTokensMutex.Lock()
+ func() {
+ defer totalTokensMutex.Unlock()
+ totalTokens += numTokens
+ tokensAdded += numTokens
+ if totalTokens > maxTokens {
+
+ if params.Truncate {
+ s.Stop()
+ ClearCurrentLine()
+ fmt.Fprintf(os.Stderr, "The total number of tokens (%d) exceeds the maximum allowed (%d). Truncating the file %s.\n", totalTokens, maxTokens, path)
+ numTokens = maxTokens - (totalTokens - numTokens)
+ s.Start()
+
+ // If the number of tokens is less than or equal to 0, then we can stop processing files
+ if numTokens <= 0 {
+ return
}
+ body = body[:numTokens]
+ totalTokens = maxTokens
+
+ } else {
+ s.Stop()
+ ClearCurrentLine()
+ log.Fatalf("The total number of tokens (%d) exceeds the maximum allowed (%d)", totalTokens, maxTokens)
}
- }()
+ }
- _, fileName := filepath.Split(path)
+ }()
- ts := shared.StringTs()
+ _, fileName := filepath.Split(path)
- contextPart := shared.ModelContextPart{
- Name: fileName,
- Body: body,
- FilePath: path,
- Sha: sha,
- NumTokens: numTokens,
- AddedAt: ts,
- UpdatedAt: ts,
- }
+ ts := shared.StringTs()
- contextPartsMutex.Lock()
- contextParts = append(contextParts, contextPart)
- contextPartsMutex.Unlock()
+ contextPart := shared.ModelContextPart{
+ Type: shared.ContextFileType,
+ Name: fileName,
+ Body: body,
+ FilePath: path,
+ Sha: sha,
+ NumTokens: numTokens,
+ AddedAt: ts,
+ UpdatedAt: ts,
+ }
- }(path)
+ contextPartsMutex.Lock()
+ contextParts = append(contextParts, contextPart)
+ contextPartsMutex.Unlock()
+
+ }(path)
- }
}
- }()
+ }
}
@@ -344,6 +399,8 @@ func LoadContextOrDie(params *types.LoadContextParams) (int, int) {
body, err := FetchURLContent(url)
if err != nil {
+ s.Stop()
+ ClearCurrentLine()
log.Fatalf("Failed to fetch content from URL %s: %v", url, err)
}
@@ -360,6 +417,7 @@ func LoadContextOrDie(params *types.LoadContextParams) (int, int) {
ClearCurrentLine()
fmt.Fprintf(os.Stderr, "The total number of tokens (%d) exceeds the maximum allowed (%d). Truncating content from URL %s.\n", totalTokens, maxTokens, url)
numTokens = maxTokens - (totalTokens - numTokens)
+ s.Start()
// If the number of tokens is less than or equal to 0, then we can stop processing content
if numTokens <= 0 {
@@ -370,6 +428,8 @@ func LoadContextOrDie(params *types.LoadContextParams) (int, int) {
totalTokens = maxTokens
} else {
+ s.Stop()
+ ClearCurrentLine()
log.Fatalf("The total number of tokens (%d) exceeds the maximum allowed (%d)", totalTokens, maxTokens)
}
}
@@ -380,6 +440,7 @@ func LoadContextOrDie(params *types.LoadContextParams) (int, int) {
ts := shared.StringTs()
contextPart := shared.ModelContextPart{
+ Type: shared.ContextURLType,
Name: SanitizeAndClipURL(url, 70),
Url: url,
Body: body,
@@ -399,7 +460,8 @@ func LoadContextOrDie(params *types.LoadContextParams) (int, int) {
wg.Wait()
if len(contextParts) == 0 {
- log.Fatalln("No context loaded")
+ fmt.Println("πŸ€·β€β™‚οΈ No context loaded")
+ os.Exit(1)
}
errCh := make(chan error, 2)
@@ -427,10 +489,19 @@ func LoadContextOrDie(params *types.LoadContextParams) (int, int) {
added = append(added, "piped data")
}
if len(inputFilePaths) > 0 {
- label := "file"
- if len(inputFilePaths) > 1 {
- label = "files"
+ var label string
+ if params.NamesOnly {
+ label = "directory tree"
+ if len(inputFilePaths) > 1 {
+ label = "directory trees"
+ }
+ } else {
+ label = "file"
+ if len(inputFilePaths) > 1 {
+ label = "files"
+ }
}
+
added = append(added, fmt.Sprintf("%d %s", len(inputFilePaths), label))
}
if len(inputUrls) > 0 {
@@ -456,6 +527,8 @@ func LoadContextOrDie(params *types.LoadContextParams) (int, int) {
msg += fmt.Sprintf(" into context | added β†’ %d πŸͺ™ | total β†’ %d πŸͺ™", tokensAdded, totalTokens)
if err != nil {
+ s.Stop()
+ ClearCurrentLine()
log.Fatalf("Failed to get total tokens: %v", err)
}
@@ -463,6 +536,8 @@ func LoadContextOrDie(params *types.LoadContextParams) (int, int) {
err = GitCommitContextUpdate(msg)
if err != nil {
+ s.Stop()
+ ClearCurrentLine()
log.Fatalf("Failed to commit context update to git: %v", err)
}
diff --git a/cli/lib/fs.go b/cli/lib/fs.go
index b0cfa729..e602b82b 100644
--- a/cli/lib/fs.go
+++ b/cli/lib/fs.go
@@ -4,10 +4,10 @@ import (
"encoding/json"
"fmt"
"io"
- "log"
"os"
"path/filepath"
"plandex/types"
+ "strings"
"sync"
)
@@ -130,9 +130,11 @@ func CwdIsPlan() bool {
return parentDir == PlandexDir
}
-func FlattenPaths(fileOrDirPaths []string, params *types.LoadContextParams) []string {
+func ParseInputPaths(fileOrDirPaths []string, params *types.LoadContextParams) ([]string, error) {
var wg sync.WaitGroup
- resPathsChan := make(chan string, len(fileOrDirPaths))
+ var mu sync.Mutex
+ var firstErr error
+ resPaths := []string{}
for _, path := range fileOrDirPaths {
wg.Add(1)
@@ -141,7 +143,13 @@ func FlattenPaths(fileOrDirPaths []string, params *types.LoadContextParams) []st
err := filepath.Walk(p, func(path string, info os.FileInfo, err error) error {
if err != nil {
- return err // Handling error more gracefully
+ return err
+ }
+
+ mu.Lock()
+ defer mu.Unlock()
+ if firstErr != nil {
+ return firstErr // If an error was encountered, stop walking
}
if info.IsDir() {
@@ -149,40 +157,45 @@ func FlattenPaths(fileOrDirPaths []string, params *types.LoadContextParams) []st
return filepath.SkipDir
}
- // calculate directory depth from p
- depth := 0
- for _, c := range info.Name() {
- if c == filepath.Separator {
- depth += 1
- }
+ if !(params.Recursive || params.NamesOnly) {
+ return fmt.Errorf("cannot process directory %s: --recursive or --tree flag not set", path)
}
+ // calculate directory depth from base
+ depth := strings.Count(path[len(p):], string(filepath.Separator))
if params.MaxDepth != -1 && depth > params.MaxDepth {
return filepath.SkipDir
}
+
+ if params.NamesOnly {
+ // add directory name to results
+ resPaths = append(resPaths, path)
+ }
+ } else {
+ // add file path to results
+ resPaths = append(resPaths, path)
}
- resPathsChan <- path
return nil
})
if err != nil {
- log.Printf("Failed to process directory %s: %v", p, err) // Logging error instead of fatal
+ mu.Lock()
+ if firstErr == nil {
+ firstErr = err
+ }
+ mu.Unlock()
}
}(path)
}
- go func() {
- wg.Wait()
- close(resPathsChan)
- }()
+ wg.Wait()
- var resPaths []string
- for p := range resPathsChan {
- resPaths = append(resPaths, p)
+ if firstErr != nil {
+ return nil, firstErr
}
- return resPaths
+ return resPaths, nil
}
func CopyFile(src, dst string) error {
diff --git a/cli/lib/url.go b/cli/lib/url.go
index e684d85d..c294f38d 100644
--- a/cli/lib/url.go
+++ b/cli/lib/url.go
@@ -6,6 +6,7 @@ import (
"log"
"net/http"
"net/url"
+ "regexp"
"strings"
"time"
@@ -68,6 +69,10 @@ func ExtractTextualContent(htmlContent string) string {
}
func SanitizeAndClipURL(url string, maxLength int) string {
+ // remove protocol portion with a regex
+ re := regexp.MustCompile(`^.*?://`)
+ url = re.ReplaceAllString(url, "")
+
// Replace common invalid filename characters. You can extend this list as needed.
sanitized := strings.ReplaceAll(url, ":", "_")
sanitized = strings.ReplaceAll(sanitized, "/", "_")
diff --git a/cli/types/types.go b/cli/types/types.go
index 751a22db..72559ea8 100644
--- a/cli/types/types.go
+++ b/cli/types/types.go
@@ -5,16 +5,6 @@ import (
"github.com/plandex/plandex/shared"
)
-type LoadContextParams struct {
- Note string
- MaxTokens int
- Recursive bool
- MaxDepth int
- NamesOnly bool
- Truncate bool
- Resources []string
-}
-
type OnStreamPlanParams struct {
Content string
State *fsm.FSM
@@ -57,3 +47,13 @@ type PlanState struct {
type PlanSettings struct {
Name string
}
+
+type LoadContextParams struct {
+ Note string
+ MaxTokens int
+ Recursive bool
+ MaxDepth int
+ NamesOnly bool
+ Truncate bool
+ Resources []string
+}
diff --git a/server/model/lib/context.go b/server/model/lib/context.go
index bddf634c..5a73bb3b 100644
--- a/server/model/lib/context.go
+++ b/server/model/lib/context.go
@@ -15,7 +15,10 @@ func FormatModelContext(context shared.ModelContext) (string, int) {
var fmtStr string
var args []any
- if part.FilePath != "" {
+ if part.Type == shared.ContextDirectoryTreeType {
+ fmtStr = "\n\n- %s | directory tree:\n\n```\n%s\n```"
+ args = append(args, part.FilePath, part.Body)
+ } else if part.Type == shared.ContextFileType {
fmtStr = "\n\n- %s:\n\n```\n%s\n```"
args = append(args, part.FilePath, part.Body)
} else if part.Url != "" {
diff --git a/shared/types.go b/shared/types.go
index 1330a214..b0ff6304 100644
--- a/shared/types.go
+++ b/shared/types.go
@@ -47,7 +47,6 @@ const (
ContextFileType ModelContextPartType = "file"
ContextURLType ModelContextPartType = "url"
ContextNoteType ModelContextPartType = "note"
- ContextDirectoryType ModelContextPartType = "directory"
ContextDirectoryTreeType ModelContextPartType = "directory tree"
ContextPipedDataType ModelContextPartType = "piped data"
)