diff --git a/core/autocomplete/templating/AutocompleteTemplate.ts b/core/autocomplete/templating/AutocompleteTemplate.ts index 1ada0d55c..f8c8215fa 100644 --- a/core/autocomplete/templating/AutocompleteTemplate.ts +++ b/core/autocomplete/templating/AutocompleteTemplate.ts @@ -1,10 +1,6 @@ // Fill in the middle prompts import { CompletionOptions } from "../../index.js"; -import { - getLastNUriRelativePathParts, - shortestRelativeUriPaths, -} from "../../util/uri.js"; import { AutocompleteCodeSnippet, AutocompleteSnippet, @@ -18,6 +14,7 @@ export interface AutocompleteTemplate { filepath: string, reponame: string, snippets: AutocompleteSnippet[], + workspaceDirs: string[], ) => [string, string]; template: | string @@ -28,6 +25,7 @@ export interface AutocompleteTemplate { reponame: string, language: string, snippets: AutocompleteSnippet[], + workspaceDirs: [], ) => string); completionOptions?: Partial; } @@ -67,32 +65,30 @@ const qwenCoderFimTemplate: AutocompleteTemplate = { }, }; -// const codestralFimTemplate: AutocompleteTemplate = { -// template: "[SUFFIX]{{{suffix}}}[PREFIX]{{{prefix}}}", -// completionOptions: { -// stop: ["[PREFIX]", "[SUFFIX]"], -// }, -// }; +const codestralFimTemplate: AutocompleteTemplate = { + template: "[SUFFIX]{{{suffix}}}[PREFIX]{{{prefix}}}", + completionOptions: { + stop: ["[PREFIX]", "[SUFFIX]"], + }, +}; const codestralMultifileFimTemplate: AutocompleteTemplate = { compilePrefixSuffix: ( - prefix: string, - suffix: string, - filepath: string, - reponame: string, - snippets: AutocompleteSnippet[], + prefix, + suffix, + filepath, + reponame, + snippets, + workspaceDirs, ): [string, string] => { if (snippets.length === 0) { if (suffix.trim().length === 0 && prefix.trim().length === 0) { - return [ - `+++++ ${getLastNUriRelativePathParts(workspaceDirs, filepath, 2)}\n${prefix}`, - suffix, - ]; + return [`+++++ ${getLastNPathParts(filepath, 2)}\n${prefix}`, suffix]; } return [prefix, suffix]; } - const relativePaths = shortestRelativeUriPaths([ + const relativePaths = shortestRelativePaths([ ...snippets.map((snippet) => "filepath" in snippet ? snippet.filepath : "Untitled.txt", ), @@ -139,38 +135,39 @@ const codegemmaFimTemplate: AutocompleteTemplate = { }, }; -// // https://arxiv.org/pdf/2402.19173.pdf section 5.1 -// const starcoder2FimTemplate: AutocompleteTemplate = { -// template: ( -// prefix: string, -// suffix: string, -// filename: string, -// reponame: string, -// language: string, -// snippets: AutocompleteSnippet[], -// ): string => { -// const otherFiles = -// snippets.length === 0 -// ? "" -// : `${snippets -// .map((snippet) => { -// return snippet.content; -// }) -// .join("")}`; +// https://arxiv.org/pdf/2402.19173.pdf section 5.1 +const starcoder2FimTemplate: AutocompleteTemplate = { + template: ( + prefix, + suffix, + filename, + reponame, + language, + snippets, + workspaceDirs, + ): string => { + const otherFiles = + snippets.length === 0 + ? "" + : `${snippets + .map((snippet) => { + return snippet.content; + }) + .join("")}`; -// const prompt = `${otherFiles}${prefix}${suffix}`; -// return prompt; -// }, -// completionOptions: { -// stop: [ -// "", -// "", -// "", -// "", -// "<|endoftext|>", -// ], -// }, -// }; + const prompt = `${otherFiles}${prefix}${suffix}`; + return prompt; + }, + completionOptions: { + stop: [ + "", + "", + "", + "", + "<|endoftext|>", + ], + }, +}; const codeLlamaFimTemplate: AutocompleteTemplate = { template: "
 {{{prefix}}} {{{suffix}}} ",
