From 6e8f4d86cd3ae1a84bada2a72be2f6e6688dfa00 Mon Sep 17 00:00:00 2001 From: Riddhimaan-Senapati <114703025+Riddhimaan-Senapati@users.noreply.github.com> Date: Sat, 8 Feb 2025 16:28:52 -0500 Subject: [PATCH 01/33] added new gemini models to config_schema.json --- extensions/vscode/config_schema.json | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index d9dab076b..642335557 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -937,7 +937,10 @@ "gemini-1.5-flash", "gemini-1.5-flash-8b", "gemini-2.0-flash-exp", - "gemini-2.0-flash" + "gemini-2.0-flash", + "gemini-2.0-flash-thinking-exp-01-21", + "gemini-2.0-pro-exp-02-05", + "gemini-2.0-flash-lite-preview-02-05" ] } } From 3c36b4dc378ddd8c5c5c2cc234e9a605d776d928 Mon Sep 17 00:00:00 2001 From: Ingo Eichhorst Date: Sun, 16 Feb 2025 22:31:10 +0100 Subject: [PATCH 02/33] feat: add unified diff instant apply --- core/edit/lazy/applyCodeBlock.ts | 12 + core/edit/lazy/unifiedDiffApply.test.ts | 412 ++++++++++++++++++++++++ core/edit/lazy/unifiedDiffApply.ts | 152 +++++++++ docs/docs/edit/how-to-use-it.md | 7 + 4 files changed, 583 insertions(+) create mode 100644 core/edit/lazy/unifiedDiffApply.test.ts create mode 100644 core/edit/lazy/unifiedDiffApply.ts diff --git a/core/edit/lazy/applyCodeBlock.ts b/core/edit/lazy/applyCodeBlock.ts index 924d1c282..8a311a4fe 100644 --- a/core/edit/lazy/applyCodeBlock.ts +++ b/core/edit/lazy/applyCodeBlock.ts @@ -5,6 +5,7 @@ import { getUriFileExtension } from "../../util/uri"; import { deterministicApplyLazyEdit } from "./deterministic"; import { streamLazyApply } from "./streamLazyApply"; +import { isUnifiedDiffFormat, applyUnifiedDiff } from "./unifiedDiffApply"; function canUseInstantApply(filename: string) { const fileExtension = getUriFileExtension(filename); @@ -32,5 +33,16 @@ export async function applyCodeBlock( } } + // If the code block is a diff + if (isUnifiedDiffFormat(newFile)) { + try { + const diffLines = applyUnifiedDiff(oldFile, newFile); + const diffGenerator = generateLines(diffLines!); + return [true, diffGenerator]; + } catch (e) { + console.error("Failed to apply unified diff", e); + } + } + return [false, streamLazyApply(oldFile, filename, newFile, llm, fastLlm)]; } diff --git a/core/edit/lazy/unifiedDiffApply.test.ts b/core/edit/lazy/unifiedDiffApply.test.ts new file mode 100644 index 000000000..c7a5a8370 --- /dev/null +++ b/core/edit/lazy/unifiedDiffApply.test.ts @@ -0,0 +1,412 @@ +import { applyUnifiedDiff, isUnifiedDiffFormat } from "./unifiedDiffApply"; + +describe("isUnifiedDiffFormat", () => { + it("should return true for valid unified diff format", () => { + const validDiff = `--- original.txt ++++ modified.txt +@@ -1,3 +1,4 @@ + line1 +-line2 ++newline2 ++newline3 + line3`; + expect(isUnifiedDiffFormat(validDiff)).toBe(true); + }); + + it("should return false for empty diff", () => { + expect(isUnifiedDiffFormat("")).toBe(false); + }); + + it("should return false for diff without hunk header", () => { + const invalidDiff = `--- original.txt ++++ modified.txt ++line1 +-line2 ++line3`; + expect(isUnifiedDiffFormat(invalidDiff)).toBe(false); + }); + + it("should return false for diff without valid content", () => { + const invalidDiff = `--- original.txt ++++ modified.txt +@@ -1,3 +1,4 @@`; + expect(isUnifiedDiffFormat(invalidDiff)).toBe(false); + }); + + it("should return true even without file headers if hunk headers exist", () => { + const diffWithoutFileHeaders = `@@ -1,3 +1,4 @@ + line1 +-line2 ++newline2 ++newline3 + line3`; + expect(isUnifiedDiffFormat(diffWithoutFileHeaders)).toBe(true); + }); + + it("should return true in case of empty lines", () => { + const diffWithoutFileHeaders = `@@ -1,3 +1,4 @@ + line1 +-line2 ++newline2 + line3`; + expect(isUnifiedDiffFormat(diffWithoutFileHeaders)).toBe(true); + }); +}); + +describe("applyUnifiedDiff", () => { + it("should correctly apply a add line of unified diff", () => { + const sourceCode = `func main() { + scanner := bufio.NewScanner(os.Stdin) + fmt.Println("Calculator started! Available operations:") + fmt.Println(" + : Addition") + fmt.Println(" - : Subtraction") + fmt.Println(" * : Multiplication") + fmt.Println(" / : Division") + fmt.Println(" ^ : Power") + fmt.Println(" √ : Square root (use only one number)") +} +// End of file`; + + const diffText = `--- original.go ++++ updated.go +@@ -30,6 +30,7 @@ + fmt.Println(" / : Division") + fmt.Println(" ^ : Power") + fmt.Println(" √ : Square root (use only one number)") ++ fmt.Println(" log: Logarithm (use 'log base number')") + }`; + + const result = applyUnifiedDiff(sourceCode, diffText); + + const expected = [ + { type: "same", line: "func main() {" }, + { type: "same", line: " scanner := bufio.NewScanner(os.Stdin)" }, + { type: "same", line: " fmt.Println(\"Calculator started! Available operations:\")" }, + { type: "same", line: " fmt.Println(\" + : Addition\")" }, + { type: "same", line: " fmt.Println(\" - : Subtraction\")" }, + { type: "same", line: " fmt.Println(\" * : Multiplication\")" }, + { type: "same", line: " fmt.Println(\" / : Division\")" }, + { type: "same", line: " fmt.Println(\" ^ : Power\")" }, + { type: "same", line: " fmt.Println(\" √ : Square root (use only one number)\")" }, + { type: "new", line: " fmt.Println(\" log: Logarithm (use 'log base number')\")" }, + { type: "same", line: "}" }, + { type: "same", line: "// End of file" } + ]; + + expect(result).toEqual(expected); + }); + + it("should correctly apply multiple insertions and deletions", () => { + const sourceCode = `package main +import "fmt" +func main() { + fmt.Println("Hello") + fmt.Println("World") +}`; + + const diffText = `--- original.go ++++ updated.go +@@ -1,8 +1,11 @@ + package main + +-import "fmt" ++import ( ++ "fmt" ++ "time" ++) + + func main() { +- fmt.Println("Hello") ++ fmt.Printf("The time is: %v\\n", time.Now()) +- fmt.Println("World") ++ fmt.Println("Goodbye!") + }`; + const result = applyUnifiedDiff(sourceCode, diffText); + + const expected = [ + { type: "same", line: "package main" }, + { type: "same", line: "" }, + { type: "old", line: "import \"fmt\"" }, + { type: "new", line: "import (" }, + { type: "new", line: " \"fmt\"" }, + { type: "new", line: " \"time\"" }, + { type: "new", line: ")" }, + { type: "same", line: "" }, + { type: "same", line: "func main() {" }, + { type: "old", line: " fmt.Println(\"Hello\")" }, + { type: "new", line: " fmt.Printf(\"The time is: %v\\n\", time.Now())" }, + { type: "old", line: " fmt.Println(\"World\")" }, + { type: "new", line: " fmt.Println(\"Goodbye!\")" }, + { type: "same", line: "}" } + ]; + + expect(result).toEqual(expected); + }); + + it("should correctly apply multiple diff blocks", () => { + const sourceCode = `package main +import ( + "bufio" + "fmt" + "math" + "os" + "strconv" + "strings" + "testing" +) +func main() { + scanner := bufio.NewScanner(os.Stdin) + fmt.Println("Calculator started! Available operations:") + fmt.Println(" + : Addition") + fmt.Println(" - : Subtraction") + fmt.Println(" * : Multiplication") + fmt.Println(" / : Division") + fmt.Println(" ^ : Power") + fmt.Println(" √ : Square root (use only one number)") + for { + fmt.Print("Enter calculation (e.g., 5 + 3 or √ 16) or 'q' to quit: ") + scanner.Scan() + input := scanner.Text() + if strings.ToLower(input) == "q" { + fmt.Println("Goodbye!") + break + } + result, err := calculate(input) + if err != nil { + fmt.Printf("Error: %v\n", err) + continue + } + fmt.Printf("Result: %v\n", result) + } +} +func calculate(input string) (float64, error) { + parts := strings.Fields(input) + if len(parts) < 2 { + return 0, fmt.Errorf("invalid input format: please use 'number operator number' or '√ number'") + } + if parts[0] == "√" { + if len(parts) != 2 { + return 0, fmt.Errorf("square root operation requires exactly one number") + } + num, err := strconv.ParseFloat(parts[1], 64) + if err != nil { + return 0, fmt.Errorf("invalid number for square root: %v", err) + } + if num < 0 { + return 0, fmt.Errorf("cannot calculate square root of a negative number") + } + return math.Sqrt(num), nil + } + if len(parts) != 3 { + return 0, fmt.Errorf("invalid input format: please use 'number operator number'") + } + num1, err := strconv.ParseFloat(parts[0], 64) + if err != nil { + return 0, fmt.Errorf("invalid first number: %v", err) + } + operator := parts[1] + num2, err := strconv.ParseFloat(parts[2], 64) + if err != nil { + return 0, fmt.Errorf("invalid second number: %v", err) + } + switch operator { + case "+": + return num1 + num2, nil + case "-": + return num1 - num2, nil + case "*": + return num1 * num2, nil + case "/": + if num2 == 0 { + return 0, fmt.Errorf("division by zero is not allowed") + } + return num1 / num2, nil + case "^": + return math.Pow(num1, num2), nil + default: + return 0, fmt.Errorf("invalid operator: must be +, -, *, /, ^, or √") + } +} +func TestCalculate(t *testing.T) { + tests := []struct { + input string + expected float64 + hasError bool + }{ + {"2 + 3", 5, false}, + {"10 - 5", 5, false}, + {"4 * 3", 12, false}, + {"15 / 3", 5, false}, + {"2 ^ 3", 8, false}, + {"√ 16", 4, false}, + {"2 + a", 0, true}, + {"15 / 0", 0, true}, + {"√ -4", 0, true}, + {"3 $ 4", 0, true}, + {"", 0, true}, + {"1", 0, true}, + {"1 +", 0, true}, + {"+ 1", 0, true}, + {"√ 2 3", 0, true}, + } + for _, test := range tests { + result, err := calculate(test.input) + if test.hasError && err == nil { + t.Errorf("Expected error for input '%s', but got none", test.input) + continue + } + if !test.hasError && err != nil { + t.Errorf("Unexpected error for input '%s': %v", test.input, err) + continue + } + if !test.hasError && result != test.expected { + t.Errorf("For input '%s': expected %f, but got %f", test.input, test.expected, result) + } + } +} +func TestSpecialCases(t *testing.T) { + result, err := calculate("2.5 + 2.5") + if err != nil { + t.Errorf("Unexpected error for floating point addition: %v", err) + } + if result != 5.0 { + t.Errorf("Floating point addition failed: expected 5.0, got %f", result) + } + result, err = calculate("2.5 ^ 2") + if err != nil { + t.Errorf("Unexpected error for power operation: %v", err) + } + expected := 6.25 + if math.Abs(result-expected) > 0.0001 { + t.Errorf("Power operation failed: expected %f, got %f", expected, result) + } + result, err = calculate("√ 2") + if err != nil { + t.Errorf("Unexpected error for square root: %v", err) + } + expected = math.Sqrt(2) + if math.Abs(result-expected) > 0.0001 { + t.Errorf("Square root operation failed: expected %f, got %f", expected, result) + } +} +func TestLargeNumbers(t *testing.T) { + result, err := calculate("1000000000 + 1000000000") + if err != nil { + t.Errorf("Unexpected error for adding large numbers: %v", err) + } + if result != 2000000000 { + t.Errorf("Adding large numbers failed: expected 2000000000, got %f", result) + } + result, err = calculate("1000000 * 1000000") + if err != nil { + t.Errorf("Unexpected error for multiplying large numbers: %v", err) + } + if result != 1000000000000 { + t.Errorf("Multiplying large numbers failed: expected 1000000000000, got %f", result) + } + result, err = calculate("2 ^ 30") + if err != nil { + t.Errorf("Unexpected error for large exponent operation: %v", err) + } + expected := math.Pow(2, 30) + if result != expected { + t.Errorf("Power operation with large exponent failed: expected %f, got %f", expected, result) + } + result, err = calculate("1000000000000 / 1000000") + if err != nil { + t.Errorf("Unexpected error for dividing large numbers: %v", err) + } + if result != 1000000 { + t.Errorf("Dividing large numbers failed: expected 1000000, got %f", result) + } +}`; + + const diffText = `--- original.go ++++ updated.go +@@ -30,6 +30,7 @@ + fmt.Println(" / : Division") + fmt.Println(" ^ : Power") + fmt.Println(" √ : Square root (use only one number)") ++ fmt.Println(" log: Logarithm (use 'log base number')") ++ fmt.Println(" Base must be > 0 and != 1, number must be > 0") + for { + fmt.Print("Enter calculation (e.g., 5 + 3 or √ 16) or 'q' to quit: ") +@@ -73,6 +74,8 @@ + } + return math.Sqrt(num), nil + } ++ ++ // Handle logarithmic operations ++ if parts[0] == "log" { ++ if len(parts) != 3 { ++ return 0, fmt.Errorf("logarithm operation requires exactly two arguments: 'log base number'") ++ } ++ base, err := strconv.ParseFloat(parts[1], 64) ++ if err != nil || base <= 0 || base == 1 { ++ return 0, fmt.Errorf("invalid base for logarithm: must be > 0 and != 1") ++ } ++ num, err := strconv.ParseFloat(parts[2], 64) ++ if err != nil || num <= 0 { ++ return 0, fmt.Errorf("invalid number for logarithm: must be > 0") ++ } ++ return math.Log(num) / math.Log(base), nil ++ } ++ + if len(parts) != 3 { + return 0, fmt.Errorf("invalid input format: please use 'number operator number'") +@@ -155,6 +158,15 @@ + } + } + } ++ ++func TestLogarithmicCases(t *testing.T) { ++ tests := []struct { ++ input string ++ expected float64 ++ hasError bool ++ }{ ++ {"log 2 8", 3, false}, ++ {"log 10 100", 2, false}, ++ {"log 10 -5", 0, true}, ++ {"log 1 100", 0, true}, ++ {"log 0.5 0.25", 2, false}, ++ }`; + const result = applyUnifiedDiff(sourceCode, diffText); + + expect(result[0].line).toEqual("package main"); + // 1st block + expect(result[21].line).toEqual(" fmt.Println(\" log: Logarithm (use 'log base number')\")"); + expect(result[22].line).toEqual(" fmt.Println(\" Base must be > 0 and != 1, number must be > 0\")"); + // 2nd block + expect(result[60]).toEqual({type: "same", line: "\t}"}); + expect(result[61]).toEqual({type: "new", line: "\t"}); + expect(result[62]).toEqual({type: "new", line: "\t// Handle logarithmic operations"}); + expect(result[77]).toEqual({type: "new", line: ""}); + expect(result[78]).toEqual({type: "same", line: "\tif len(parts) != 3 {"}); + // 3rd block + expect(result[145]).toEqual({type: "same", line: "}"}); + expect(result[146]).toEqual({type: "new", line: ""}); + expect(result[147]).toEqual({type: "new", line: "func TestLogarithmicCases(t *testing.T) {"}); + expect(result[158]).toEqual({type: "new", line: "\t}"}); + expect(result[159]).toEqual({type: "same", line: ""}); + expect(result[160]).toEqual({type: "same", line: "func TestSpecialCases(t *testing.T) {"}); + + }); + + it("should throw error when hunk cannot be matched to source", () => { + const sourceCode = `line1 +line2 +line3`; + + const diffText = `--- a.txt ++++ b.txt +@@ -1,3 +1,4 @@ +missing1 +-missing2 ++newline2 +missing3`; + + expect(() => applyUnifiedDiff(sourceCode, diffText)) + .toThrow("Hunk could not be applied cleanly to source code."); + }); +}); diff --git a/core/edit/lazy/unifiedDiffApply.ts b/core/edit/lazy/unifiedDiffApply.ts new file mode 100644 index 000000000..c5768f1d4 --- /dev/null +++ b/core/edit/lazy/unifiedDiffApply.ts @@ -0,0 +1,152 @@ +import { DiffLine } from "../../index"; + +/** + * Checks if a string matches unified diff format by validating: + * 1. Has at least one hunk header (@@ -n,m +n,m @@) + * 2. Contains valid diff content lines (starting with +, -, or space) which are not header lines + */ +export function isUnifiedDiffFormat(diff: string): boolean { + const lines = diff.trim().split("\n"); + + if (lines.length < 3) {return false;} + + let hasHunkHeader = false; + let hasValidContent = false; + + for (const line of lines) { + if (line.startsWith("---") || line.startsWith("+++")) { + // ignore file headers - they are not required or useful + } else if (line.match(/^@@ -\d+,?\d* \+\d+,?\d* @@/)) { + hasHunkHeader = true; + } else if (line.match(/^[+ -]/) || line === "") { + hasValidContent = true; + } + } + + return hasHunkHeader && hasValidContent; +} + +function extractBeforeLines(hunkLines: string[]): string[] { + return hunkLines + .filter((line) => line.startsWith("-") || !line.startsWith("+")) + .map((line) => line.substring(1)); +} + +/** + * Applies a unified diff to source code and returns an array of DiffLine objects. + * Each DiffLine contains a type ("same", "new", or "old") and the line content. + * + * @throws Error if the diff cannot be cleanly applied to the source + */ +export function applyUnifiedDiff(sourceCode: string, unifiedDiffText: string): DiffLine[] { + const sourceLines = sourceCode.split(/\r?\n/); + const hunks = parseUnifiedDiff(unifiedDiffText); + const diffResult: DiffLine[] = []; + let currentPos = 0; // pointer in sourceLines + + for (const hunk of hunks) { + const hunkBeforeLines = extractBeforeLines(hunk.lines); + const hunkStart = findHunkInSource(sourceLines, hunkBeforeLines, currentPos); + if (hunkStart === -1) { + // All hunks must be found in the source code. If not, throw an error. + throw new Error("Hunk could not be applied cleanly to source code."); + } + + // Emit any unchanged lines that come before this hunk. + for (let i = currentPos; i < hunkStart; i++) { + diffResult.push({ type: "same", line: sourceLines[i] }); + } + let hunkSourcePos = hunkStart; + + for (const dline of hunk.lines) { + const srcLine = sourceLines[hunkSourcePos]; + if (dline.startsWith("+")) { + // Insertion: output new line (strip the '+' marker) + diffResult.push({ type: "new", line: dline.substring(1) }); + } else if (dline.startsWith("-")) { + // Removal: output the removed (old) line and advance the pointer. + diffResult.push({ type: "old", line: srcLine }); + hunkSourcePos++; + } else { + // Context line: use the source line (in case the diff’s context has a minor whitespace error) + // and advance the pointer. + diffResult.push({ type: "same", line: srcLine }); + hunkSourcePos++; + } + } + currentPos = hunkSourcePos; + } + + for (let i = currentPos; i < sourceLines.length; i++) { + diffResult.push({ type: "same", line: sourceLines[i] }); + } + return diffResult; +} + +interface Hunk { + lines: string[]; +} + +/** + * Parses a unified diff string into an array of hunks. + * It skips the file header lines (starting with "---" or "+++") and hunk header lines (starting with "@@"), + * then collects the remaining lines (which may start with '+' or '-' or have no prefix). + */ +function parseUnifiedDiff(diffText: string): Hunk[] { + const lines = diffText.split(/\r?\n/); + const hunks: Hunk[] = []; + let currentHunk: Hunk | null = null; + + for (const line of lines) { + if (line.startsWith("---") || line.startsWith("+++")) { + // Skip file header lines. + continue; + } + if (line.startsWith("@@")) { + if (currentHunk) { + hunks.push(currentHunk); + } + currentHunk = { lines: [] }; + continue; + } + currentHunk?.lines.push(line); + } + if (currentHunk) { + hunks.push(currentHunk); + } + return hunks; +} + +/** + * Searches for an occurrence of the block of lines (the “before” block) in sourceLines, + * starting at startIndex. Comparison is done by checking if the lines are exactly equal, + * or if their trimmed versions are equal. + * + * Returns the index in sourceLines where the block begins, or -1 if no match is found. + */ +function findHunkInSource(sourceLines: string[], hunkBeforeLines: string[], startIndex: number): number { + for (let i = startIndex; i <= sourceLines.length - hunkBeforeLines.length; i++) { + let match = true; + for (let j = 0; j < hunkBeforeLines.length; j++) { + const sl = sourceLines[i + j]; + const hl = hunkBeforeLines[j]; + if (!linesMatch(sl, hl)) { + match = false; + break; + } + } + if (match) { + return i; + } + } + return -1; +} + +/** + * Returns true if the two lines are either exactly equal or equal after trimming whitespace and tabs. + */ +function linesMatch(a: string, b: string): boolean { + const trimmedA = a.replace(/^\s+/, ""); + const trimmedB = b.replace(/^\s+/, ""); + return trimmedA === trimmedB; +} diff --git a/docs/docs/edit/how-to-use-it.md b/docs/docs/edit/how-to-use-it.md index 850c34b60..19f8e0ccd 100644 --- a/docs/docs/edit/how-to-use-it.md +++ b/docs/docs/edit/how-to-use-it.md @@ -35,3 +35,10 @@ You can navigate through each proposed change, accepting or rejecting them using You can also accept or reject all changes at once using cmd/ctrl + shift + enter (to accept) or cmd/ctrl + shift + delete/backspace (to reject). If you want to request a new suggestion for the same highlighted code section, you can use cmd/ctrl + i to re-prompt the model. + +## Instant Diff Apply + +If you have large files (exeeding the output token of your model) the edit apply will delete all lines that exceed the model window. To mitigate you can instead of applying the changes directly, ask the chat LLM to "generate a unified diff". +The resulting diff (if the LLM has not made a mistake) can be instantly applied, changing only the lines that need to change. + +Explainer Video: https://youtu.be/b7Xxsot4gyw \ No newline at end of file From 15e93dd5d0dc3b5dcd00504833beacbddbfe44f3 Mon Sep 17 00:00:00 2001 From: Ingo Eichhorst Date: Sun, 23 Feb 2025 13:16:50 +0100 Subject: [PATCH 03/33] fix: fixed misallignment in tests caused by linter --- core/edit/lazy/unifiedDiffApply.test.ts | 31 ++++++++++++++----------- 1 file changed, 17 insertions(+), 14 deletions(-) diff --git a/core/edit/lazy/unifiedDiffApply.test.ts b/core/edit/lazy/unifiedDiffApply.test.ts index c7a5a8370..f0eae9b64 100644 --- a/core/edit/lazy/unifiedDiffApply.test.ts +++ b/core/edit/lazy/unifiedDiffApply.test.ts @@ -46,8 +46,10 @@ describe("isUnifiedDiffFormat", () => { it("should return true in case of empty lines", () => { const diffWithoutFileHeaders = `@@ -1,3 +1,4 @@ line1 + -line2 +newline2 + line3`; expect(isUnifiedDiffFormat(diffWithoutFileHeaders)).toBe(true); }); @@ -98,7 +100,9 @@ describe("applyUnifiedDiff", () => { it("should correctly apply multiple insertions and deletions", () => { const sourceCode = `package main + import "fmt" + func main() { fmt.Println("Hello") fmt.Println("World") @@ -375,22 +379,21 @@ func TestLargeNumbers(t *testing.T) { expect(result[0].line).toEqual("package main"); // 1st block - expect(result[21].line).toEqual(" fmt.Println(\" log: Logarithm (use 'log base number')\")"); - expect(result[22].line).toEqual(" fmt.Println(\" Base must be > 0 and != 1, number must be > 0\")"); + expect(result[18].line).toEqual("\tfmt.Println(\" √ : Square root (use only one number)\")"); + expect(result[19].line).toEqual(" fmt.Println(\" log: Logarithm (use 'log base number')\")"); + expect(result[20].line).toEqual(" fmt.Println(\" Base must be > 0 and != 1, number must be > 0\")"); // 2nd block - expect(result[60]).toEqual({type: "same", line: "\t}"}); - expect(result[61]).toEqual({type: "new", line: "\t"}); - expect(result[62]).toEqual({type: "new", line: "\t// Handle logarithmic operations"}); - expect(result[77]).toEqual({type: "new", line: ""}); - expect(result[78]).toEqual({type: "same", line: "\tif len(parts) != 3 {"}); + expect(result[56]).toEqual({type: "same", line: "\t}"}); + expect(result[57]).toEqual({type: "new", line: "\t"}); + expect(result[58]).toEqual({type: "new", line: "\t// Handle logarithmic operations"}); + expect(result[73]).toEqual({type: "new", line: ""}); + expect(result[74]).toEqual({type: "same", line: "\tif len(parts) != 3 {"}); // 3rd block - expect(result[145]).toEqual({type: "same", line: "}"}); - expect(result[146]).toEqual({type: "new", line: ""}); - expect(result[147]).toEqual({type: "new", line: "func TestLogarithmicCases(t *testing.T) {"}); - expect(result[158]).toEqual({type: "new", line: "\t}"}); - expect(result[159]).toEqual({type: "same", line: ""}); - expect(result[160]).toEqual({type: "same", line: "func TestSpecialCases(t *testing.T) {"}); - + expect(result[140]).toEqual({type: "same", line: "}"}); + expect(result[141]).toEqual({type: "new", line: ""}); + expect(result[142]).toEqual({type: "new", line: "func TestLogarithmicCases(t *testing.T) {"}); + expect(result[153]).toEqual({type: "new", line: "\t}"}); + expect(result[154]).toEqual({type: "same", line: "func TestSpecialCases(t *testing.T) {"}); }); it("should throw error when hunk cannot be matched to source", () => { From 753b3bc938944882d8523053458f3de2c21d08b4 Mon Sep 17 00:00:00 2001 From: Simon Chauvin <34301767+chauvinSimon@users.noreply.github.com> Date: Mon, 3 Mar 2025 14:29:17 +0100 Subject: [PATCH 04/33] Update codebase.mdx - fix yaml against LanceError To prevent the popup of VSCode Error: `Error getting context items from codebase: Error: lance error: LanceError(IO): k must be positive ...` --- docs/docs/customize/deep-dives/codebase.mdx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/docs/customize/deep-dives/codebase.mdx b/docs/docs/customize/deep-dives/codebase.mdx index 24256672e..409ecd080 100644 --- a/docs/docs/customize/deep-dives/codebase.mdx +++ b/docs/docs/customize/deep-dives/codebase.mdx @@ -49,8 +49,8 @@ There are a few options that let you configure the behavior of the `@codebase` c context: - provider: codebase params: - nRetrieve: 25, - nFinal: 5, + nRetrieve: 25 + nFinal: 5 useReranking: true ``` From f86c95ebdbd1851bcbf0e6f22d18a348a8a154ed Mon Sep 17 00:00:00 2001 From: liuk Date: Sat, 8 Mar 2025 23:27:04 +0800 Subject: [PATCH 05/33] fix: Ensure valid line index for highlighter --- .../continueintellijextension/editor/DiffStreamHandler.kt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt index e44c08dd5..55df303a8 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt @@ -13,6 +13,7 @@ import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.TextEditor import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile +import kotlin.math.max import kotlin.math.min @@ -179,7 +180,7 @@ class DiffStreamHandler( // Update the highlighter to show the current line curLine.highlighter?.let { editor.markupModel.removeHighlighter(it) } curLine.highlighter = editor.markupModel.addLineHighlighter( - curLineKey, min(curLine.index, editor.document.lineCount - 1), HighlighterLayer.LAST + curLineKey, min(curLine.index, max(0, editor.document.lineCount - 1)), HighlighterLayer.LAST ) // Remove the unfinished lines highlighter From 7d7fe143ec9b7148cff6b383016b2baf3eb09e29 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 8 Mar 2025 08:59:40 -0800 Subject: [PATCH 06/33] move to dedicated apply deep dive, to be completed --- docs/docs/customize/deep-dives/_apply.md | 16 ++++++++++++++++ docs/docs/edit/how-to-use-it.md | 7 ------- 2 files changed, 16 insertions(+), 7 deletions(-) create mode 100644 docs/docs/customize/deep-dives/_apply.md diff --git a/docs/docs/customize/deep-dives/_apply.md b/docs/docs/customize/deep-dives/_apply.md new file mode 100644 index 000000000..1f87a1993 --- /dev/null +++ b/docs/docs/customize/deep-dives/_apply.md @@ -0,0 +1,16 @@ +--- +description: Learn how to use the Apply feature +keywords: [apply, speculative] +toc_max_heading_level: 5 +--- + + + +# Apply + +## Instant Diff Apply + +If you have large files (exeeding the output token of your model) the edit apply will delete all lines that exceed the model window. To mitigate you can instead of applying the changes directly, ask the chat LLM to "generate a unified diff". +The resulting diff (if the LLM has not made a mistake) can be instantly applied, changing only the lines that need to change. + +Explainer Video: https://youtu.be/b7Xxsot4gyw diff --git a/docs/docs/edit/how-to-use-it.md b/docs/docs/edit/how-to-use-it.md index 19f8e0ccd..850c34b60 100644 --- a/docs/docs/edit/how-to-use-it.md +++ b/docs/docs/edit/how-to-use-it.md @@ -35,10 +35,3 @@ You can navigate through each proposed change, accepting or rejecting them using You can also accept or reject all changes at once using cmd/ctrl + shift + enter (to accept) or cmd/ctrl + shift + delete/backspace (to reject). If you want to request a new suggestion for the same highlighted code section, you can use cmd/ctrl + i to re-prompt the model. - -## Instant Diff Apply - -If you have large files (exeeding the output token of your model) the edit apply will delete all lines that exceed the model window. To mitigate you can instead of applying the changes directly, ask the chat LLM to "generate a unified diff". -The resulting diff (if the LLM has not made a mistake) can be instantly applied, changing only the lines that need to change. - -Explainer Video: https://youtu.be/b7Xxsot4gyw \ No newline at end of file From 6bc7c5560e6a003b208a363deb38a65e5b4adb73 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 8 Mar 2025 11:54:09 -0800 Subject: [PATCH 07/33] load .continue/assistants profiles --- core/config/ConfigHandler.ts | 48 ++++++++++++++-- core/config/getSystemPromptDotFile.ts | 55 +++++++++++++++++++ .../profile/ControlPlaneProfileLoader.ts | 1 + core/config/profile/LocalProfileLoader.ts | 2 + core/config/profile/PlatformProfileLoader.ts | 1 + core/config/profile/doLoadConfig.ts | 3 +- core/util/paths.ts | 4 ++ extensions/vscode/package-lock.json | 4 +- 8 files changed, 110 insertions(+), 8 deletions(-) diff --git a/core/config/ConfigHandler.ts b/core/config/ConfigHandler.ts index b9a0f0896..96b5fc6da 100644 --- a/core/config/ConfigHandler.ts +++ b/core/config/ConfigHandler.ts @@ -20,6 +20,7 @@ import { GlobalContext } from "../util/GlobalContext.js"; import { getConfigJsonPath, getConfigYamlPath } from "../util/paths.js"; import { localPathToUri } from "../util/pathToUri.js"; +import { getAllAssistantFiles } from "./getSystemPromptDotFile.js"; import { LOCAL_ONBOARDING_CHAT_MODEL, LOCAL_ONBOARDING_PROVIDER_TITLE, @@ -86,6 +87,25 @@ export class ConfigHandler { }); } + /** + * Users can define as many local assistants as they want in a `.continue/assistants` folder + */ + private async getLocalAssistantProfiles() { + const assistantFiles = await getAllAssistantFiles(this.ide); + const profiles = assistantFiles.map((assistant) => { + return new LocalProfileLoader( + this.ide, + this.ideSettingsPromise, + this.controlPlaneClient, + this.writeLog, + assistant.path, + ); + }); + return profiles.map( + (profile) => new ProfileLifecycleManager(profile, this.ide), + ); + } + /** * Retrieves the titles of additional context providers that are of type "submenu". * @@ -98,13 +118,20 @@ export class ConfigHandler { } private async init() { + try { + await this.loadLocalProfilesOnly(); + } catch (e) { + console.error("Failed to load local assistants: ", e); + } + try { await this.fetchControlPlaneProfiles(); } catch (e) { // If this fails, make sure at least local profile is loaded console.error("Failed to fetch control plane profiles in init: ", e); - await this.updateAvailableProfiles([this.localProfileManager]); + await this.loadLocalProfilesOnly(); } + try { const configResult = await this.loadConfig(); this.notifyConfigListeners(configResult); @@ -189,7 +216,8 @@ export class ConfigHandler { if (selectedOrgId === null) { // Personal - profiles = [...hubProfiles, this.localProfileManager]; + const allLocalProfiles = await this.getAllLocalProfiles(); + profiles = [...hubProfiles, ...allLocalProfiles]; } else { // Organization profiles = hubProfiles; @@ -199,6 +227,16 @@ export class ConfigHandler { await this.updateAvailableProfiles(profiles); } + private async getAllLocalProfiles() { + const localAssistantProfiles = await this.getLocalAssistantProfiles(); + return [this.localProfileManager, ...localAssistantProfiles]; + } + + private async loadLocalProfilesOnly() { + const allLocalProfiles = await this.getAllLocalProfiles(); + await this.updateAvailableProfiles(allLocalProfiles); + } + private async updateAvailableProfiles(profiles: ProfileLifecycleManager[]) { this.profiles = profiles; @@ -278,7 +316,7 @@ export class ConfigHandler { } else { try { const workspaces = await this.controlPlaneClient.listWorkspaces(); - const profiles = [this.localProfileManager]; + const profiles = await this.getAllLocalProfiles(); workspaces.forEach((workspace) => { const profileLoader = new ControlPlaneProfileLoader( workspace.id, @@ -296,7 +334,7 @@ export class ConfigHandler { await this.updateAvailableProfiles(profiles); } catch (e: any) { console.error("Failed to load profiles: ", e); - await this.updateAvailableProfiles([this.localProfileManager]); + await this.loadLocalProfilesOnly(); } } } @@ -355,7 +393,7 @@ export class ConfigHandler { ); this.fetchControlPlaneProfiles().catch(async (e) => { console.error("Failed to fetch control plane profiles: ", e); - await this.updateAvailableProfiles([this.localProfileManager]); + await this.loadLocalProfilesOnly(); await this.reloadConfig(); }); } diff --git a/core/config/getSystemPromptDotFile.ts b/core/config/getSystemPromptDotFile.ts index 550144cd8..1bfc6d1a1 100644 --- a/core/config/getSystemPromptDotFile.ts +++ b/core/config/getSystemPromptDotFile.ts @@ -1,4 +1,6 @@ import { IDE } from ".."; +import { walkDir } from "../indexing/walkDir"; +import { getGlobalAssistantsPath } from "../util/paths"; import { joinPathsToUri } from "../util/uri"; export const SYSTEM_PROMPT_DOT_FILE = ".continuerules"; @@ -24,3 +26,56 @@ export async function getSystemPromptDotFile(ide: IDE): Promise { return prompts.join("\n\n"); } + +export const ASSISTANTS_FOLDER = ".continue/assistants"; + +export async function getAssistantFilesFromDir( + ide: IDE, + dir: string, +): Promise<{ path: string; content: string }[]> { + try { + const exists = await ide.fileExists(dir); + + if (!exists) { + return []; + } + + const uris = await walkDir(dir, ide); + const assistantFilePaths = uris.filter( + (p) => p.endsWith(".yaml") || p.endsWith(".yml"), + ); + const results = assistantFilePaths.map(async (uri) => { + const content = await ide.readFile(uri); // make a try catch + return { path: uri, content }; + }); + return Promise.all(results); + } catch (e) { + console.error(e); + return []; + } +} + +export async function getAllAssistantFiles( + ide: IDE, +): Promise<{ path: string; content: string }[]> { + const workspaceDirs = await ide.getWorkspaceDirs(); + let assistantFiles: { path: string; content: string }[] = []; + + let dirsToCheck = [ASSISTANTS_FOLDER]; + const fullDirs = workspaceDirs + .map((dir) => dirsToCheck.map((d) => joinPathsToUri(dir, d))) + .flat(); + + fullDirs.push(getGlobalAssistantsPath()); + + assistantFiles = ( + await Promise.all(fullDirs.map((dir) => getAssistantFilesFromDir(ide, dir))) + ).flat(); + + return await Promise.all( + assistantFiles.map(async (file) => { + const content = await ide.readFile(file.path); + return { path: file.path, content }; + }), + ); +} diff --git a/core/config/profile/ControlPlaneProfileLoader.ts b/core/config/profile/ControlPlaneProfileLoader.ts index 6df837cf4..fa62d042f 100644 --- a/core/config/profile/ControlPlaneProfileLoader.ts +++ b/core/config/profile/ControlPlaneProfileLoader.ts @@ -68,6 +68,7 @@ export default class ControlPlaneProfileLoader implements IProfileLoader { undefined, undefined, this.workspaceId, + undefined, ); return { diff --git a/core/config/profile/LocalProfileLoader.ts b/core/config/profile/LocalProfileLoader.ts index 9ccf5c812..921a6170d 100644 --- a/core/config/profile/LocalProfileLoader.ts +++ b/core/config/profile/LocalProfileLoader.ts @@ -27,6 +27,7 @@ export default class LocalProfileLoader implements IProfileLoader { private ideSettingsPromise: Promise, private controlPlaneClient: ControlPlaneClient, private writeLog: (message: string) => Promise, + private overrideConfigYamlByPath?: string | undefined, ) {} async doLoadConfig(): Promise> { @@ -39,6 +40,7 @@ export default class LocalProfileLoader implements IProfileLoader { undefined, undefined, this.description.id, + this.overrideConfigYamlByPath, ); this.description.errors = result.errors; diff --git a/core/config/profile/PlatformProfileLoader.ts b/core/config/profile/PlatformProfileLoader.ts index c0fa4c5cc..0a36d7492 100644 --- a/core/config/profile/PlatformProfileLoader.ts +++ b/core/config/profile/PlatformProfileLoader.ts @@ -70,6 +70,7 @@ export default class PlatformProfileLoader implements IProfileLoader { packageSlug: this.packageSlug, }, this.description.id, + undefined ); return { diff --git a/core/config/profile/doLoadConfig.ts b/core/config/profile/doLoadConfig.ts index 0ec9b4137..2e3e403ef 100644 --- a/core/config/profile/doLoadConfig.ts +++ b/core/config/profile/doLoadConfig.ts @@ -36,6 +36,7 @@ export default async function doLoadConfig( overrideConfigYaml: AssistantUnrolled | undefined, platformConfigMetadata: PlatformConfigMetadata | undefined, profileId: string, + overrideConfigYamlByPath: string | undefined ): Promise> { const workspaceConfigs = await getWorkspaceConfigs(ide); const ideInfo = await ide.getIdeInfo(); @@ -50,7 +51,7 @@ export default async function doLoadConfig( migrateJsonSharedConfig(configJsonPath, ide); } - const configYamlPath = getConfigYamlPath(ideInfo.ideType); + const configYamlPath = overrideConfigYamlByPath || getConfigYamlPath(ideInfo.ideType); let newConfig: ContinueConfig | undefined; let errors: ConfigValidationError[] | undefined; diff --git a/core/util/paths.ts b/core/util/paths.ts index 31ed8bb02..fc537ed63 100644 --- a/core/util/paths.ts +++ b/core/util/paths.ts @@ -353,6 +353,10 @@ export function getGlobalPromptsPath(): string { return path.join(getContinueGlobalPath(), "prompts"); } +export function getGlobalAssistantsPath(): string { + return path.join(getContinueGlobalPath(), "assistants"); +} + export function readAllGlobalPromptFiles( folderPath: string = getGlobalPromptsPath(), ): { path: string; content: string }[] { diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index ed46978a0..43750054e 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "1.1.4", + "version": "1.1.5", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "1.1.4", + "version": "1.1.5", "license": "Apache-2.0", "dependencies": { "@continuedev/fetch": "^1.0.3", From edcf5b321cb201c328ed640c13f8e99ac7559137 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 8 Mar 2025 16:09:08 -0800 Subject: [PATCH 08/33] load multiple local assistants --- core/config/ConfigHandler.ts | 56 +++++++++---------- core/config/ProfileLifecycleManager.ts | 1 + .../profile/ControlPlaneProfileLoader.ts | 2 + core/config/profile/LocalProfileLoader.ts | 52 +++++++++++------ core/config/profile/PlatformProfileLoader.ts | 46 ++++++++++++--- core/config/profile/doLoadConfig.ts | 10 +++- core/config/yaml/loadYaml.ts | 6 +- core/control-plane/env.ts | 2 +- core/util/paths.ts | 10 +++- gui/src/components/AddModelButtonSubtext.tsx | 2 +- .../components/modelSelection/ModelSelect.tsx | 14 ++--- .../modelSelection/platform/utils.ts | 3 +- gui/src/pages/AddNewModel/AddNewModel.tsx | 2 +- gui/src/pages/config/index.tsx | 2 +- gui/src/util/index.ts | 2 +- 15 files changed, 134 insertions(+), 76 deletions(-) diff --git a/core/config/ConfigHandler.ts b/core/config/ConfigHandler.ts index 96b5fc6da..d50e63235 100644 --- a/core/config/ConfigHandler.ts +++ b/core/config/ConfigHandler.ts @@ -1,5 +1,3 @@ -import * as fs from "node:fs"; - import { ConfigResult, FullSlug } from "@continuedev/config-yaml"; import { @@ -17,8 +15,6 @@ import { } from "../index.js"; import Ollama from "../llm/llms/Ollama.js"; import { GlobalContext } from "../util/GlobalContext.js"; -import { getConfigJsonPath, getConfigYamlPath } from "../util/paths.js"; -import { localPathToUri } from "../util/pathToUri.js"; import { getAllAssistantFiles } from "./getSystemPromptDotFile.js"; import { @@ -98,7 +94,7 @@ export class ConfigHandler { this.ideSettingsPromise, this.controlPlaneClient, this.writeLog, - assistant.path, + assistant, ); }); return profiles.map( @@ -162,14 +158,12 @@ export class ConfigHandler { async openConfigProfile(profileId?: string) { let openProfileId = profileId || this.selectedProfileId; - if (openProfileId === "local") { + const profile = this.profiles?.find( + (p) => p.profileDescription.id === openProfileId, + ); + if (profile?.profileDescription.profileType === "local") { const ideInfo = await this.ide.getIdeInfo(); - const configYamlPath = getConfigYamlPath(ideInfo.ideType); - if (fs.existsSync(configYamlPath)) { - await this.ide.openFile(localPathToUri(configYamlPath)); - } else { - await this.ide.openFile(localPathToUri(getConfigJsonPath())); - } + await this.ide.openFile(profile.profileDescription.uri); } else { const env = await getControlPlaneEnv(this.ide.getIdeSettings()); await this.ide.openUrl(`${env.APP_URL}${openProfileId}`); @@ -194,25 +188,27 @@ export class ConfigHandler { const assistants = await this.controlPlaneClient.listAssistants(selectedOrgId); - const hubProfiles = assistants.map((assistant) => { - const profileLoader = new PlatformProfileLoader( - { - ...assistant.configResult, - config: assistant.configResult.config, - }, - assistant.ownerSlug, - assistant.packageSlug, - assistant.iconUrl, - assistant.configResult.config?.version ?? "latest", - this.controlPlaneClient, - this.ide, - this.ideSettingsPromise, - this.writeLog, - this.reloadConfig.bind(this), - ); + const hubProfiles = await Promise.all( + assistants.map(async (assistant) => { + const profileLoader = await PlatformProfileLoader.create( + { + ...assistant.configResult, + config: assistant.configResult.config, + }, + assistant.ownerSlug, + assistant.packageSlug, + assistant.iconUrl, + assistant.configResult.config?.version ?? "latest", + this.controlPlaneClient, + this.ide, + this.ideSettingsPromise, + this.writeLog, + this.reloadConfig.bind(this), + ); - return new ProfileLifecycleManager(profileLoader, this.ide); - }); + return new ProfileLifecycleManager(profileLoader, this.ide); + }), + ); if (selectedOrgId === null) { // Personal diff --git a/core/config/ProfileLifecycleManager.ts b/core/config/ProfileLifecycleManager.ts index deaf5f40e..b7946ed7d 100644 --- a/core/config/ProfileLifecycleManager.ts +++ b/core/config/ProfileLifecycleManager.ts @@ -21,6 +21,7 @@ export interface ProfileDescription { id: string; iconUrl: string; errors: ConfigValidationError[] | undefined; + uri: string; } export interface OrganizationDescription { diff --git a/core/config/profile/ControlPlaneProfileLoader.ts b/core/config/profile/ControlPlaneProfileLoader.ts index fa62d042f..cce940ab7 100644 --- a/core/config/profile/ControlPlaneProfileLoader.ts +++ b/core/config/profile/ControlPlaneProfileLoader.ts @@ -10,6 +10,7 @@ import { } from "../../index.js"; import { ProfileDescription } from "../ProfileLifecycleManager.js"; +import { PRODUCTION_ENV } from "../../control-plane/env.js"; import doLoadConfig from "./doLoadConfig.js"; import { IProfileLoader } from "./IProfileLoader.js"; @@ -40,6 +41,7 @@ export default class ControlPlaneProfileLoader implements IProfileLoader { }, title: workspaceTitle, errors: undefined, + uri: `${PRODUCTION_ENV.APP_URL}workspaces/${workspaceId}`, }; setInterval(async () => { diff --git a/core/config/profile/LocalProfileLoader.ts b/core/config/profile/LocalProfileLoader.ts index 921a6170d..13a1480c9 100644 --- a/core/config/profile/LocalProfileLoader.ts +++ b/core/config/profile/LocalProfileLoader.ts @@ -1,34 +1,54 @@ -import { ConfigResult } from "@continuedev/config-yaml"; +import { ConfigResult, parseConfigYaml } from "@continuedev/config-yaml"; import { ControlPlaneClient } from "../../control-plane/client.js"; import { ContinueConfig, IDE, IdeSettings } from "../../index.js"; import { ProfileDescription } from "../ProfileLifecycleManager.js"; +import { getPrimaryConfigFilePath } from "../../util/paths.js"; +import { localPathToUri } from "../../util/pathToUri.js"; import doLoadConfig from "./doLoadConfig.js"; import { IProfileLoader } from "./IProfileLoader.js"; export default class LocalProfileLoader implements IProfileLoader { static ID = "local"; - description: ProfileDescription = { - id: LocalProfileLoader.ID, - profileType: "local", - fullSlug: { - ownerSlug: "", - packageSlug: "", - versionSlug: "", - }, - iconUrl: "", - title: "Local Config", - errors: undefined, - }; constructor( private ide: IDE, private ideSettingsPromise: Promise, private controlPlaneClient: ControlPlaneClient, private writeLog: (message: string) => Promise, - private overrideConfigYamlByPath?: string | undefined, - ) {} + private overrideAssistantFile?: + | { path: string; content: string } + | undefined, + ) { + const description: ProfileDescription = { + id: overrideAssistantFile?.path ?? LocalProfileLoader.ID, + profileType: "local", + fullSlug: { + ownerSlug: "", + packageSlug: "", + versionSlug: "", + }, + iconUrl: "", + title: overrideAssistantFile?.path ?? "Local Config", + errors: undefined, + uri: + overrideAssistantFile?.path ?? + localPathToUri(getPrimaryConfigFilePath()), + }; + this.description = description; + if (overrideAssistantFile?.content) { + try { + const parsedAssistant = parseConfigYaml( + overrideAssistantFile?.content ?? "", + ); + this.description.title = parsedAssistant.name; + } catch (e) { + console.error("Failed to parse assistant file: ", e); + } + } + } + description: ProfileDescription; async doLoadConfig(): Promise> { const result = await doLoadConfig( @@ -40,7 +60,7 @@ export default class LocalProfileLoader implements IProfileLoader { undefined, undefined, this.description.id, - this.overrideConfigYamlByPath, + this.overrideAssistantFile?.path, ); this.description.errors = result.errors; diff --git a/core/config/profile/PlatformProfileLoader.ts b/core/config/profile/PlatformProfileLoader.ts index 0a36d7492..329a7a59e 100644 --- a/core/config/profile/PlatformProfileLoader.ts +++ b/core/config/profile/PlatformProfileLoader.ts @@ -5,6 +5,7 @@ import { ContinueConfig, IDE, IdeSettings } from "../../index.js"; import { ProfileDescription } from "../ProfileLifecycleManager.js"; +import { getControlPlaneEnv } from "../../control-plane/env.js"; import doLoadConfig from "./doLoadConfig.js"; import { IProfileLoader } from "./IProfileLoader.js"; @@ -21,21 +22,35 @@ export interface PlatformConfigMetadata { export default class PlatformProfileLoader implements IProfileLoader { static RELOAD_INTERVAL = 1000 * 5; // 5 seconds - description: ProfileDescription; - - constructor( + private constructor( private configResult: ConfigResult, private readonly ownerSlug: string, private readonly packageSlug: string, private readonly iconUrl: string, - versionSlug: string, + private readonly versionSlug: string, private readonly controlPlaneClient: ControlPlaneClient, private readonly ide: IDE, private ideSettingsPromise: Promise, private writeLog: (message: string) => Promise, private readonly onReload: () => void, - ) { - this.description = { + readonly description: ProfileDescription, + ) {} + + static async create( + configResult: ConfigResult, + ownerSlug: string, + packageSlug: string, + iconUrl: string, + versionSlug: string, + controlPlaneClient: ControlPlaneClient, + ide: IDE, + ideSettingsPromise: Promise, + writeLog: (message: string) => Promise, + onReload: () => void, + ): Promise { + const controlPlaneEnv = await getControlPlaneEnv(ideSettingsPromise); + + const description: ProfileDescription = { id: `${ownerSlug}/${packageSlug}`, profileType: "platform", fullSlug: { @@ -45,8 +60,23 @@ export default class PlatformProfileLoader implements IProfileLoader { }, title: configResult.config?.name ?? `${ownerSlug}/${packageSlug}`, errors: configResult.errors, - iconUrl: this.iconUrl, + iconUrl: iconUrl, + uri: `${controlPlaneEnv}${ownerSlug}/${packageSlug}`, }; + + return new PlatformProfileLoader( + configResult, + ownerSlug, + packageSlug, + iconUrl, + versionSlug, + controlPlaneClient, + ide, + ideSettingsPromise, + writeLog, + onReload, + description, + ); } async doLoadConfig(): Promise> { @@ -70,7 +100,7 @@ export default class PlatformProfileLoader implements IProfileLoader { packageSlug: this.packageSlug, }, this.description.id, - undefined + undefined, ); return { diff --git a/core/config/profile/doLoadConfig.ts b/core/config/profile/doLoadConfig.ts index 2e3e403ef..224b7b64e 100644 --- a/core/config/profile/doLoadConfig.ts +++ b/core/config/profile/doLoadConfig.ts @@ -19,13 +19,14 @@ import { getControlPlaneEnv } from "../../control-plane/env.js"; import { TeamAnalytics } from "../../control-plane/TeamAnalytics.js"; import ContinueProxy from "../../llm/llms/stubs/ContinueProxy"; import { getConfigJsonPath, getConfigYamlPath } from "../../util/paths"; +import { localPathOrUriToPath } from "../../util/pathToUri"; import { Telemetry } from "../../util/posthog"; import { TTS } from "../../util/tts"; import { loadContinueConfigFromJson } from "../load"; import { migrateJsonSharedConfig } from "../migrateSharedConfig"; +import { rectifySelectedModelsFromGlobalContext } from "../selectedModels"; import { loadContinueConfigFromYaml } from "../yaml/loadYaml"; import { PlatformConfigMetadata } from "./PlatformProfileLoader"; -import { rectifySelectedModelsFromGlobalContext } from "../selectedModels"; export default async function doLoadConfig( ide: IDE, @@ -36,7 +37,7 @@ export default async function doLoadConfig( overrideConfigYaml: AssistantUnrolled | undefined, platformConfigMetadata: PlatformConfigMetadata | undefined, profileId: string, - overrideConfigYamlByPath: string | undefined + overrideConfigYamlByPath: string | undefined, ): Promise> { const workspaceConfigs = await getWorkspaceConfigs(ide); const ideInfo = await ide.getIdeInfo(); @@ -51,7 +52,9 @@ export default async function doLoadConfig( migrateJsonSharedConfig(configJsonPath, ide); } - const configYamlPath = overrideConfigYamlByPath || getConfigYamlPath(ideInfo.ideType); + const configYamlPath = localPathOrUriToPath( + overrideConfigYamlByPath || getConfigYamlPath(ideInfo.ideType), + ); let newConfig: ContinueConfig | undefined; let errors: ConfigValidationError[] | undefined; @@ -69,6 +72,7 @@ export default async function doLoadConfig( overrideConfigYaml, platformConfigMetadata, controlPlaneClient, + configYamlPath, ); newConfig = result.config; errors = result.errors; diff --git a/core/config/yaml/loadYaml.ts b/core/config/yaml/loadYaml.ts index b008092e9..8d0ebf60a 100644 --- a/core/config/yaml/loadYaml.ts +++ b/core/config/yaml/loadYaml.ts @@ -366,10 +366,14 @@ export async function loadContinueConfigFromYaml( overrideConfigYaml: AssistantUnrolled | undefined, platformConfigMetadata: PlatformConfigMetadata | undefined, controlPlaneClient: ControlPlaneClient, + configYamlPath: string | undefined, ): Promise> { const rawYaml = overrideConfigYaml === undefined - ? fs.readFileSync(getConfigYamlPath(ideInfo.ideType), "utf-8") + ? fs.readFileSync( + configYamlPath ?? getConfigYamlPath(ideInfo.ideType), + "utf-8", + ) : ""; const configYamlResult = await loadConfigYaml( diff --git a/core/control-plane/env.ts b/core/control-plane/env.ts index 288901cab..8995dca7e 100644 --- a/core/control-plane/env.ts +++ b/core/control-plane/env.ts @@ -18,7 +18,7 @@ const WORKOS_CLIENT_ID_STAGING = "client_01J0FW6XCPMJMQ3CG51RB4HBZQ"; const WORKOS_ENV_ID_PRODUCTION = "continue"; const WORKOS_ENV_ID_STAGING = "continue-staging"; -const PRODUCTION_ENV: ControlPlaneEnv = { +export const PRODUCTION_ENV: ControlPlaneEnv = { DEFAULT_CONTROL_PLANE_PROXY_URL: "https://control-plane-api-service-i3dqylpbqa-uc.a.run.app/", CONTROL_PLANE_URL: diff --git a/core/util/paths.ts b/core/util/paths.ts index fc537ed63..02d2f43b5 100644 --- a/core/util/paths.ts +++ b/core/util/paths.ts @@ -103,7 +103,7 @@ export function getConfigJsonPath(ideType: IdeType = "vscode"): string { return p; } -export function getConfigYamlPath(ideType: IdeType): string { +export function getConfigYamlPath(ideType?: IdeType): string { const p = path.join(getContinueGlobalPath(), "config.yaml"); // if (!fs.existsSync(p)) { // if (ideType === "jetbrains") { @@ -115,6 +115,14 @@ export function getConfigYamlPath(ideType: IdeType): string { return p; } +export function getPrimaryConfigFilePath(): string { + const configYamlPath = getConfigYamlPath(); + if (fs.existsSync(configYamlPath)) { + return configYamlPath; + } + return getConfigJsonPath(); +} + export function getConfigTsPath(): string { const p = path.join(getContinueGlobalPath(), "config.ts"); if (!fs.existsSync(p)) { diff --git a/gui/src/components/AddModelButtonSubtext.tsx b/gui/src/components/AddModelButtonSubtext.tsx index 0ebb2ed9d..aa7ef99b5 100644 --- a/gui/src/components/AddModelButtonSubtext.tsx +++ b/gui/src/components/AddModelButtonSubtext.tsx @@ -12,7 +12,7 @@ function AddModelButtonSubtext() { className="cursor-pointer underline" onClick={() => ideMessenger.post("config/openProfile", { - profileId: "local", + profileId: undefined, }) } > diff --git a/gui/src/components/modelSelection/ModelSelect.tsx b/gui/src/components/modelSelection/ModelSelect.tsx index d99ced546..7cf854e4d 100644 --- a/gui/src/components/modelSelection/ModelSelect.tsx +++ b/gui/src/components/modelSelection/ModelSelect.tsx @@ -19,14 +19,10 @@ import { setDefaultModel, } from "../../redux/slices/configSlice"; import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice"; -import { - getFontSize, - getMetaKeyLabel, - isMetaEquivalentKeyPressed, -} from "../../util"; +import { getFontSize, isMetaEquivalentKeyPressed } from "../../util"; import ConfirmationDialog from "../dialogs/ConfirmationDialog"; +import Shortcut from "../gui/Shortcut"; import { Divider } from "./platform/shared"; -import Shortcut from '../gui/Shortcut'; interface ModelOptionProps { option: Option; @@ -166,9 +162,7 @@ function ModelOption({ e.stopPropagation(); e.preventDefault(); - ideMessenger.post("config/openProfile", { - profileId: "local", - }); + ideMessenger.post("config/openProfile", { profileId: undefined }); } function handleOptionClick(e: any) { @@ -351,7 +345,7 @@ function ModelSelect() {
- {selectedProfile?.id === "local" && ( + {selectedProfile?.profileType === "local" && ( <> { ideMessenger.post("config/openProfile", { - profileId: "local", + profileId: undefined, }); }} > diff --git a/gui/src/pages/config/index.tsx b/gui/src/pages/config/index.tsx index 79c81a221..f82443531 100644 --- a/gui/src/pages/config/index.tsx +++ b/gui/src/pages/config/index.tsx @@ -297,7 +297,7 @@ function ConfigPage() {
{selectedProfile && ( - {selectedProfile.id === "local" + {selectedProfile.profileType === "local" ? "Open Config File" : hubEnabled ? "Open Assistant" diff --git a/gui/src/util/index.ts b/gui/src/util/index.ts index eb5fc2324..2636a3b67 100644 --- a/gui/src/util/index.ts +++ b/gui/src/util/index.ts @@ -108,5 +108,5 @@ export function updatedObj(old: any, pathToValue: { [key: string]: any }) { } export function isLocalProfile(profile: ProfileDescription): boolean { - return profile.id === "local"; + return profile.profileType === "local"; } From 5dfc9110c6f22104a16920e19f82ce21b84c9d7f Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 8 Mar 2025 16:18:51 -0800 Subject: [PATCH 09/33] ignore .continue folder --- .continueignore | 3 ++- .gitignore | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/.continueignore b/.continueignore index 79e924012..50684c187 100644 --- a/.continueignore +++ b/.continueignore @@ -5,4 +5,5 @@ docs/docs/languages .vscode/ .archive/ **/*.scm -**/*.diff \ No newline at end of file +**/*.diff +.continue/ \ No newline at end of file diff --git a/.gitignore b/.gitignore index f331ec68c..94efa5983 100644 --- a/.gitignore +++ b/.gitignore @@ -168,4 +168,5 @@ extensions/.continue-debug/ *.vsix -.continuerules \ No newline at end of file +.continuerules +.continue/ \ No newline at end of file From 693540155b719e5059d838a0cc82fa487690fb43 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 8 Mar 2025 16:19:05 -0800 Subject: [PATCH 10/33] hot reload local assistants --- core/core.ts | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/core/core.ts b/core/core.ts index d5b0f6d8e..4861013bf 100644 --- a/core/core.ts +++ b/core/core.ts @@ -30,12 +30,7 @@ import { ChatDescriber } from "./util/chatDescriber"; import { clipboardCache } from "./util/clipboardCache"; import { GlobalContext } from "./util/GlobalContext"; import historyManager from "./util/history"; -import { - editConfigJson, - getConfigJsonPath, - migrateV1DevDataFiles, -} from "./util/paths"; -import { localPathToUri } from "./util/pathToUri"; +import { editConfigJson, migrateV1DevDataFiles } from "./util/paths"; import { Telemetry } from "./util/posthog"; import { getSymbolsForManyFiles } from "./util/treeSitter"; import { TTS } from "./util/tts"; @@ -860,7 +855,10 @@ export class Core { for (const uri of data.uris) { // Listen for file changes in the workspace // URI TODO is this equality statement valid? - if (URI.equal(uri, localPathToUri(getConfigJsonPath()))) { + const currentProfileUri = + this.configHandler.currentProfile?.profileDescription.uri ?? ""; + + if (URI.equal(uri, currentProfileUri)) { // Trigger a toast notification to provide UI feedback that config has been updated const showToast = this.globalContext.get("showConfigUpdateToast") ?? true; @@ -874,6 +872,8 @@ export class Core { this.globalContext.update("showConfigUpdateToast", false); } } + await this.configHandler.reloadConfig(); + continue; } if ( From 7e0b3d93870ad10ecb7f8f1e4092511af74fa7dc Mon Sep 17 00:00:00 2001 From: "Owen W. Taylor" Date: Sun, 9 Mar 2025 06:25:23 -0400 Subject: [PATCH 11/33] Fix logic for setting IGNORE_SSH_TESTS The logic for checking for dependabot introduced in fda4cc8096 skip ssh on dependabot PRs was somewhat confused; this was partially fixed in 98739c63ec fix ignore api key tests Make IGNORE_SSH_TESTS match. --- .github/workflows/pr_checks.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/pr_checks.yaml b/.github/workflows/pr_checks.yaml index da4d69970..6dbae92a6 100644 --- a/.github/workflows/pr_checks.yaml +++ b/.github/workflows/pr_checks.yaml @@ -460,7 +460,7 @@ jobs: - name: Run e2e tests run: | cd extensions/vscode - IGNORE_SSH_TESTS="${{ github.event.pull_request.head.repo.fork == false && github.actor != 'dependabot[bot]' }}" TEST_FILE="${{ matrix.test_file }}" npm run ${{ matrix.command }} + IGNORE_SSH_TESTS="${{ github.event.pull_request.head.repo.fork == true || github.actor == 'dependabot[bot]' }}" TEST_FILE="${{ matrix.test_file }}" npm run ${{ matrix.command }} env: DISPLAY: :99 From ba80343cabe080e6098eee39004f48b3725070d1 Mon Sep 17 00:00:00 2001 From: Daniel Barduhn Date: Sun, 9 Mar 2025 16:33:17 +0100 Subject: [PATCH 12/33] added tools support for fireworks.ai --- core/llm/llms/OpenAI.ts | 12 +++++++++++- core/llm/toolSupport.ts | 13 +++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/core/llm/llms/OpenAI.ts b/core/llm/llms/OpenAI.ts index 92f0aca08..139d033ab 100644 --- a/core/llm/llms/OpenAI.ts +++ b/core/llm/llms/OpenAI.ts @@ -97,6 +97,10 @@ class OpenAI extends BaseLLM { return !!model && (model.startsWith("o1") || model.startsWith("o3")); } + private isFireworksAiModel(model?: string): boolean { + return !!model && model.startsWith("accounts/fireworks/models"); + } + protected supportsPrediction(model: string): boolean { const SUPPORTED_MODELS = ["gpt-4o-mini", "gpt-4o", "mistral-large"]; return SUPPORTED_MODELS.some((m) => model.includes(m)); @@ -274,7 +278,13 @@ class OpenAI extends BaseLLM { body.max_completion_tokens = undefined; } - if (body.tools?.length && !body.model?.startsWith("o3")) { + if (body.tools?.length) { + if (this.isFireworksAiModel(body.model)) { + // fireworks.ai does not support parallel tool calls, but their api expects this to be true anyway otherwise they return an error. + // tooling works with them as a inference provider once this is set to true. + // https://docs.fireworks.ai/guides/function-calling#openai-compatibility + body.parallel_tool_calls = true; + } // To ensure schema adherence: https://platform.openai.com/docs/guides/function-calling#parallel-function-calling-and-structured-outputs // In practice, setting this to true and asking for multiple tool calls // leads to "arguments" being something like '{"file": "test.ts"}{"file": "test.js"}' diff --git a/core/llm/toolSupport.ts b/core/llm/toolSupport.ts index ebe6599f8..06994ec93 100644 --- a/core/llm/toolSupport.ts +++ b/core/llm/toolSupport.ts @@ -39,6 +39,19 @@ export const PROVIDER_TOOL_SUPPORT: Record< ) { return true; } + // firworks-ai https://docs.fireworks.ai/guides/function-calling + if (model.startsWith("accounts/fireworks/models/")) { + switch (model.substring(26)) { + case "llama-v3p1-405b-instruct": + case "llama-v3p1-70b-instruct": + case "qwen2p5-72b-instruct": + case "firefunction-v1": + case "firefunction-v2": + return true; + default: + return false; + } + } }, gemini: (model) => { // All gemini models support function calling From d7b30155c2b139a3c11c9c9db85c4be2d86c038c Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 9 Mar 2025 10:51:37 -0700 Subject: [PATCH 13/33] fix bug in codebase retrieval --- core/indexing/LanceDbIndex.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/core/indexing/LanceDbIndex.ts b/core/indexing/LanceDbIndex.ts index 168a4ff07..2b2f23a77 100644 --- a/core/indexing/LanceDbIndex.ts +++ b/core/indexing/LanceDbIndex.ts @@ -24,6 +24,7 @@ import { } from "./types"; import type * as LanceType from "vectordb"; +import { localPathToUri } from "../util/pathToUri"; interface LanceDbRow { uuid: string; @@ -498,7 +499,7 @@ export class LanceDbIndex implements CodebaseIndex { return data.map((d) => { return { digest: d.cacheKey, - filepath: d.path, + filepath: localPathToUri(d.path), startLine: d.startLine, endLine: d.endLine, index: 0, From 91426f233cbdbb04c9af894d8b3340031257df88 Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 9 Mar 2025 10:54:58 -0700 Subject: [PATCH 14/33] isolate errors in the different codebase retrieval steps --- .../pipelines/BaseRetrievalPipeline.ts | 27 ++++------ .../pipelines/NoRerankerRetrievalPipeline.ts | 46 ++++++++++++----- .../pipelines/RerankerRetrievalPipeline.ts | 51 ++++++++++++++----- 3 files changed, 81 insertions(+), 43 deletions(-) diff --git a/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts b/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts index d91931327..a3dcc0f7e 100644 --- a/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts +++ b/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts @@ -80,24 +80,19 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline { args: RetrievalPipelineRunArguments, n: number, ): Promise { - try { - if (args.query.trim() === "") { - return []; - } - - const tokensRaw = this.getCleanedTrigrams(args.query).join(" OR "); - const tokens = this.escapeFtsQueryString(tokensRaw); - - return await this.ftsIndex.retrieve({ - n, - text: tokens, - tags: args.tags, - directory: args.filterDirectory, - }); - } catch (e) { - console.warn("Error retrieving from FTS:", e); + if (args.query.trim() === "") { return []; } + + const tokensRaw = this.getCleanedTrigrams(args.query).join(" OR "); + const tokens = this.escapeFtsQueryString(tokensRaw); + + return await this.ftsIndex.retrieve({ + n, + text: tokens, + tags: args.tags, + directory: args.filterDirectory, + }); } protected async retrieveAndChunkRecentlyEditedFiles( diff --git a/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts b/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts index 889005414..f35809fed 100644 --- a/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts +++ b/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts @@ -19,22 +19,42 @@ export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline { let retrievalResults: Chunk[] = []; - const ftsChunks = await this.retrieveFts(args, ftsNFinal); + let ftsChunks: Chunk[] = []; + try { + ftsChunks = await this.retrieveFts(args, ftsNFinal); + } catch (error) { + console.error("Error retrieving FTS chunks:", error); + } - const embeddingsChunks = !!config.selectedModelByRole.embed - ? await this.retrieveEmbeddings(input, embeddingsNFinal) - : []; + let embeddingsChunks: Chunk[] = []; + try { + embeddingsChunks = !!config.selectedModelByRole.embed + ? await this.retrieveEmbeddings(input, embeddingsNFinal) + : []; + } catch (error) { + console.error("Error retrieving embeddings:", error); + } - const recentlyEditedFilesChunks = - await this.retrieveAndChunkRecentlyEditedFiles(recentlyEditedNFinal); + let recentlyEditedFilesChunks: Chunk[] = []; + try { + recentlyEditedFilesChunks = + await this.retrieveAndChunkRecentlyEditedFiles(recentlyEditedNFinal); + } catch (error) { + console.error("Error retrieving recently edited files:", error); + } - const repoMapChunks = await requestFilesFromRepoMap( - this.options.llm, - this.options.config, - this.options.ide, - input, - filterDirectory, - ); + let repoMapChunks: Chunk[] = []; + try { + repoMapChunks = await requestFilesFromRepoMap( + this.options.llm, + this.options.config, + this.options.ide, + input, + filterDirectory, + ); + } catch (error) { + console.error("Error retrieving repo map chunks:", error); + } retrievalResults.push( ...recentlyEditedFilesChunks, diff --git a/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts b/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts index 5fc4f240b..a3e4d830f 100644 --- a/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts +++ b/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts @@ -16,20 +16,42 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline { let retrievalResults: Chunk[] = []; - const ftsChunks = await this.retrieveFts(args, nRetrieve); - const embeddingsChunks = !!config.selectedModelByRole.embed - ? await this.retrieveEmbeddings(input, nRetrieve) - : []; - const recentlyEditedFilesChunks = - await this.retrieveAndChunkRecentlyEditedFiles(nRetrieve); + let ftsChunks: Chunk[] = []; + try { + ftsChunks = await this.retrieveFts(args, nRetrieve); + } catch (error) { + console.error("Error retrieving FTS chunks:", error); + } - const repoMapChunks = await requestFilesFromRepoMap( - this.options.llm, - this.options.config, - this.options.ide, - input, - filterDirectory, - ); + let embeddingsChunks: Chunk[] = []; + try { + embeddingsChunks = !!config.selectedModelByRole.embed + ? await this.retrieveEmbeddings(input, nRetrieve) + : []; + } catch (error) { + console.error("Error retrieving embeddings chunks:", error); + } + + let recentlyEditedFilesChunks: Chunk[] = []; + try { + recentlyEditedFilesChunks = + await this.retrieveAndChunkRecentlyEditedFiles(nRetrieve); + } catch (error) { + console.error("Error retrieving recently edited files chunks:", error); + } + + let repoMapChunks: Chunk[] = []; + try { + repoMapChunks = await requestFilesFromRepoMap( + this.options.llm, + this.options.config, + this.options.ide, + input, + filterDirectory, + ); + } catch (error) { + console.error("Error retrieving repo map chunks:", error); + } retrievalResults.push( ...recentlyEditedFilesChunks, @@ -41,7 +63,8 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline { if (filterDirectory) { // Backup if the individual retrieval methods don't listen retrievalResults = retrievalResults.filter( - (chunk) => !!findUriInDirs(chunk.filepath, [filterDirectory]).foundInDir, + (chunk) => + !!findUriInDirs(chunk.filepath, [filterDirectory]).foundInDir, ); } From 26d7eb4631b2b41f1b38c180cd4d6f376a8b52f0 Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 9 Mar 2025 11:57:14 -0700 Subject: [PATCH 15/33] anthropic tool call fix in openai-adapters --- packages/openai-adapters/package.json | 2 +- .../openai-adapters/src/apis/Anthropic.ts | 26 ++++++++ packages/openai-adapters/src/apis/Gemini.ts | 42 ++++++++++++- packages/openai-adapters/src/test/util.ts | 59 +++++++++++++++++++ packages/openai-adapters/src/types.ts | 1 + 5 files changed, 128 insertions(+), 2 deletions(-) diff --git a/packages/openai-adapters/package.json b/packages/openai-adapters/package.json index b2d293852..f11313bad 100644 --- a/packages/openai-adapters/package.json +++ b/packages/openai-adapters/package.json @@ -1,6 +1,6 @@ { "name": "@continuedev/openai-adapters", - "version": "1.0.15", + "version": "1.0.16", "description": "", "main": "dist/index.js", "types": "dist/index.d.ts", diff --git a/packages/openai-adapters/src/apis/Anthropic.ts b/packages/openai-adapters/src/apis/Anthropic.ts index d8c5b0c44..04b0fbce9 100644 --- a/packages/openai-adapters/src/apis/Anthropic.ts +++ b/packages/openai-adapters/src/apis/Anthropic.ts @@ -71,6 +71,32 @@ export class AnthropicApi implements BaseLlmApi { msgs: OpenAI.Chat.Completions.ChatCompletionMessageParam[], ): any[] { const messages = msgs.map((message) => { + if (message.role === "tool") { + return { + role: "user", + content: [ + { + type: "tool_result", + tool_use_id: message.tool_call_id, + content: + typeof message.content === "string" + ? message.content + : message.content.map((part) => part.text).join(""), + }, + ], + }; + } else if (message.role === "assistant" && message.tool_calls) { + return { + role: "assistant", + content: message.tool_calls.map((toolCall) => ({ + type: "tool_use", + id: toolCall.id, + name: toolCall.function?.name, + input: JSON.parse(toolCall.function?.arguments || "{}"), + })), + }; + } + if (!Array.isArray(message.content)) { return message; } diff --git a/packages/openai-adapters/src/apis/Gemini.ts b/packages/openai-adapters/src/apis/Gemini.ts index ae2235d25..c17527674 100644 --- a/packages/openai-adapters/src/apis/Gemini.ts +++ b/packages/openai-adapters/src/apis/Gemini.ts @@ -86,11 +86,50 @@ export class GeminiApi implements BaseLlmApi { } const isV1API = url.includes("/v1/"); + + const toolCallIdToNameMap = new Map(); const contents = oaiBody.messages .map((msg) => { if (msg.role === "system" && !isV1API) { return null; // Don't include system message in contents } + + if (msg.role == "assistant" && msg.tool_calls?.length) { + for (const toolCall of msg.tool_calls) { + toolCallIdToNameMap.set(toolCall.id, toolCall.function.name); + } + + return { + role: "model", + parts: msg.tool_calls.map((toolCall) => ({ + functionCall: { + name: toolCall.function.name, + args: JSON.parse(toolCall.function.arguments || "{}"), + }, + })), + }; + } + + if (msg.role === "tool") { + return { + role: "user", + parts: [ + { + functionResponse: { + name: msg.tool_call_id, + response: { + name: toolCallIdToNameMap.get(msg.tool_call_id), + content: + typeof msg.content === "string" + ? msg.content + : msg.content.map((part) => part.text).join(""), + }, + }, + }, + ], + }; + } + if (!msg.content) { return null; } @@ -246,9 +285,10 @@ export class GeminiApi implements BaseLlmApi { `models/${body.model}:streamGenerateContent?key=${this.config.apiKey}`, this.apiBase, ).toString(); + const convertedBody = this._convertBody(body, apiURL); const resp = await customFetch(this.config.requestOptions)(apiURL, { method: "POST", - body: JSON.stringify(this._convertBody(body, apiURL)), + body: JSON.stringify(convertedBody), signal, }); diff --git a/packages/openai-adapters/src/test/util.ts b/packages/openai-adapters/src/test/util.ts index 5b1b52ab1..ba4490f2a 100644 --- a/packages/openai-adapters/src/test/util.ts +++ b/packages/openai-adapters/src/test/util.ts @@ -260,6 +260,65 @@ export function testChat(api: BaseLlmApi, model: string) { const parsedArgs = JSON.parse(args); expect(parsedArgs.name).toBe("Nate"); }); + + test("Tool Call second message works", async () => { + let response = ""; + for await (const chunk of api.chatCompletionStream( + { + messages: [ + { + role: "user", + content: + "Hi, my name is Nate. Please call the say_hello function to respond to me, then respond to me again.", + }, + { + role: "assistant", + tool_calls: [ + { + function: { + arguments: '{"name":"Nate"}', + name: "say_hello", + }, + id: "tool_call_1", + type: "function", + }, + ], + }, + { + role: "tool", + tool_call_id: "tool_call_1", + content: "Nate was greeted", + }, + ], + tools: [ + { + function: { + name: "say_hello", + description: "Say Hello", + parameters: { + type: "object", + properties: { + name: { + type: "string", + description: "The name of the person to greet", + }, + }, + }, + }, + type: "function", + }, + ], + stream: true, + model, + }, + new AbortController().signal, + )) { + console.log(JSON.stringify(chunk, null, 2)); + response += chunk.choices[0].delta.content ?? ""; + } + + expect(response.length).toBeGreaterThan(0); + }); } export function testCompletion(api: BaseLlmApi, model: string) { diff --git a/packages/openai-adapters/src/types.ts b/packages/openai-adapters/src/types.ts index c59c8c8f7..30fd2cef0 100644 --- a/packages/openai-adapters/src/types.ts +++ b/packages/openai-adapters/src/types.ts @@ -54,6 +54,7 @@ export const OpenAIConfigSchema = BasePlusConfig.extend({ z.literal("vllm"), z.literal("x-ai"), z.literal("scaleway"), + z.literal("ncompass"), ]), }); export type OpenAIConfig = z.infer; From 21934981cd90594c5d75ce9cbada90d6b37115a0 Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 9 Mar 2025 18:10:15 -0700 Subject: [PATCH 16/33] only ignore assistants --- .gitignore | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 94efa5983..b24d52983 100644 --- a/.gitignore +++ b/.gitignore @@ -169,4 +169,4 @@ extensions/.continue-debug/ *.vsix .continuerules -.continue/ \ No newline at end of file +.continue/assistants/ \ No newline at end of file From 81511a10640aa5a5eca40a253e5fc8bff6b117cd Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 9 Mar 2025 18:13:31 -0700 Subject: [PATCH 17/33] fix uri bug --- core/config/getSystemPromptDotFile.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/core/config/getSystemPromptDotFile.ts b/core/config/getSystemPromptDotFile.ts index 1bfc6d1a1..de2c25db8 100644 --- a/core/config/getSystemPromptDotFile.ts +++ b/core/config/getSystemPromptDotFile.ts @@ -1,6 +1,7 @@ import { IDE } from ".."; import { walkDir } from "../indexing/walkDir"; import { getGlobalAssistantsPath } from "../util/paths"; +import { localPathToUri } from "../util/pathToUri"; import { joinPathsToUri } from "../util/uri"; export const SYSTEM_PROMPT_DOT_FILE = ".continuerules"; @@ -34,7 +35,7 @@ export async function getAssistantFilesFromDir( dir: string, ): Promise<{ path: string; content: string }[]> { try { - const exists = await ide.fileExists(dir); + const exists = await ide.fileExists(localPathToUri(dir)); if (!exists) { return []; From fc306c736374661f56fb73204f1149ffb05865a0 Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 9 Mar 2025 19:55:19 -0700 Subject: [PATCH 18/33] bump --- extensions/vscode/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index caa49d1dc..347351b00 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -2,7 +2,7 @@ "name": "continue", "icon": "media/icon.png", "author": "Continue Dev, Inc", - "version": "1.1.5", + "version": "1.1.6", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" From be0fc05f2bacb0bb0efe1182ea872978802a5b02 Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 9 Mar 2025 21:54:48 -0700 Subject: [PATCH 19/33] fix --- core/config/getSystemPromptDotFile.ts | 4 ++-- extensions/vscode/package.json | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/core/config/getSystemPromptDotFile.ts b/core/config/getSystemPromptDotFile.ts index de2c25db8..fa07b9cfd 100644 --- a/core/config/getSystemPromptDotFile.ts +++ b/core/config/getSystemPromptDotFile.ts @@ -35,7 +35,7 @@ export async function getAssistantFilesFromDir( dir: string, ): Promise<{ path: string; content: string }[]> { try { - const exists = await ide.fileExists(localPathToUri(dir)); + const exists = await ide.fileExists(dir); if (!exists) { return []; @@ -67,7 +67,7 @@ export async function getAllAssistantFiles( .map((dir) => dirsToCheck.map((d) => joinPathsToUri(dir, d))) .flat(); - fullDirs.push(getGlobalAssistantsPath()); + fullDirs.push(localPathToUri(getGlobalAssistantsPath())); assistantFiles = ( await Promise.all(fullDirs.map((dir) => getAssistantFilesFromDir(ide, dir))) diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 46ba6fa70..e313d1ddd 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -2,7 +2,7 @@ "name": "continue", "icon": "media/icon.png", "author": "Continue Dev, Inc", - "version": "1.1.6", + "version": "1.1.7", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" From f01c37feb3777e3939d7deb9a43abae4ba14c942 Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 9 Mar 2025 22:12:12 -0700 Subject: [PATCH 20/33] load local profiles when logged out --- core/config/ConfigHandler.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/core/config/ConfigHandler.ts b/core/config/ConfigHandler.ts index d50e63235..8f2c6ad4c 100644 --- a/core/config/ConfigHandler.ts +++ b/core/config/ConfigHandler.ts @@ -182,7 +182,8 @@ export class ConfigHandler { let profiles: ProfileLifecycleManager[] | null = null; if (!userId) { // Not logged in - profiles = [this.localProfileManager]; + const allLocalProfiles = await this.getAllLocalProfiles(); + profiles = [...allLocalProfiles]; } else { // Logged in const assistants = From f84eee6c0b2eb4cd7fab6bd87223563c4d0f3ec3 Mon Sep 17 00:00:00 2001 From: gyeongmin-ju Date: Mon, 10 Mar 2025 19:18:24 +0900 Subject: [PATCH 21/33] Issue #4474 bug fixed. Fixed the problem where log information was not transmitted even when registering an autocomplete event in the data section of config.json. Signed-off-by: Ju, Gyeongmin --- core/data/log.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/data/log.ts b/core/data/log.ts index 1b810d851..6af4738eb 100644 --- a/core/data/log.ts +++ b/core/data/log.ts @@ -47,7 +47,7 @@ export class DataLogger { newBody.eventName = eventName; } if ("timestamp" in zodSchema.shape) { - newBody.timestamp = new Date().toISOString(); + newBody.timestamp = Date.now(); } if ("schema" in zodSchema.shape) { newBody.schema = schema; From 561dcd931f207d10b5d1d38b5bcd90ac73063fd6 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 10 Mar 2025 13:29:13 -0700 Subject: [PATCH 22/33] catch rerank errors --- .../pipelines/RerankerRetrievalPipeline.ts | 49 ++++++++++--------- 1 file changed, 27 insertions(+), 22 deletions(-) diff --git a/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts b/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts index a3e4d830f..6e69a4078 100644 --- a/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts +++ b/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts @@ -82,29 +82,34 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline { // remove empty chunks -- some APIs fail on that chunks = chunks.filter((chunk) => chunk.content); - let scores: number[] = - await this.options.config.selectedModelByRole.rerank.rerank( - input, - chunks, + try { + let scores: number[] = + await this.options.config.selectedModelByRole.rerank.rerank( + input, + chunks, + ); + + // Filter out low-scoring results + let results = chunks; + // let results = chunks.filter( + // (_, i) => scores[i] >= RETRIEVAL_PARAMS.rerankThreshold, + // ); + // scores = scores.filter( + // (score) => score >= RETRIEVAL_PARAMS.rerankThreshold, + // ); + + const chunkIndexMap = new Map(); + chunks.forEach((chunk, idx) => chunkIndexMap.set(chunk, idx)); + + results.sort( + (a, b) => scores[chunkIndexMap.get(a)!] - scores[chunkIndexMap.get(b)!], ); - - // Filter out low-scoring results - let results = chunks; - // let results = chunks.filter( - // (_, i) => scores[i] >= RETRIEVAL_PARAMS.rerankThreshold, - // ); - // scores = scores.filter( - // (score) => score >= RETRIEVAL_PARAMS.rerankThreshold, - // ); - - const chunkIndexMap = new Map(); - chunks.forEach((chunk, idx) => chunkIndexMap.set(chunk, idx)); - - results.sort( - (a, b) => scores[chunkIndexMap.get(a)!] - scores[chunkIndexMap.get(b)!], - ); - results = results.slice(-this.options.nFinal); - return results; + results = results.slice(-this.options.nFinal); + return results; + } catch (e) { + console.warn(`Failed to rerank codebase retrieval results ${e}`); + return chunks; + } } private async _expandWithEmbeddings(chunks: Chunk[]): Promise { From c096a4fd32d04ea55114ad348b9e14a38e843b22 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 10 Mar 2025 13:40:23 -0700 Subject: [PATCH 23/33] ide warnings --- core/context/providers/DocsContextProvider.ts | 5 ++++- .../retrieval/pipelines/RerankerRetrievalPipeline.ts | 7 +++++-- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/core/context/providers/DocsContextProvider.ts b/core/context/providers/DocsContextProvider.ts index f4b816f33..3b9fa0cf4 100644 --- a/core/context/providers/DocsContextProvider.ts +++ b/core/context/providers/DocsContextProvider.ts @@ -5,6 +5,7 @@ import { ContextProviderDescription, ContextProviderExtras, ContextSubmenuItem, + IDE, LoadSubmenuItemsArgs, } from "../.."; import DocsService from "../../indexing/docs/DocsService"; @@ -36,6 +37,7 @@ class DocsContextProvider extends BaseContextProvider { chunks: Chunk[], reranker: NonNullable, fullInput: ContextProviderExtras["fullInput"], + ide: IDE, ) { let chunksCopy = [...chunks]; @@ -51,7 +53,7 @@ class DocsContextProvider extends BaseContextProvider { this.options?.nFinal ?? DocsContextProvider.nFinal, ); } catch (e) { - console.warn(`Failed to rerank docs results: ${e}`); + void ide.showToast("warning", `Failed to rerank retrieval results\n${e}`); chunksCopy = chunksCopy.splice( 0, @@ -116,6 +118,7 @@ class DocsContextProvider extends BaseContextProvider { chunks, extras.reranker, extras.fullInput, + extras.ide, ); } diff --git a/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts b/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts index 6e69a4078..e73edf118 100644 --- a/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts +++ b/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts @@ -107,8 +107,11 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline { results = results.slice(-this.options.nFinal); return results; } catch (e) { - console.warn(`Failed to rerank codebase retrieval results ${e}`); - return chunks; + void this.options.ide.showToast( + "warning", + `Failed to rerank retrieval results\n${e}`, + ); + return chunks.slice(-this.options.nFinal); } } From 3733d0d670aebae9f80a024f5480e47a4a114b9b Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 10 Mar 2025 15:45:01 -0700 Subject: [PATCH 24/33] bump config-yaml --- core/config/yaml/models.ts | 4 ++++ core/package-lock.json | 8 ++++---- core/package.json | 2 +- extensions/vscode/package-lock.json | 6 +++--- gui/package-lock.json | 2 +- 5 files changed, 13 insertions(+), 9 deletions(-) diff --git a/core/config/yaml/models.ts b/core/config/yaml/models.ts index b4392d519..f2270c429 100644 --- a/core/config/yaml/models.ts +++ b/core/config/yaml/models.ts @@ -49,6 +49,10 @@ async function modelConfigToBaseLLM( title: model.name, systemMessage, promptTemplates: model.promptTemplates, + capabilities: { + tools: model.capabilities?.includes("tool_use"), + uploadImage: model.capabilities?.includes("image_input"), + }, }; if (model.embedOptions?.maxBatchSize) { diff --git a/core/package-lock.json b/core/package-lock.json index a15d33faf..ec99105e1 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -13,7 +13,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.621.0", "@aws-sdk/credential-providers": "^3.620.1", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.52", + "@continuedev/config-yaml": "^1.0.56", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.2", "@continuedev/openai-adapters": "^1.0.10", @@ -3038,9 +3038,9 @@ } }, "node_modules/@continuedev/config-yaml": { - "version": "1.0.52", - "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.52.tgz", - "integrity": "sha512-x0m4bcQpjHrrv95cq5tsen4Hb6yKCVGn+NeojyzNQYnRD0If/On+ATgX78uXtQtZxsdO4ip73HHCyQlA0O3ZyQ==", + "version": "1.0.56", + "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.56.tgz", + "integrity": "sha512-2OBhmlSFOgZ+Z/ZQ18R/JR9zo6HIzkQ09PCuHQQ9NanN+g5AEVCdWgEtMyOq5DmQM3HLJCoLMXwqzQ9qSJEfFg==", "dependencies": { "@continuedev/config-types": "^1.0.14", "yaml": "^2.6.1", diff --git a/core/package.json b/core/package.json index a88bf0cf1..75c47caf6 100644 --- a/core/package.json +++ b/core/package.json @@ -46,7 +46,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.621.0", "@aws-sdk/credential-providers": "^3.620.1", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.52", + "@continuedev/config-yaml": "^1.0.56", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.2", "@continuedev/openai-adapters": "^1.0.10", diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 43750054e..5f7702aee 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "1.1.5", + "version": "1.1.7", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "1.1.5", + "version": "1.1.7", "license": "Apache-2.0", "dependencies": { "@continuedev/fetch": "^1.0.3", @@ -106,7 +106,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.621.0", "@aws-sdk/credential-providers": "^3.620.1", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.52", + "@continuedev/config-yaml": "^1.0.56", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.2", "@continuedev/openai-adapters": "^1.0.10", diff --git a/gui/package-lock.json b/gui/package-lock.json index 74273c5aa..20ade99a1 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -107,7 +107,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.621.0", "@aws-sdk/credential-providers": "^3.620.1", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.52", + "@continuedev/config-yaml": "^1.0.56", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.2", "@continuedev/openai-adapters": "^1.0.10", From f0cae280e481c493a8098039368e8c405d427675 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 10 Mar 2025 15:50:56 -0700 Subject: [PATCH 25/33] this.fetch additions --- core/llm/llms/HuggingFaceTEI.ts | 30 +++++++++------------ core/llm/llms/Voyage.ts | 2 +- core/llm/llms/stubs/ContinueProxy.ts | 2 +- packages/openai-adapters/src/apis/OpenAI.ts | 8 +++--- 4 files changed, 19 insertions(+), 23 deletions(-) diff --git a/core/llm/llms/HuggingFaceTEI.ts b/core/llm/llms/HuggingFaceTEI.ts index 206bbd5e2..52580c187 100644 --- a/core/llm/llms/HuggingFaceTEI.ts +++ b/core/llm/llms/HuggingFaceTEI.ts @@ -1,5 +1,4 @@ import { Chunk, LLMOptions } from "../../index.js"; -import { withExponentialBackoff } from "../../util/withExponentialBackoff.js"; import { BaseLLM } from "../index.js"; class HuggingFaceTEIEmbeddingsProvider extends BaseLLM { @@ -36,17 +35,15 @@ class HuggingFaceTEIEmbeddingsProvider extends BaseLLM { } async doEmbedRequest(batch: string[]): Promise { - const resp = await withExponentialBackoff(() => - this.fetch(new URL("embed", this.apiBase), { - method: "POST", - body: JSON.stringify({ - inputs: batch, - }), - headers: { - "Content-Type": "application/json", - }, + const resp = await this.fetch(new URL("embed", this.apiBase), { + method: "POST", + body: JSON.stringify({ + inputs: batch, }), - ); + headers: { + "Content-Type": "application/json", + }, + }); if (!resp.ok) { const text = await resp.text(); const embedError = JSON.parse(text) as TEIEmbedErrorResponse; @@ -59,11 +56,10 @@ class HuggingFaceTEIEmbeddingsProvider extends BaseLLM { } async doInfoRequest(): Promise { - const resp = await withExponentialBackoff(() => - this.fetch(new URL("info", this.apiBase), { - method: "GET", - }), - ); + // TODO - need to use custom fetch for this request? + const resp = await this.fetch(new URL("info", this.apiBase), { + method: "GET", + }); if (!resp.ok) { throw new Error(await resp.text()); } @@ -79,7 +75,7 @@ class HuggingFaceTEIEmbeddingsProvider extends BaseLLM { headers["Authorization"] = `Bearer ${this.apiKey}`; } - const resp = await fetch(new URL("rerank", this.apiBase), { + const resp = await this.fetch(new URL("rerank", this.apiBase), { method: "POST", headers, body: JSON.stringify({ diff --git a/core/llm/llms/Voyage.ts b/core/llm/llms/Voyage.ts index 27db04e17..fe08d8b1d 100644 --- a/core/llm/llms/Voyage.ts +++ b/core/llm/llms/Voyage.ts @@ -14,7 +14,7 @@ class Voyage extends OpenAI { return []; } const url = new URL("rerank", this.apiBase); - const resp = await fetch(url, { + const resp = await this.fetch(url, { method: "POST", headers: { "Content-Type": "application/json", diff --git a/core/llm/llms/stubs/ContinueProxy.ts b/core/llm/llms/stubs/ContinueProxy.ts index 00ec93dbc..94221ec1c 100644 --- a/core/llm/llms/stubs/ContinueProxy.ts +++ b/core/llm/llms/stubs/ContinueProxy.ts @@ -65,7 +65,7 @@ class ContinueProxy extends OpenAI { async rerank(query: string, chunks: Chunk[]): Promise { const url = new URL("rerank", this.apiBase); - const resp = await fetch(url, { + const resp = await this.fetch(url, { method: "POST", headers: { "Content-Type": "application/json", diff --git a/packages/openai-adapters/src/apis/OpenAI.ts b/packages/openai-adapters/src/apis/OpenAI.ts index aa059f7db..358f52dca 100644 --- a/packages/openai-adapters/src/apis/OpenAI.ts +++ b/packages/openai-adapters/src/apis/OpenAI.ts @@ -14,7 +14,7 @@ import { } from "openai/resources/index"; import { z } from "zod"; import { OpenAIConfigSchema } from "../types.js"; -import { maybeCustomFetch } from "../util.js"; +import { customFetch, maybeCustomFetch } from "../util.js"; import { BaseLlmApi, CreateRerankResponse, @@ -31,7 +31,7 @@ export class OpenAIApi implements BaseLlmApi { this.openai = new OpenAI({ apiKey: config.apiKey, baseURL: this.apiBase, - fetch: maybeCustomFetch(config.requestOptions), + fetch: customFetch(config.requestOptions), }); } @@ -100,7 +100,7 @@ export class OpenAIApi implements BaseLlmApi { signal: AbortSignal, ): AsyncGenerator { const endpoint = new URL("fim/completions", this.apiBase); - const resp = await fetch(endpoint, { + const resp = await customFetch(this.config.requestOptions)(endpoint, { method: "POST", body: JSON.stringify({ model: body.model, @@ -139,7 +139,7 @@ export class OpenAIApi implements BaseLlmApi { async rerank(body: RerankCreateParams): Promise { const endpoint = new URL("rerank", this.apiBase); - const response = await fetch(endpoint, { + const response = await customFetch(this.config.requestOptions)(endpoint, { method: "POST", body: JSON.stringify(body), headers: { From 9d2a873abce95d4fa9b11bd567c245ee3429e093 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 10 Mar 2025 16:03:03 -0700 Subject: [PATCH 26/33] cohere --- core/llm/llms/Cohere.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/llm/llms/Cohere.ts b/core/llm/llms/Cohere.ts index 1c895c2fe..86834cb74 100644 --- a/core/llm/llms/Cohere.ts +++ b/core/llm/llms/Cohere.ts @@ -117,7 +117,7 @@ class Cohere extends BaseLLM { } async rerank(query: string, chunks: Chunk[]): Promise { - const resp = await fetch(new URL("rerank", this.apiBase), { + const resp = await this.fetch(new URL("rerank", this.apiBase), { method: "POST", headers: { Authorization: `Bearer ${this.apiKey}`, From af36d82f418527d090439812825c38a3baf1e5a9 Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 10 Mar 2025 17:06:59 -0700 Subject: [PATCH 27/33] localPathToUri don't convert if already converted --- core/util/pathToUri.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/core/util/pathToUri.ts b/core/util/pathToUri.ts index 67a249d74..36c2bc35f 100644 --- a/core/util/pathToUri.ts +++ b/core/util/pathToUri.ts @@ -6,6 +6,10 @@ import * as URI from "uri-js"; // Converts a local path to a file:/// URI export function localPathToUri(path: string) { + if (path.startsWith("file://")) { + console.warn("localPathToUri: path already starts with file://"); + return path; + } const url = pathToFileURL(path); return URI.normalize(url.toString()); } From 71f0f0fb04d34fb2339673a73d5d808fb2227a3a Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 10 Mar 2025 17:07:20 -0700 Subject: [PATCH 28/33] localPathToUri-related at-codebase fixes --- core/context/retrieval/repoMapRequest.ts | 8 +++++--- core/indexing/LanceDbIndex.ts | 3 +-- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/core/context/retrieval/repoMapRequest.ts b/core/context/retrieval/repoMapRequest.ts index 5637019ad..5a4f9be2a 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 { localPathToUri } from "../../util/pathToUri"; const SUPPORTED_MODEL_TITLE_FAMILIES = [ "claude-3", @@ -72,7 +73,7 @@ This is the question that you should select relevant files for: "${input}"`; return []; } - const fileUris = content + const filepaths = content .split("")[1] ?.split("")[0] ?.split("\n") @@ -80,8 +81,9 @@ This is the question that you should select relevant files for: "${input}"`; .map((uri) => uri.trim()); const chunks = await Promise.all( - fileUris.map(async (uri) => { - const content = await ide.readFile(uri); + filepaths.map(async (filepath) => { + const uri = localPathToUri(filepath); + const content = await ide.readFile(filepath); const lineCount = content.split("\n").length; const chunk: Chunk = { digest: uri, diff --git a/core/indexing/LanceDbIndex.ts b/core/indexing/LanceDbIndex.ts index 2b2f23a77..168a4ff07 100644 --- a/core/indexing/LanceDbIndex.ts +++ b/core/indexing/LanceDbIndex.ts @@ -24,7 +24,6 @@ import { } from "./types"; import type * as LanceType from "vectordb"; -import { localPathToUri } from "../util/pathToUri"; interface LanceDbRow { uuid: string; @@ -499,7 +498,7 @@ export class LanceDbIndex implements CodebaseIndex { return data.map((d) => { return { digest: d.cacheKey, - filepath: localPathToUri(d.path), + filepath: d.path, startLine: d.startLine, endLine: d.endLine, index: 0, From 4b227f1d3f5a75398700b5445f975dab88d0e19b Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 10 Mar 2025 17:07:27 -0700 Subject: [PATCH 29/33] fix reranker through continue-proxy --- core/llm/llms/stubs/ContinueProxy.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/core/llm/llms/stubs/ContinueProxy.ts b/core/llm/llms/stubs/ContinueProxy.ts index 00ec93dbc..4dd8976b2 100644 --- a/core/llm/llms/stubs/ContinueProxy.ts +++ b/core/llm/llms/stubs/ContinueProxy.ts @@ -75,6 +75,7 @@ class ContinueProxy extends OpenAI { query, documents: chunks.map((chunk) => chunk.content), model: this.model, + ...this.extraBodyProperties(), }), }); const data: any = await resp.json(); From a31f0d6a48a730ea263a160fb973b6b9091d806f Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 10 Mar 2025 17:07:41 -0700 Subject: [PATCH 30/33] bump version --- extensions/vscode/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index e313d1ddd..942724cda 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -2,7 +2,7 @@ "name": "continue", "icon": "media/icon.png", "author": "Continue Dev, Inc", - "version": "1.1.7", + "version": "1.1.8", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" From c819cbf81f9b75191ad0c0bdcbbe3a154167ef98 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 10 Mar 2025 17:13:25 -0700 Subject: [PATCH 31/33] .local env --- core/control-plane/env.ts | 10 +++++++++- core/util/paths.ts | 4 ++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/core/control-plane/env.ts b/core/control-plane/env.ts index 8995dca7e..7d3ae9eb0 100644 --- a/core/control-plane/env.ts +++ b/core/control-plane/env.ts @@ -1,6 +1,9 @@ import * as fs from "node:fs"; import { IdeSettings } from ".."; -import { getStagingEnvironmentDotFilePath } from "../util/paths"; +import { + getLocalEnvironmentDotFilePath, + getStagingEnvironmentDotFilePath, +} from "../util/paths"; export interface ControlPlaneEnv { DEFAULT_CONTROL_PLANE_PROXY_URL: string; @@ -78,6 +81,11 @@ export function getControlPlaneEnvSync( ideTestEnvironment: IdeSettings["continueTestEnvironment"], enableControlServerBeta: IdeSettings["enableControlServerBeta"], ): ControlPlaneEnv { + // Note .local overrides .staging + if (fs.existsSync(getLocalEnvironmentDotFilePath())) { + return LOCAL_ENV; + } + if (fs.existsSync(getStagingEnvironmentDotFilePath())) { return STAGING_ENV; } diff --git a/core/util/paths.ts b/core/util/paths.ts index 02d2f43b5..3bc2ee3cf 100644 --- a/core/util/paths.ts +++ b/core/util/paths.ts @@ -418,6 +418,10 @@ export function migrateV1DevDataFiles() { moveToV1FolderIfExists("autocomplete", "autocomplete"); } +export function getLocalEnvironmentDotFilePath(): string { + return path.join(getContinueGlobalPath(), ".local"); +} + export function getStagingEnvironmentDotFilePath(): string { return path.join(getContinueGlobalPath(), ".staging"); } From cfc99b7e57a9ce1a73872a9056d65f0b4a8d174b Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 10 Mar 2025 20:41:40 -0700 Subject: [PATCH 32/33] remove legacy server cache logic --- core/indexing/CodebaseIndexer.ts | 1 - core/indexing/LanceDbIndex.test.ts | 2 - core/indexing/LanceDbIndex.ts | 63 +----------------------------- 3 files changed, 1 insertion(+), 65 deletions(-) diff --git a/core/indexing/CodebaseIndexer.ts b/core/indexing/CodebaseIndexer.ts index d59f0ded8..03fb23897 100644 --- a/core/indexing/CodebaseIndexer.ts +++ b/core/indexing/CodebaseIndexer.ts @@ -97,7 +97,6 @@ export class CodebaseIndexer { const lanceDbIndex = await LanceDbIndex.create( embeddingsModel, this.ide.readFile.bind(this.ide), - this.continueServerClient, ); if (lanceDbIndex) { diff --git a/core/indexing/LanceDbIndex.test.ts b/core/indexing/LanceDbIndex.test.ts index ac6ed3591..ad28b3456 100644 --- a/core/indexing/LanceDbIndex.test.ts +++ b/core/indexing/LanceDbIndex.test.ts @@ -9,7 +9,6 @@ import { DatabaseConnection, SqliteDb } from "./refreshIndex"; import { mockPathAndCacheKey, mockTag, - testContinueServerClient, updateIndexAndAwaitGenerator, } from "./test/indexing"; import { IndexResultType } from "./types"; @@ -37,7 +36,6 @@ describe.skip("ChunkCodebaseIndex", () => { index = (await LanceDbIndex.create( mockConfig.selectedModelByRole.embed, testIde.readFile.bind(testIde), - testContinueServerClient, ))!; sqliteDb = await SqliteDb.get(); diff --git a/core/indexing/LanceDbIndex.ts b/core/indexing/LanceDbIndex.ts index 168a4ff07..3f9630eb1 100644 --- a/core/indexing/LanceDbIndex.ts +++ b/core/indexing/LanceDbIndex.ts @@ -2,7 +2,6 @@ import { RunResult } from "sqlite3"; import { v4 as uuidv4 } from "uuid"; import { isSupportedLanceDbCpuTargetForLinux } from "../config/util"; -import { IContinueServerClient } from "../continueServer/interface"; import { BranchAndDir, Chunk, @@ -57,7 +56,6 @@ export class LanceDbIndex implements CodebaseIndex { static async create( embeddingsProvider: ILLM, readFile: (filepath: string) => Promise, - continueServerClient?: IContinueServerClient, ): Promise { if (!isSupportedLanceDbCpuTargetForLinux()) { return null; @@ -65,11 +63,7 @@ export class LanceDbIndex implements CodebaseIndex { try { this.lance = await import("vectordb"); - return new LanceDbIndex( - embeddingsProvider, - readFile, - continueServerClient, - ); + return new LanceDbIndex(embeddingsProvider, readFile); } catch (err) { console.error("Failed to load LanceDB:", err); return null; @@ -79,7 +73,6 @@ export class LanceDbIndex implements CodebaseIndex { private constructor( private readonly embeddingsProvider: ILLM, private readonly readFile: (filepath: string) => Promise, - private readonly continueServerClient?: IContinueServerClient, ) { if (!LanceDbIndex.lance) { throw new Error("LanceDB not initialized"); @@ -278,60 +271,6 @@ export class LanceDbIndex implements CodebaseIndex { await markComplete(pathAndCacheKeys, IndexResultType.Compute); }; - if (this.continueServerClient?.connected) { - try { - const keys = results.compute.map(({ cacheKey }) => cacheKey); - const resp = await this.continueServerClient.getFromIndexCache( - keys, - "embeddings", - repoName, - ); - for (const [cacheKey, chunks] of Object.entries(resp.files)) { - const path = results.compute.find( - (item) => item.cacheKey === cacheKey, - )?.path; - if (!path) { - console.warn( - "Continue server sent a cacheKey that wasn't requested", - cacheKey, - ); - continue; - } - - const rows: LanceDbRow[] = []; - for (const chunk of chunks) { - const row = { - path, - cachekey: cacheKey, - uuid: uuidv4(), - vector: chunk.vector, - }; - rows.push(row); - - await sqliteDb.run( - "INSERT INTO lance_db_cache (uuid, cacheKey, path, artifact_id, vector, startLine, endLine, contents) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", - row.uuid, - row.cachekey, - row.path, - this.artifactId, - JSON.stringify(row.vector), - chunk.startLine, - chunk.endLine, - chunk.contents, - ); - } - - await addComputedLanceDbRows([{ cacheKey, path }], rows); - } - - results.compute = results.compute.filter( - (item) => !resp.files[item.cacheKey], - ); - } catch (e) { - console.log("Error checking remote cache: ", e); - } - } - yield { progress: 0, desc: `Computing embeddings for ${ From ec092ca498a4576deedfde203145f06ddbc9206f Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 10 Mar 2025 21:25:04 -0700 Subject: [PATCH 33/33] use relative paths and fix URI resolution in codebase repo map retrieval --- core/context/retrieval/repoMapRequest.ts | 15 +++++++++------ core/util/pathToUri.ts | 1 + 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/core/context/retrieval/repoMapRequest.ts b/core/context/retrieval/repoMapRequest.ts index 5a4f9be2a..ee0d5aaf7 100644 --- a/core/context/retrieval/repoMapRequest.ts +++ b/core/context/retrieval/repoMapRequest.ts @@ -1,8 +1,8 @@ import { Chunk, ContinueConfig, IDE, ILLM } from "../.."; import { getModelByRole } from "../../config/util"; import generateRepoMap from "../../util/generateRepoMap"; +import { resolveRelativePathInDir } from "../../util/ideUtils"; import { renderChatMessage } from "../../util/messageContent"; -import { localPathToUri } from "../../util/pathToUri"; const SUPPORTED_MODEL_TITLE_FAMILIES = [ "claude-3", @@ -49,14 +49,14 @@ export async function requestFilesFromRepoMap( const repoMap = await generateRepoMap(llm, ide, { dirUris: filterDirUri ? [filterDirUri] : undefined, includeSignatures: false, - outputRelativeUriPaths: false, + outputRelativeUriPaths: true, }); const prompt = `${repoMap} Given the above repo map, your task is to decide which files are most likely to be relevant in answering a question. Before giving your answer, you should write your reasoning about which files/folders are most important. This thinking should start with a tag, followed by a paragraph explaining your reasoning, and then a closing tag on the last line. -After this, your response should begin with a tag, followed by a list of each file, one per line, and then a closing tag on the last line. You should select between 5 and 10 files. The names that you list should be the full path from the root of the repo, not just the basename of the file. +After this, your response should begin with a tag, followed by a list of each file, one per line, and then a closing tag on the last line. You should select between 5 and 10 files. The names that you list should be the exact relative path that you saw in the repo map, not just the basename of the file. This is the question that you should select relevant files for: "${input}"`; @@ -78,11 +78,14 @@ This is the question that you should select relevant files for: "${input}"`; ?.split("")[0] ?.split("\n") .filter(Boolean) - .map((uri) => uri.trim()); + .map((filepath) => filepath.trim()); const chunks = await Promise.all( filepaths.map(async (filepath) => { - const uri = localPathToUri(filepath); + const uri = await resolveRelativePathInDir(filepath, ide); + if (!uri) { + return undefined; + } const content = await ide.readFile(filepath); const lineCount = content.split("\n").length; const chunk: Chunk = { @@ -97,7 +100,7 @@ This is the question that you should select relevant files for: "${input}"`; }), ); - return chunks; + return chunks.filter((c) => c !== undefined) as Chunk[]; } catch (e) { console.debug("Error requesting files from repo map", e); return []; diff --git a/core/util/pathToUri.ts b/core/util/pathToUri.ts index 36c2bc35f..ce83563fd 100644 --- a/core/util/pathToUri.ts +++ b/core/util/pathToUri.ts @@ -6,6 +6,7 @@ import * as URI from "uri-js"; // Converts a local path to a file:/// URI export function localPathToUri(path: string) { + // This may incidentally solve bugs, but it is primarily here to warn us if we accidentally try to double-convert. It doesn't handle other URI schemes. if (path.startsWith("file://")) { console.warn("localPathToUri: path already starts with file://"); return path;