@@ -195,21 +192,22 @@ const deepseekFimTemplate: AutocompleteTemplate = {
 // https://github.com/THUDM/CodeGeeX4/blob/main/guides/Infilling_guideline.md
 const codegeexFimTemplate: AutocompleteTemplate = {
   template: (
-    prefix: string,
-    suffix: string,
-    directoryUri: string,
-    reponame: string,
-    language: string,
-    allSnippets: AutocompleteSnippet[],
+    prefix,
+    suffix,
+    filepath,
+    reponame,
+    language,
+    allSnippets,
+    workspaceDirs,
   ): string => {
     const snippets = allSnippets.filter(
       (snippet) => snippet.type === AutocompleteSnippetType.Code,
     ) as AutocompleteCodeSnippet[];
 
-    const relativePaths = shortestRelativeUriPaths(
-      [...snippets.map((snippet) => snippet.filepath)],
-      directoryUri,
-    );
+    const relativePaths = shortestRelativePaths([
+      ...snippets.map((snippet) => snippet.filepath),
+      filepath,
+    ]);
     const baseTemplate = `###PATH:${
       relativePaths[relativePaths.length - 1]
     }\n###LANGUAGE:${language}\n###MODE:BLOCK\n<|code_suffix|>${suffix}<|code_prefix|>${prefix}<|code_middle|>`;
diff --git a/core/context/retrieval/repoMapRequest.ts b/core/context/retrieval/repoMapRequest.ts
index 5aaabead7..a6a77127a 100644
--- a/core/context/retrieval/repoMapRequest.ts
+++ b/core/context/retrieval/repoMapRequest.ts
@@ -2,6 +2,7 @@ import { Chunk, ContinueConfig, IDE, ILLM } from "../..";
 import { getModelByRole } from "../../config/util";
 import generateRepoMap from "../../util/generateRepoMap";
 import { renderChatMessage } from "../../util/messageContent";
+import { getUriPathBasename } from "../../util/uri";
 
 const SUPPORTED_MODEL_TITLE_FAMILIES = [
   "claude-3",
@@ -35,7 +36,7 @@ export async function requestFilesFromRepoMap(
   config: ContinueConfig,
   ide: IDE,
   input: string,
-  filterDirectory?: string,
+  filterDirUri?: string,
 ): Promise {
   const llm = getModelByRole(config, "repoMapFileSelection") ?? defaultLlm;
 
@@ -47,7 +48,7 @@ export async function requestFilesFromRepoMap(
   try {
     const repoMap = await generateRepoMap(llm, ide, {
       includeSignatures: false,
-      dirs: filterDirectory ? [filterDirectory] : undefined,
+      dirs: filterDirUri ? [filterDirUri] : undefined,
     });
 
     const prompt = `${repoMap}
@@ -71,7 +72,9 @@ This is the question that you should select relevant files for: "${input}"`;
       return [];
     }
 
-    const subDirPrefix = filterDirectory ? filterDirectory + pathSep : "";
+    const subDirPrefix = filterDirUri
+      ? getUriPathBasename(filterDirUri) + "/"
+      : "";
     const files =
       content
         .split("")[1]
diff --git a/core/indexing/walkDir.test.ts b/core/indexing/walkDir.test.ts
index af22265ff..390a81b8a 100644
--- a/core/indexing/walkDir.test.ts
+++ b/core/indexing/walkDir.test.ts
@@ -15,7 +15,7 @@ async function walkTestDir(
   options?: WalkerOptions,
 ): Promise {
   return walkDir(TEST_DIR, ide, {
-    returnRelativePaths: true,
+    returnRelativeUris: true,
     ...options,
   });
 }
@@ -259,7 +259,7 @@ describe("walkDir", () => {
       [path.join(TEST_DIR, "a.txt"), path.join(TEST_DIR, "b", "c.txt")],
       [],
       {
-        returnRelativePaths: false,
+        returnRelativeUris: false,
       },
     );
   });
diff --git a/core/indexing/walkDir.ts b/core/indexing/walkDir.ts
index 47f5a2cac..75fe734e9 100644
--- a/core/indexing/walkDir.ts
+++ b/core/indexing/walkDir.ts
@@ -1,5 +1,3 @@
-import path from "node:path";
-
 import ignore, { Ignore } from "ignore";
 
 import { FileType, IDE } from "../index.d.js";
@@ -12,11 +10,12 @@ import {
   getGlobalContinueIgArray,
   gitIgArrayFromFile,
 } from "./ignore.js";
+import { joinPathsToUri } from "../util/uri.js";
 
 export interface WalkerOptions {
   ignoreFiles?: string[];
   onlyDirs?: boolean;
-  returnRelativePaths?: boolean;
+  returnRelativeUris?: boolean;
   additionalIgnoreRules?: string[];
 }
 
@@ -25,7 +24,7 @@ type Entry = [string, FileType];
 // helper struct used for the DFS walk
 type WalkableEntry = {
   relPath: string;
-  absPath: string;
+  uri: string;
   type: FileType;
   entry: Entry;
 };
@@ -45,7 +44,7 @@ class DFSWalker {
   private readonly ignoreFileNames: Set;
 
   constructor(
-    private readonly path: string,
+    private readonly uri: string,
     private readonly ide: IDE,
     private readonly options: WalkerOptions,
   ) {
@@ -54,10 +53,6 @@ class DFSWalker {
 
   // walk is a depth-first search implementation
   public async *walk(): AsyncGenerator {
-    const fixupFunc = await this.newPathFixupFunc(
-      this.options.returnRelativePaths ? "" : this.path,
-      this.ide,
-    );
     const root = this.newRootWalkContext();
     const stack = [root];
     for (let cur = stack.pop(); cur; cur = stack.pop()) {
@@ -77,10 +72,11 @@ class DFSWalker {
           });
           if (this.options.onlyDirs) {
             // when onlyDirs is enabled the walker will only return directory names
-            yield fixupFunc(w.relPath);
+            yield w.relPath + "/";
           }
         } else {
-          yield fixupFunc(w.relPath);
+          // Note that shouldInclude handles skipping files if options.onlyDirs is true
+          yield w.relPath;
         }
       }
     }
@@ -91,7 +87,7 @@ class DFSWalker {
     return {
       walkableEntry: {
         relPath: "",
-        absPath: this.path,
+        uri: this.uri,
         type: 2 as FileType.Directory,
         entry: ["", 2 as FileType.Directory],
       },
@@ -110,15 +106,13 @@ class DFSWalker {
   private async listDirForWalking(
     walkableEntry: WalkableEntry,
   ): Promise {
-    const entries = await this.ide.listDir(walkableEntry.absPath);
-    return entries.map((e) => {
-      return {
-        relPath: path.join(walkableEntry.relPath, e[0]),
-        absPath: path.join(walkableEntry.absPath, e[0]),
-        type: e[1],
-        entry: e,
-      };
-    });
+    const entries = await this.ide.listDir(walkableEntry.uri);
+    return entries.map((e) => ({
+      relPath: `${walkableEntry.relPath}/${e[0]}`,
+      uri: joinPathsToUri(walkableEntry.uri, e[0]),
+      type: e[1],
+      entry: e,
+    }));
   }
 
   private async getIgnoreToApplyInDir(
@@ -138,25 +132,22 @@ class DFSWalker {
   }
 
   private async loadIgnoreFiles(entries: WalkableEntry[]): Promise {
-    const ignoreEntries = entries.filter((w) => this.isIgnoreFile(w.entry));
+    const ignoreEntries = entries.filter((w) =>
+      this.entryIsIgnoreFile(w.entry),
+    );
     const promises = ignoreEntries.map(async (w) => {
-      return await this.ide.readFile(w.absPath);
+      return await this.ide.readFile(w.uri);
     });
     return Promise.all(promises);
   }
 
-  private isIgnoreFile(e: Entry): boolean {
-    const p = e[0];
-    return this.ignoreFileNames.has(p);
-  }
-
   private shouldInclude(
     walkableEntry: WalkableEntry,
     ignoreContexts: IgnoreContext[],
   ) {
     if (this.entryIsSymlink(walkableEntry.entry)) {
       // If called from the root, a symlink either links to a real file in this repository,
-      // and therefore will be walked OR it linksto something outside of the repository and
+      // and therefore will be walked OR it links to something outside of the repository and
       // we do not want to index it
       return false;
     }
@@ -189,50 +180,38 @@ class DFSWalker {
     return entry[1] === (64 as FileType.SymbolicLink);
   }
 
-  // returns a function which will optionally prefix a root path and fixup the paths for the appropriate OS filesystem (i.e. windows)
-  // the reason to construct this function once is to avoid the need to call ide.pathSep() multiple times
-  private async newPathFixupFunc(
-    rootPath: string,
-    ide: IDE,
-  ): Promise<(relPath: string) => string> {
-    const pathSep = await ide.pathSep();
-    const prefix = rootPath === "" ? "" : rootPath + pathSep;
-    if (pathSep === "/") {
-      if (rootPath === "") {
-        // return a no-op function in this case to avoid unnecessary string concatentation
-        return (relPath: string) => relPath;
-      }
-      return (relPath: string) => prefix + relPath;
+  private entryIsIgnoreFile(e: Entry): boolean {
+    if (e[1] === FileType.Directory || e[1] === FileType.SymbolicLink) {
+      return false;
     }
-    // this serves to 'fix-up' the path on Windows
-    return (relPath: string) => {
-      return prefix + relPath.split("/").join(pathSep);
-    };
+    return this.ignoreFileNames.has(e[0]);
   }
 }
 
 const defaultOptions: WalkerOptions = {
   ignoreFiles: [".gitignore", ".continueignore"],
   additionalIgnoreRules: [...DEFAULT_IGNORE_DIRS, ...DEFAULT_IGNORE_FILETYPES],
+  onlyDirs: false,
+  returnRelativeUris: false,
 };
 
 export async function walkDir(
-  path: string,
+  uri: string,
   ide: IDE,
-  _options?: WalkerOptions,
+  _optionOverrides?: WalkerOptions,
 ): Promise {
-  let paths: string[] = [];
-  for await (const p of walkDirAsync(path, ide, _options)) {
-    paths.push(p);
+  let urisOrRelativePaths: string[] = [];
+  for await (const p of walkDirAsync(uri, ide, _optionOverrides)) {
+    urisOrRelativePaths.push(p);
   }
-  return paths;
+  return urisOrRelativePaths;
 }
 
 export async function* walkDirAsync(
   path: string,
   ide: IDE,
-  _options?: WalkerOptions,
+  _optionOverrides?: WalkerOptions,
 ): AsyncGenerator {
-  const options = { ...defaultOptions, ..._options };
+  const options = { ...defaultOptions, ..._optionOverrides };
   yield* new DFSWalker(path, ide, options).walk();
 }
diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts
index ebe11b890..ec5bde252 100644
--- a/extensions/vscode/src/extension/VsCodeMessenger.ts
+++ b/extensions/vscode/src/extension/VsCodeMessenger.ts
@@ -1,5 +1,3 @@
-import * as fs from "node:fs";
-
 import { ConfigHandler } from "core/config/ConfigHandler";
 import { getModelByRole } from "core/config/util";
 import { applyCodeBlock } from "core/edit/lazy/applyCodeBlock";