diff --git a/.changes/extensions/intellij/0.0.69.md b/.changes/extensions/intellij/0.0.69.md new file mode 100644 index 000000000..a4b67ca0c --- /dev/null +++ b/.changes/extensions/intellij/0.0.69.md @@ -0,0 +1,7 @@ +## 0.0.69 - 2024-09-22 +### Added +* Support for the "search" context provider +### Fixed +* Fixed bug where only first module would be recognized +* Improved concurrency handling to avoid freezes +* Made compatible with latest JetBrains versions diff --git a/.changes/extensions/vscode/0.9.210.md b/.changes/extensions/vscode/0.9.210.md new file mode 100644 index 000000000..8e255dc2e --- /dev/null +++ b/.changes/extensions/vscode/0.9.210.md @@ -0,0 +1,15 @@ +## 0.9.210 - 2024-09-15 + +### Added + +- NVIDIA NIMs embeddings provider +- SambaNova LLM Provider +- Support for OpenAI's new o1-preview and o1-mini models + +### Changed + +- Use Chromium only as a fallback after asking user + +### Fixed + +- Increased default maxTokens, and autodetect for common models diff --git a/.changes/unreleased/Added-20240927-142940.yaml b/.changes/unreleased/Added-20240927-142940.yaml new file mode 100644 index 000000000..3a2785783 --- /dev/null +++ b/.changes/unreleased/Added-20240927-142940.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Added +body: Improved loading/accept/reject UI for apply +time: 2024-09-27T14:29:40.283176-07:00 diff --git a/.changes/unreleased/Added-20240927-143005.yaml b/.changes/unreleased/Added-20240927-143005.yaml new file mode 100644 index 000000000..4dafa06cb --- /dev/null +++ b/.changes/unreleased/Added-20240927-143005.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Added +body: Polished chat sidebar, especially context dropdown +time: 2024-09-27T14:30:05.576347-07:00 diff --git a/.changes/unreleased/Added-20240929-095627.yaml b/.changes/unreleased/Added-20240929-095627.yaml new file mode 100644 index 000000000..ec21be676 --- /dev/null +++ b/.changes/unreleased/Added-20240929-095627.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Added +body: Further prompt caching with Anthropic +time: 2024-09-29T09:56:27.946259-07:00 diff --git a/.changes/unreleased/Changed-20240923-160251.yaml b/.changes/unreleased/Changed-20240923-160251.yaml new file mode 100644 index 000000000..5cef25bab --- /dev/null +++ b/.changes/unreleased/Changed-20240923-160251.yaml @@ -0,0 +1,4 @@ +project: extensions/intellij +kind: Changed +body: Updated tutorial file +time: 2024-09-23T16:02:51.918152-07:00 diff --git a/.changes/unreleased/Changed-20240923-160302.yaml b/.changes/unreleased/Changed-20240923-160302.yaml new file mode 100644 index 000000000..55cb8a77a --- /dev/null +++ b/.changes/unreleased/Changed-20240923-160302.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Changed +body: Updated tutorial file +time: 2024-09-23T16:03:02.944462-07:00 diff --git a/.changes/unreleased/Changed-20240929-095407.yaml b/.changes/unreleased/Changed-20240929-095407.yaml new file mode 100644 index 000000000..e6f87aac6 --- /dev/null +++ b/.changes/unreleased/Changed-20240929-095407.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Changed +body: Improved styling on "More" page +time: 2024-09-29T09:54:07.999324-07:00 diff --git a/.changes/unreleased/Fixed-20240919-211112.yaml b/.changes/unreleased/Fixed-20240919-211112.yaml new file mode 100644 index 000000000..5109006f8 --- /dev/null +++ b/.changes/unreleased/Fixed-20240919-211112.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Fixed +body: Continue for teams auth bug fix +time: 2024-09-19T21:11:12.997946-07:00 diff --git a/.changes/unreleased/Fixed-20240927-142924.yaml b/.changes/unreleased/Fixed-20240927-142924.yaml new file mode 100644 index 000000000..9a799ee51 --- /dev/null +++ b/.changes/unreleased/Fixed-20240927-142924.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Fixed +body: Fixed a number of apply bugs +time: 2024-09-27T14:29:24.69568-07:00 diff --git a/.changes/unreleased/Fixed-20240929-095440.yaml b/.changes/unreleased/Fixed-20240929-095440.yaml new file mode 100644 index 000000000..d31fac222 --- /dev/null +++ b/.changes/unreleased/Fixed-20240929-095440.yaml @@ -0,0 +1,4 @@ +project: extensions/intellij +kind: Fixed +body: Fix ability to load config.ts in JetBrains IDEs +time: 2024-09-29T09:54:40.284968-07:00 diff --git a/.changes/unreleased/Fixed-20240929-095525.yaml b/.changes/unreleased/Fixed-20240929-095525.yaml new file mode 100644 index 000000000..2774af39d --- /dev/null +++ b/.changes/unreleased/Fixed-20240929-095525.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Fixed +body: Fixed autoscrolling behavior +time: 2024-09-29T09:55:25.835696-07:00 diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index 348fe493d..93c04fe38 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -23,16 +23,15 @@ body: description: | Feel free to omit any info that is not relevant to your issue. - - **OS**: e.g. macOS 14.2.1 - - **Continue**: e.g. v0.9.4 - - **IDE**: e.g. VSCode 1.85.1 - - Include also your LLM Model if it is relevant to your issue - - **Model**: e.g. Ollama v0.1.19 - - The contents of your config.json file (e.g. `~/.continue/config.json` on macOS) + - **OS**: macOS + - **Continue version**: v0.9.4 + - **IDE version**: VSCode 1.85.1 + - Model: Claude Sonnet 3.5 + - config.json: `{ "models": ... }` value: | - OS: - - Continue: - - IDE: + - Continue version: + - IDE version: - Model: - config.json: ```json diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index e4400f20b..cf3cc4ae1 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -203,6 +203,7 @@ jobs: ls echo "---" FILENAME=`ls continue-intellij-extension-*.zip` + echo "Filename=${FILENAME}" unzip "$FILENAME" -d content echo "filename=${FILENAME%.????}" >> $GITHUB_OUTPUT @@ -330,10 +331,10 @@ jobs: - name: Upload logs if: ${{ always() }} - uses: actions/upload-artifact@v2 + uses: actions/upload-artifact@v4 with: name: core-logs-${{ matrix.platform }}-${{ matrix.arch }} - path: binary/.continue/logs/core.log + path: ~/.continue/logs/core.log # Run tests and upload a code coverage report test: diff --git a/.gitignore b/.gitignore index 5f242c5ef..ba5199b56 100644 --- a/.gitignore +++ b/.gitignore @@ -169,4 +169,4 @@ Icon? .prompts/ .aider* -notes.md \ No newline at end of file +notes.md diff --git a/.prettierignore b/.prettierignore index fcb08552d..db326191f 100644 --- a/.prettierignore +++ b/.prettierignore @@ -1,3 +1,4 @@ extensions/vscode/continue_rc_schema.json **/.continueignore -CHANGELOG.md \ No newline at end of file +CHANGELOG.md +**/continue_tutorial.py diff --git a/.prompts/test.prompt b/.prompts/test.prompt new file mode 100644 index 000000000..e2f5d8662 --- /dev/null +++ b/.prompts/test.prompt @@ -0,0 +1,19 @@ +temperature: 0.5 +maxTokens: 4096 +name: jest +description: Write Jest unit tests +--- + +You are an expert programmer + + +{{{ input }}} + +Write unit tests for the above selected code, following each of these instructions: +- Use `jest` +- Properly set up and tear down +- Include important edge cases +- The tests should be complete and sophisticated +- Give the tests just as chat output, don't edit any file +- Don't explain how to set up `jest` +- Write a single code block, making sure to label with the language being used (e.g. "```typscript") \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 9fad5eb06..c070f0bc1 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -68,12 +68,18 @@ You can run the documentation server locally using either of the following metho #### Method 1: NPM Script -1. Open your terminal and navigate to the root directory of the project. +1. Open your terminal and navigate to the `docs` subdirectory of the project. The `docusaurus.config.js` file you'll see there is a sign you're in the right place. -2. Run the following command to start the documentation server: +2. Run the following command to install the necessary dependencies for the documentation server: ```bash - npm run start --prefix docs + npm install + ``` + +3. Run the following command to start the documentation server: + + ```bash + npm run start ``` #### Method 2: VS Code Task @@ -211,9 +217,9 @@ Continue has support for more than a dozen different LLM "providers", making it - At least one of `_streamComplete` or `_streamChat` - This is the function that makes the request to the API and returns the streamed response. You only need to implement one because Continue can automatically convert between "chat" and "raw completion". 2. Add your provider to the `LLMs` array in [core/llm/llms/index.ts](./core/llm/llms/index.ts). -3. If your provider supports images, add it to the `PROVIDER_SUPPORTS_IMAGES` array in [core/llm/index.ts](./core/llm/index.ts). +3. If your provider supports images, add it to the `PROVIDER_SUPPORTS_IMAGES` array in [core/llm/autodetect.ts](./core/llm/autodetect.ts). 4. Add the necessary JSON Schema types to [`config_schema.json`](./extensions/vscode/config_schema.json). This makes sure that Intellisense shows users what options are available for your provider when they are editing `config.json`. -5. Add a documentation page for your provider in [`docs/docs/reference/Model Providers`](./docs/docs/reference/Model%20Providers). This should show an example of configuring your provider in `config.json` and explain what options are available. +5. Add a documentation page for your provider in [`docs/docs/customize/model-providers`](./docs/docs/customize/model-providers). This should show an example of configuring your provider in `config.json` and explain what options are available. ### Adding Models diff --git a/binary/package-lock.json b/binary/package-lock.json index 7ed2f9aea..5f1410c1a 100644 --- a/binary/package-lock.json +++ b/binary/package-lock.json @@ -48,7 +48,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.621.0", "@aws-sdk/credential-providers": "^3.620.1", "@continuedev/config-types": "^1.0.10", - "@continuedev/llm-info": "^1.0.1", + "@continuedev/llm-info": "^1.0.2", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.0.2", "@typescript-eslint/eslint-plugin": "^7.8.0", @@ -60,7 +60,8 @@ "cheerio": "^1.0.0-rc.12", "commander": "^12.0.0", "comment-json": "^4.2.3", - "dbinfoz": "^0.1.4", + "dbinfoz": "^0.11.0", + "diff": "^7.0.0", "dotenv": "^16.4.5", "fastest-levenshtein": "^1.0.16", "follow-redirects": "^1.15.5", @@ -104,6 +105,7 @@ "@babel/preset-env": "^7.24.7", "@biomejs/biome": "1.6.4", "@google/generative-ai": "^0.11.4", + "@types/diff": "^5.2.2", "@types/follow-redirects": "^1.14.4", "@types/jest": "^29.5.12", "@types/jquery": "^3.5.29", diff --git a/binary/test/binary.test.ts b/binary/test/binary.test.ts index 747b7d6f9..3554aed27 100644 --- a/binary/test/binary.test.ts +++ b/binary/test/binary.test.ts @@ -5,7 +5,11 @@ import FileSystemIde from "core/util/filesystem"; import { IMessenger } from "core/util/messenger"; import { ReverseMessageIde } from "core/util/reverseMessageIde"; import fs from "fs"; -import { ChildProcessWithoutNullStreams, spawn } from "node:child_process"; +import { + ChildProcessWithoutNullStreams, + execSync, + spawn, +} from "node:child_process"; import path from "path"; import { CoreBinaryMessenger, @@ -59,21 +63,66 @@ describe("Test Suite", () => { beforeAll(async () => { const [platform, arch] = autodetectPlatformAndArch(); - const binaryPath = path.join( - __dirname, - "..", - "bin", - `${platform}-${arch}`, - `continue-binary${platform === "win32" ? ".exe" : ""}`, - ); - expect(fs.existsSync(binaryPath)).toBe(true); + const binaryDir = path.join(__dirname, "..", "bin", `${platform}-${arch}`); + const exe = platform === "win32" ? ".exe" : ""; + const binaryPath = path.join(binaryDir, `continue-binary${exe}`); + const expectedItems = [ + `continue-binary${exe}`, + `esbuild${exe}`, + "index.node", + "package.json", + "build/Release/node_sqlite3.node", + ]; + expectedItems.forEach((item) => { + expect(fs.existsSync(path.join(binaryDir, item))).toBe(true); + }); + + // Set execute permissions and remove quarantine attribute if on macOS + if (platform !== "win32") { + try { + fs.chmodSync(binaryPath, 0o755); + console.log("Execute permissions set for the binary"); + + if (platform === "darwin") { + const indexNodePath = path.join(binaryDir, "index.node"); + const filesToUnquarantine = [binaryPath, indexNodePath]; + + for (const file of filesToUnquarantine) { + try { + execSync(`xattr -d com.apple.quarantine "${file}"`, { + stdio: "ignore", + }); + console.log( + `Quarantine attribute removed from ${path.basename(file)}`, + ); + } catch (error) { + console.warn( + `Failed to remove quarantine attribute from ${path.basename(file)}:`, + error, + ); + } + } + } + } catch (error) { + console.error( + "Error setting permissions or removing quarantine:", + error, + ); + } + } if (USE_TCP) { messenger = new CoreBinaryTcpMessenger(); } else { - subprocess = spawn(binaryPath, { - env: { ...process.env, CONTINUE_GLOBAL_DIR }, - }); + try { + subprocess = spawn(binaryPath, { + env: { ...process.env, CONTINUE_GLOBAL_DIR }, + }); + console.log("Successfully spawned subprocess"); + } catch (error) { + console.error("Error spawning subprocess:", error); + throw error; + } messenger = new CoreBinaryMessenger( subprocess, ); @@ -123,13 +172,17 @@ describe("Test Suite", () => { "package.json", "logs/core.log", "index/autocompleteCache.sqlite", - "out/config.js", "types/core/index.d.ts", ]; - for (const file of expectedFiles) { + const missingFiles = expectedFiles.filter((file) => { const filePath = path.join(CONTINUE_GLOBAL_DIR, file); - expect(fs.existsSync(filePath)).toBe(true); + return !fs.existsSync(filePath); + }); + + expect(missingFiles).toEqual([]); + if (missingFiles.length > 0) { + console.log("Missing files:", missingFiles); } }); diff --git a/core/autocomplete/README.md b/core/autocomplete/README.md index 2c68be1bf..e19509bd8 100644 --- a/core/autocomplete/README.md +++ b/core/autocomplete/README.md @@ -25,7 +25,7 @@ You can also set up tab-autocomplete with a local LM Studio instance by followin Example: -```json title=~/.continue/config.json +```json title="config.json" { "tabAutocompleteModel": { "title": "Starcoder2 3b", @@ -40,7 +40,7 @@ Example: All of the configuration options available for chat models are available to use for tab-autocomplete. For example, if you wanted to use a remote vLLM instance you would edit your `config.json` like this (note that it is not inside the models array), filling in the correct model name and vLLM endpoint: -```json title=~/.continue/config.json +```json title="config.json" { "tabAutocompleteModel": { "title": "Tab Autocomplete Model", @@ -54,7 +54,7 @@ All of the configuration options available for chat models are available to use As another example, say you want to use a different model, `deepseek-coder:6.7b-base`, with Ollama: -```json title=~/.continue/config.json +```json title="config.json" { "tabAutocompleteModel": { "title": "Tab Autocomplete Model", @@ -100,7 +100,7 @@ This object allows you to customize the behavior of tab-autocomplete. The availa ### Full example -```json title=~/.continue/config.json +```json title="config.json" { "tabAutocompleteModel": { "title": "Tab Autocomplete Model", diff --git a/core/autocomplete/ast.ts b/core/autocomplete/ast.ts index 933ae76c0..139b22dbf 100644 --- a/core/autocomplete/ast.ts +++ b/core/autocomplete/ast.ts @@ -2,6 +2,8 @@ import Parser from "web-tree-sitter"; import { RangeInFileWithContents } from "../commands/util.js"; import { getParserForFile } from "../util/treeSitter.js"; +export type AstPath = Parser.SyntaxNode[]; + export async function getAst( filepath: string, fileContents: string, @@ -23,7 +25,7 @@ export async function getAst( export async function getTreePathAtCursor( ast: Parser.Tree, cursorIndex: number, -): Promise { +): Promise { const path = [ast.rootNode]; while (path[path.length - 1].childCount > 0) { let foundChild = false; diff --git a/core/autocomplete/charStream.test.ts b/core/autocomplete/charStream.test.ts index 7ab8923fc..b5504ad63 100644 --- a/core/autocomplete/charStream.test.ts +++ b/core/autocomplete/charStream.test.ts @@ -1,4 +1,4 @@ -import { stopAtStopTokens } from "./charStream"; +import { stopAtStopTokens } from "./streamTransforms/charStream"; describe("stopAtStopTokens", () => { async function* createMockStream(chunks: string[]): AsyncGenerator { diff --git a/core/autocomplete/completionProvider.ts b/core/autocomplete/completionProvider.ts index bbc2d2577..d954c3f31 100644 --- a/core/autocomplete/completionProvider.ts +++ b/core/autocomplete/completionProvider.ts @@ -22,20 +22,18 @@ import { } from "../util/parameters.js"; import { Telemetry } from "../util/posthog.js"; import { getRangeInString } from "../util/ranges.js"; -import { ImportDefinitionsService } from "./ImportDefinitionsService.js"; -import { BracketMatchingService } from "./brackets.js"; + import AutocompleteLruCache from "./cache.js"; -import { - noFirstCharNewline, - onlyWhitespaceAfterEndOfLine, - stopAtStopTokens, -} from "./charStream.js"; import { constructAutocompletePrompt, languageForFilepath, } from "./constructPrompt.js"; import { isOnlyPunctuationAndWhitespace } from "./filter.js"; import { AutocompleteLanguageInfo } from "./languages.js"; +import { postprocessCompletion } from "./postprocessing.js"; +import { AutocompleteSnippet } from "./ranking.js"; +import { RecentlyEditedRange } from "./recentlyEdited.js"; +import { RootPathContextService } from "./services/RootPathContextService.js"; import { avoidPathLineAndEmptyComments, noTopLevelKeywordsMidline, @@ -44,15 +42,19 @@ import { stopAtRepeatingLines, stopAtSimilarLine, streamWithNewLines, -} from "./lineStream.js"; -import { postprocessCompletion } from "./postprocessing.js"; -import { AutocompleteSnippet } from "./ranking.js"; -import { RecentlyEditedRange } from "./recentlyEdited.js"; +} from "./streamTransforms/lineStream.js"; import { getTemplateForModel } from "./templates.js"; import { GeneratorReuseManager } from "./util.js"; // @prettier-ignore import Handlebars from "handlebars"; import { getConfigJsonPath } from "../util/paths.js"; +import { BracketMatchingService } from "./services/BracketMatchingService.js"; +import { ImportDefinitionsService } from "./services/ImportDefinitionsService.js"; +import { + noFirstCharNewline, + onlyWhitespaceAfterEndOfLine, + stopAtStopTokens, +} from "./streamTransforms/charStream.js"; export interface AutocompleteInput { completionId: string; @@ -158,9 +160,14 @@ export class CompletionProvider { this.onError.bind(this), ); this.importDefinitionsService = new ImportDefinitionsService(this.ide); + this.rootPathContextService = new RootPathContextService( + this.importDefinitionsService, + this.ide, + ); } private importDefinitionsService: ImportDefinitionsService; + private rootPathContextService: RootPathContextService; private generatorReuseManager: GeneratorReuseManager; private autocompleteCache = AutocompleteLruCache.get(); public errorsShown: Set = new Set(); @@ -204,7 +211,7 @@ export class CompletionProvider { const outcome = this._outcomes.get(completionId)!; outcome.accepted = true; logDevData("autocomplete", outcome); - Telemetry.capture( + void Telemetry.capture( "autocomplete", { accepted: outcome.accepted, @@ -378,7 +385,7 @@ export class CompletionProvider { outcome.accepted = false; logDevData("autocomplete", outcome); const { prompt, completion, ...restOfOutcome } = outcome; - Telemetry.capture( + void Telemetry.capture( "autocomplete", { ...restOfOutcome, @@ -542,6 +549,7 @@ export class CompletionProvider { llm.model, extrasSnippets, this.importDefinitionsService, + this.rootPathContextService, ); // If prefix is manually passed diff --git a/core/autocomplete/constructPrompt.ts b/core/autocomplete/constructPrompt.ts index cf5b07e44..f3d08ff5c 100644 --- a/core/autocomplete/constructPrompt.ts +++ b/core/autocomplete/constructPrompt.ts @@ -1,4 +1,3 @@ -import Parser from "web-tree-sitter"; import { RangeInFileWithContents } from "../commands/util.js"; import { TabAutocompleteOptions } from "../index.js"; @@ -7,8 +6,7 @@ import { pruneLinesFromBottom, pruneLinesFromTop, } from "../llm/countTokens.js"; -import { ImportDefinitionsService } from "./ImportDefinitionsService.js"; -import { getAst, getTreePathAtCursor } from "./ast.js"; +import { AstPath, getAst, getTreePathAtCursor } from "./ast.js"; import { AutocompleteLanguageInfo, LANGUAGES, @@ -22,6 +20,8 @@ import { type AutocompleteSnippet, } from "./ranking.js"; import { RecentlyEditedRange, findMatchingRange } from "./recentlyEdited.js"; +import { ImportDefinitionsService } from "./services/ImportDefinitionsService.js"; +import { RootPathContextService } from "./services/RootPathContextService.js"; export function languageForFilepath( filepath: string, @@ -32,7 +32,7 @@ export function languageForFilepath( const BLOCK_TYPES = ["body", "statement_block"]; function shouldCompleteMultilineAst( - treePath: Parser.SyntaxNode[], + treePath: AstPath, cursorLine: number, ): boolean { // If at the base of the file, do multiline @@ -63,7 +63,7 @@ function isMidlineCompletion(prefix: string, suffix: string): boolean { } async function shouldCompleteMultiline( - filepath: string, + treePath: AstPath | undefined, fullPrefix: string, fullSuffix: string, language: AutocompleteLanguageInfo, @@ -94,18 +94,6 @@ async function shouldCompleteMultiline( } // Use AST to determine whether to complete multiline - let treePath: Parser.SyntaxNode[] | undefined; - try { - const ast = await getAst(filepath, fullPrefix + fullSuffix); - if (!ast) { - return true; - } - - treePath = await getTreePathAtCursor(ast, fullPrefix.length); - } catch (e) { - console.error("Failed to parse AST", e); - } - let completeMultiline = false; if (treePath) { const cursorLine = fullPrefix.split("\n").length - 1; @@ -127,6 +115,7 @@ export async function constructAutocompletePrompt( modelName: string, extraSnippets: AutocompleteSnippet[], importDefinitionsService: ImportDefinitionsService, + rootPathContextService: RootPathContextService, ): Promise<{ prefix: string; suffix: string; @@ -145,6 +134,17 @@ export async function constructAutocompletePrompt( ); const suffix = pruneLinesFromBottom(fullSuffix, maxSuffixTokens, modelName); + // Calculate AST Path + let treePath: AstPath | undefined; + try { + const ast = await getAst(filepath, fullPrefix + fullSuffix); + if (ast) { + treePath = await getTreePathAtCursor(ast, fullPrefix.length); + } + } catch (e) { + console.error("Failed to parse AST", e); + } + // Find external snippets let snippets: AutocompleteSnippet[] = []; @@ -215,6 +215,14 @@ export async function constructAutocompletePrompt( snippets.push(...importSnippets); } + if (options.useRootPathContext && treePath) { + const ctx = await rootPathContextService.getContextForPath( + filepath, + treePath, + ); + snippets.push(...ctx); + } + // Filter out empty snippets and ones that are already in the prefix/suffix snippets = snippets .map((snippet) => ({ ...snippet })) @@ -269,7 +277,7 @@ export async function constructAutocompletePrompt( suffix, useFim: true, completeMultiline: await shouldCompleteMultiline( - filepath, + treePath, fullPrefix, fullSuffix, language, diff --git a/core/autocomplete/languages.ts b/core/autocomplete/languages.ts index f5b4cffb0..be414098a 100644 --- a/core/autocomplete/languages.ts +++ b/core/autocomplete/languages.ts @@ -1,4 +1,4 @@ -import type { LineFilter } from "./lineStream.js"; +import { LineFilter } from "./streamTransforms/lineStream"; export interface AutocompleteLanguageInfo { name: string; @@ -26,7 +26,7 @@ export const Python = { name: "Python", // """"#" is for .ipynb files, where we add '"""' surrounding markdown blocks. // This stops the model from trying to complete the start of a new markdown block - topLevelKeywords: ["def", "class", "\"\"\"#"], + topLevelKeywords: ["def", "class", '"""#'], singleLineComment: "#", endOfLine: [], }; diff --git a/core/autocomplete/lineStream.test.ts b/core/autocomplete/lineStream.test.ts index df8cd1263..ace94eaa4 100644 --- a/core/autocomplete/lineStream.test.ts +++ b/core/autocomplete/lineStream.test.ts @@ -1,5 +1,5 @@ import { jest } from "@jest/globals"; -import * as lineStream from "./lineStream"; +import * as lineStream from "./streamTransforms/lineStream"; describe("lineStream", () => { let mockFullStop: jest.Mock; diff --git a/core/autocomplete/postprocessing.ts b/core/autocomplete/postprocessing.ts index bc1961e69..cb3ada459 100644 --- a/core/autocomplete/postprocessing.ts +++ b/core/autocomplete/postprocessing.ts @@ -1,6 +1,6 @@ import type { ILLM } from "../index.js"; import { longestCommonSubsequence } from "../util/lcs.js"; -import { lineIsRepeated } from "./lineStream.js"; +import { lineIsRepeated } from "./streamTransforms/lineStream.js"; function rewritesLineAbove(completion: string, prefix: string): boolean { const lineAbove = prefix diff --git a/core/autocomplete/ranking.ts b/core/autocomplete/ranking.ts index 51791794c..48e01d5ff 100644 --- a/core/autocomplete/ranking.ts +++ b/core/autocomplete/ranking.ts @@ -80,7 +80,7 @@ export function deduplicateSnippets( function mergeSnippetsByRange( snippets: Required[], ): Required[] { - if (snippets.length === 0) { + if (snippets.length <= 1) { return snippets; } diff --git a/core/autocomplete/brackets.ts b/core/autocomplete/services/BracketMatchingService.ts similarity index 100% rename from core/autocomplete/brackets.ts rename to core/autocomplete/services/BracketMatchingService.ts diff --git a/core/autocomplete/ImportDefinitionsService.ts b/core/autocomplete/services/ImportDefinitionsService.ts similarity index 90% rename from core/autocomplete/ImportDefinitionsService.ts rename to core/autocomplete/services/ImportDefinitionsService.ts index a17e3a0c9..0df08f096 100644 --- a/core/autocomplete/ImportDefinitionsService.ts +++ b/core/autocomplete/services/ImportDefinitionsService.ts @@ -1,11 +1,11 @@ -import { IDE } from "../index.js"; -import { RangeInFileWithContents } from "../commands/util.js"; -import { PrecalculatedLruCache } from "../util/LruCache.js"; +import { IDE } from "../.."; +import { RangeInFileWithContents } from "../../commands/util"; +import { PrecalculatedLruCache } from "../../util/LruCache"; import { TSQueryType, getParserForFile, getQueryForFile, -} from "../util/treeSitter.js"; +} from "../../util/treeSitter"; interface FileInfo { imports: { [key: string]: RangeInFileWithContents[] }; diff --git a/core/autocomplete/services/NearbyDefinitionsService.ts b/core/autocomplete/services/NearbyDefinitionsService.ts new file mode 100644 index 000000000..12d6f7947 --- /dev/null +++ b/core/autocomplete/services/NearbyDefinitionsService.ts @@ -0,0 +1,45 @@ +import { IDE, Location } from "../.."; +import { LANGUAGES } from "../languages"; +import { getSymbolsForSnippet } from "../ranking"; + +interface FileInfo { + filepath: string; +} + +export class NearbyDefinitionsService { + static N = 10; + + constructor(private readonly ide: IDE) {} + + async getDefinitionsForLine(filepath: string, line: number) { + const lineContent = await this.ide.readRangeInFile(filepath, { + start: { + line, + character: 0, + }, + end: { + line: line + 1, + character: 0, + }, + }); + + // Remove keywords + const lang = LANGUAGES[filepath.split(".").slice(-1)[0]]; + const symbols = Array.from(getSymbolsForSnippet(lineContent)) + .filter((s) => s.length > 0) + .filter((s) => !(lang && lang?.stopWords?.includes(s))); + + return Promise.all( + symbols.map((s) => { + const character = lineContent.indexOf(s); + const pos: Location = { + filepath, + position: { + line, + character, + }, + }; + }), + ); + } +} diff --git a/core/autocomplete/services/RootPathContextService.ts b/core/autocomplete/services/RootPathContextService.ts new file mode 100644 index 000000000..69426aab8 --- /dev/null +++ b/core/autocomplete/services/RootPathContextService.ts @@ -0,0 +1,129 @@ +import { createHash } from "crypto"; +import { LRUCache } from "lru-cache"; +import Parser from "web-tree-sitter"; +import { IDE } from "../.."; +import { getQueryForFile, TSQueryType } from "../../util/treeSitter"; +import { AstPath } from "../ast"; +import { AutocompleteSnippet } from "../ranking"; +import { ImportDefinitionsService } from "./ImportDefinitionsService"; + +export class RootPathContextService { + private cache = new LRUCache({ + max: 100, + }); + + constructor( + private readonly importDefinitionsService: ImportDefinitionsService, + private readonly ide: IDE, + ) {} + + private static getNodeId(node: Parser.SyntaxNode): string { + return `${node.startIndex}`; + } + + private static TYPES_TO_USE = new Set([ + "program", + "function_declaration", + "method_definition", + ]); + + /** + * Key comes from hash of parent key and node type and node id. + */ + private static keyFromNode( + parentKey: string, + astNode: Parser.SyntaxNode, + ): string { + return createHash("sha256") + .update(parentKey) + .update(astNode.type) + .update(RootPathContextService.getNodeId(astNode)) + .digest("hex"); + } + + private async getSnippetsForNode( + filepath: string, + node: Parser.SyntaxNode, + ): Promise { + const snippets: AutocompleteSnippet[] = []; + + let query: Parser.Query | undefined; + switch (node.type) { + case "program": + this.importDefinitionsService.get(filepath); + break; + case "function_declaration": + query = await getQueryForFile( + filepath, + TSQueryType.FunctionDeclaration, + ); + break; + case "method_definition": + query = await getQueryForFile(filepath, TSQueryType.MethodDefinition); + break; + case "function_definition": + query = await getQueryForFile(filepath, TSQueryType.FunctionDefinition); + break; + case "method_declaration": + query = await getQueryForFile(filepath, TSQueryType.MethodDeclaration); + break; + default: + break; + } + + if (!query) { + return snippets; + } + + await Promise.all( + query.matches(node).map(async (match) => { + const startPosition = match.captures[0].node.startPosition; + const endPosition = match.captures[0].node.endPosition; + const definitions = await this.ide.gotoDefinition({ + filepath, + position: { + line: endPosition.row, + character: endPosition.column, + }, + }); + const newSnippets = await Promise.all( + definitions.map(async (def) => ({ + ...def, + contents: await this.ide.readRangeInFile(def.filepath, def.range), + })), + ); + snippets.push(...newSnippets); + }), + ); + + return snippets; + } + + async getContextForPath( + filepath: string, + astPath: AstPath, + // cursorIndex: number, + ): Promise { + const snippets: AutocompleteSnippet[] = []; + + let parentKey = filepath; + for (const astNode of astPath.filter((node) => + RootPathContextService.TYPES_TO_USE.has(node.type), + )) { + const key = RootPathContextService.keyFromNode(parentKey, astNode); + + const foundInCache = this.cache.get(key); + const newSnippets = + foundInCache ?? (await this.getSnippetsForNode(filepath, astNode)); + snippets.push(...newSnippets); + + if (!foundInCache) { + this.cache.set(key, newSnippets); + } + + parentKey = key; + } + + return snippets; + } +} diff --git a/core/autocomplete/charStream.ts b/core/autocomplete/streamTransforms/charStream.ts similarity index 100% rename from core/autocomplete/charStream.ts rename to core/autocomplete/streamTransforms/charStream.ts diff --git a/core/autocomplete/lineStream.ts b/core/autocomplete/streamTransforms/lineStream.ts similarity index 94% rename from core/autocomplete/lineStream.ts rename to core/autocomplete/streamTransforms/lineStream.ts index e7d3493bd..5990bbf3c 100644 --- a/core/autocomplete/lineStream.ts +++ b/core/autocomplete/streamTransforms/lineStream.ts @@ -1,6 +1,6 @@ import { distance } from "fastest-levenshtein"; -import { LineStream } from "../diff/util"; -import { DiffLine } from "../"; +import { DiffLine } from "../.."; +import { LineStream } from "../../diff/util"; export type LineFilter = (args: { lines: LineStream; @@ -238,9 +238,10 @@ export async function* stopAtSimilarLine( export async function* stopAtLines( stream: LineStream, fullStop: () => void, + linesToStopAt: string[] = LINES_TO_STOP_AT, ): LineStream { for await (const line of stream) { - if (LINES_TO_STOP_AT.some((stopAt) => line.trim().includes(stopAt))) { + if (linesToStopAt.some((stopAt) => line.trim().includes(stopAt))) { fullStop(); break; } @@ -382,6 +383,17 @@ export async function* filterEnglishLinesAtEnd(lines: LineStream) { } } +export async function* filterLeadingNewline(lines: LineStream): LineStream { + let firstLine = true; + for await (const line of lines) { + if (firstLine && line.trim() === "") { + firstLine = false; + continue; + } + yield line; + } +} + /** * Removes leading indentation from the first line of a CodeLlama output. * @param {LineStream} lines - The input stream of lines. @@ -482,3 +494,19 @@ export async function* stopAtRepeatingLines( previousLine = line; } } + +/** + * Pass-through, except logs the total output at the end + * @param lines a `LineStream` + */ +export async function* logLines( + lines: LineStream, + prefix: string = "STREAMED LINES", +): LineStream { + let linesToLog = []; + for await (const line of lines) { + yield line; + linesToLog.push(line); + } + console.log(`${prefix}:\n${linesToLog.join("\n")}\n\n`); +} diff --git a/core/autocomplete/templates.ts b/core/autocomplete/templates.ts index 030e0a306..cda8b8a2d 100644 --- a/core/autocomplete/templates.ts +++ b/core/autocomplete/templates.ts @@ -41,6 +41,25 @@ const stableCodeFimTemplate: AutocompleteTemplate = { }, }; +// https://github.com/QwenLM/Qwen2.5-Coder?tab=readme-ov-file#3-file-level-code-completion-fill-in-the-middle +const qwenCoderFimTemplate: AutocompleteTemplate = { + template: + "<|fim_prefix|>{{{prefix}}}<|fim_suffix|>{{{suffix}}}<|fim_middle|>", + completionOptions: { + stop: [ + "<|endoftext|>", + "<|fim_prefix|>", + "<|fim_middle|>", + "<|fim_suffix|>", + "<|fim_pad|>", + "<|repo_name|>", + "<|file_sep|>", + "<|im_start|>", + "<|im_end|>", + ], + }, +}; + const codestralFimTemplate: AutocompleteTemplate = { template: "[SUFFIX]{{{suffix}}}[PREFIX]{{{prefix}}}", completionOptions: { @@ -318,6 +337,10 @@ export function getTemplateForModel(model: string): AutocompleteTemplate { // return starcoder2FimTemplate; // } + if (lowerCaseModel.includes("qwen") && lowerCaseModel.includes("coder")) { + return qwenCoderFimTemplate; + } + if ( lowerCaseModel.includes("starcoder") || lowerCaseModel.includes("star-coder") || diff --git a/core/commands/slash/edit.ts b/core/commands/slash/edit.ts index a3c3ed91c..5d26b0408 100644 --- a/core/commands/slash/edit.ts +++ b/core/commands/slash/edit.ts @@ -1,3 +1,4 @@ +import { ContextItemWithId, ILLM, SlashCommand } from "../../"; import { filterCodeBlockLines, filterEnglishLinesAtEnd, @@ -5,16 +6,15 @@ import { fixCodeLlamaFirstLineIndentation, stopAtLines, streamWithNewLines, -} from "../../autocomplete/lineStream"; +} from "../../autocomplete/streamTransforms/lineStream"; import { streamLines } from "../../diff/util"; -import { ContextItemWithId, ILLM, SlashCommand } from "../../"; import { stripImages } from "../../llm/images"; import { dedentAndGetCommonWhitespace, getMarkdownLanguageTagForFile, } from "../../util/"; import { - contextItemToRangeInFileWithContents, + ctxItemToRifWithContents, type RangeInFileWithContents, } from "../util"; @@ -250,7 +250,7 @@ const EditSlashCommand: SlashCommand = { } const rif: RangeInFileWithContents = - contextItemToRangeInFileWithContents(contextItemToEdit); + ctxItemToRifWithContents(contextItemToEdit); await ide.saveFile(rif.filepath); const fullFileContents = await ide.readFile(rif.filepath); diff --git a/core/commands/util.ts b/core/commands/util.ts index 207b6c5ec..a6be440e9 100644 --- a/core/commands/util.ts +++ b/core/commands/util.ts @@ -1,4 +1,4 @@ -import { ContextItemWithId } from "../index.js"; +import { ContextItemWithId } from "../"; export interface RangeInFileWithContents { filepath: string; @@ -9,20 +9,29 @@ export interface RangeInFileWithContents { contents: string; } -export function contextItemToRangeInFileWithContents( +export function ctxItemToRifWithContents( item: ContextItemWithId, ): RangeInFileWithContents { - const lines = item.name.split("(")[1].split(")")[0].split("-"); + let startLine = 0; + let endLine = 0; + + const nameSplit = item.name.split("("); + + if (nameSplit.length > 1) { + const lines = nameSplit[1].split(")")[0].split("-"); + startLine = Number.parseInt(lines[0], 10); + endLine = Number.parseInt(lines[1], 10); + } const rif: RangeInFileWithContents = { - filepath: item.id.itemId, + filepath: item.uri?.value || "", range: { start: { - line: Number.parseInt(lines[0]), + line: startLine, character: 0, }, end: { - line: Number.parseInt(lines[1]), + line: endLine, character: 0, }, }, diff --git a/core/config/default.ts b/core/config/default.ts index af5b19913..634c8c599 100644 --- a/core/config/default.ts +++ b/core/config/default.ts @@ -21,9 +21,11 @@ export const DEFAULT_AUTOCOMPLETE_MODEL_CONFIG: ModelDescription = { export const FREE_TRIAL_MODELS: ModelDescription[] = [ { - title: "Claude 3 Sonnet (Free Trial)", + title: "Claude 3.5 Sonnet (Free Trial)", provider: "free-trial", - model: "claude-3-sonnet-20240229", + model: "claude-3-5-sonnet-20240620", + systemMessage: + "You are an expert software developer. You give helpful and concise responses.", }, { title: "GPT-4o (Free Trial)", @@ -33,16 +35,18 @@ export const FREE_TRIAL_MODELS: ModelDescription[] = [ "You are an expert software developer. You give helpful and concise responses.", }, { - title: "Llama3 70b (Free Trial)", + title: "Llama3.1 70b (Free Trial)", provider: "free-trial", - model: "llama3-70b", + model: "llama3.1-70b", systemMessage: - "You are an expert software developer. You give helpful and concise responses. Whenever you write a code block you include the language after the opening ticks.", + "You are an expert software developer. You give helpful and concise responses.", }, { title: "Codestral (Free Trial)", provider: "free-trial", - model: "codestral", + model: "codestral-latest", + systemMessage: + "You are an expert software developer. You give helpful and concise responses.", }, ]; diff --git a/core/config/load.ts b/core/config/load.ts index 95fc73053..67982ecad 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -595,7 +595,24 @@ async function loadFullConfigNode( try { // Try config.ts first const configJsPath = getConfigJsPath(); - const module = await import(configJsPath); + let module: any; + + try { + module = await import(configJsPath); + } catch (e) { + console.log(e); + console.log( + "Could not load config.ts as absolute path, retrying as file url ...", + ); + try { + module = await import(`file://${configJsPath}`); + } catch (e) { + throw new Error("Could not load config.ts as file url either", { + cause: e, + }); + } + } + if (typeof require !== "undefined") { delete require.cache[require.resolve(configJsPath)]; } diff --git a/core/config/profile/doLoadConfig.ts b/core/config/profile/doLoadConfig.ts index 13b098f50..e19feed85 100644 --- a/core/config/profile/doLoadConfig.ts +++ b/core/config/profile/doLoadConfig.ts @@ -1,7 +1,12 @@ import { ContinueProxyReranker } from "../../context/rerankers/ContinueProxyReranker.js"; -import { ControlPlaneClient } from "../../control-plane/client.js"; +import { ControlPlaneProxyInfo } from "../../control-plane/analytics/IAnalyticsProvider.js"; +import { + ControlPlaneClient, + DEFAULT_CONTROL_PLANE_PROXY_URL, +} from "../../control-plane/client.js"; import { TeamAnalytics } from "../../control-plane/TeamAnalytics.js"; import { + ContinueConfig, ContinueRcJson, IDE, IdeSettings, @@ -33,7 +38,7 @@ export default async function doLoadConfig( const ideSettings = await ideSettingsPromise; const workOsAccessToken = await controlPlaneClient.getAccessToken(); - const newConfig = await loadFullConfigNode( + let newConfig = await loadFullConfigNode( ide, workspaceConfigs, ideSettings, @@ -56,34 +61,59 @@ export default async function doLoadConfig( // TODO: pass config to pre-load non-system TTS models await TTS.setup(); + // Set up control plane proxy if configured + let controlPlaneProxyUrl: string = + (newConfig as any).controlPlane?.proxyUrl ?? + DEFAULT_CONTROL_PLANE_PROXY_URL; + if (!controlPlaneProxyUrl.endsWith("/")) { + controlPlaneProxyUrl += "/"; + } + const controlPlaneProxyInfo = { + workspaceId, + controlPlaneProxyUrl, + workOsAccessToken, + }; + if (newConfig.analytics) { await TeamAnalytics.setup( newConfig.analytics as any, // TODO: Need to get rid of index.d.ts once and for all uniqueId, ideInfo.extensionVersion, controlPlaneClient, - workspaceId, + controlPlaneProxyInfo, ); } - [...newConfig.models, ...(newConfig.tabAutocompleteModels ?? [])].forEach( + newConfig = await injectControlPlaneProxyInfo( + newConfig, + controlPlaneProxyInfo, + ); + + return newConfig; +} + +// Pass ControlPlaneProxyInfo to objects that need it +async function injectControlPlaneProxyInfo( + config: ContinueConfig, + info: ControlPlaneProxyInfo, +): Promise { + [...config.models, ...(config.tabAutocompleteModels ?? [])].forEach( async (model) => { if (model.providerName === "continue-proxy") { - (model as ContinueProxy).workOsAccessToken = workOsAccessToken; + (model as ContinueProxy).controlPlaneProxyInfo = info; } }, ); - if (newConfig.embeddingsProvider?.providerName === "continue-proxy") { + if (config.embeddingsProvider?.providerName === "continue-proxy") { ( - newConfig.embeddingsProvider as ContinueProxyEmbeddingsProvider - ).workOsAccessToken = workOsAccessToken; + config.embeddingsProvider as ContinueProxyEmbeddingsProvider + ).controlPlaneProxyInfo = info; } - if (newConfig.reranker?.name === "continue-proxy") { - (newConfig.reranker as ContinueProxyReranker).workOsAccessToken = - workOsAccessToken; + if (config.reranker?.name === "continue-proxy") { + (config.reranker as ContinueProxyReranker).controlPlaneProxyInfo = info; } - return newConfig; + return config; } diff --git a/core/config/types.ts b/core/config/types.ts index e69c312ab..dafbe588a 100644 --- a/core/config/types.ts +++ b/core/config/types.ts @@ -47,6 +47,7 @@ declare global { llmRequestHook?: (model: string, prompt: string) => any; apiKey?: string; apiBase?: string; + cacheBehavior?: CacheBehavior; engine?: string; apiVersion?: string; @@ -313,6 +314,7 @@ declare global { apiKey?: string; aiGatewaySlug?: string; apiBase?: string; + cacheBehavior?: CacheBehavior; useLegacyCompletionsEndpoint?: boolean; @@ -341,8 +343,6 @@ declare global { watsonxProjectId?: string; watsonxStopToken?: string; watsonxApiVersion?: string; - - cacheSystemMessage?: boolean; } type RequireAtLeastOne = Pick< T, @@ -547,7 +547,8 @@ declare global { | "docs" | "gitlab-mr" | "os" - | "currentFile"; + | "currentFile" + | "greptile; type TemplateType = | "llama2" @@ -647,6 +648,8 @@ declare global { | "deepseek-7b" | "deepseek-33b" | "neural-chat-7b" + | "gemma-7b-it" + | "gemma2-9b-it" // Anthropic | "claude-3-5-sonnet-20240620" | "claude-3-opus-20240229" @@ -685,6 +688,11 @@ declare global { clientCertificate?: ClientCertificateOptions; } + export interface CacheBehavior { + cacheSystemMessage?: boolean; + cacheConversation?: boolean; + } + export interface ClientCertificateOptions { cert: string; key: string; @@ -747,6 +755,7 @@ declare global { requestOptions?: RequestOptions; promptTemplates?: { [key: string]: string }; capabilities?: ModelCapability; + cacheBehavior?: CacheBehavior; } export type EmbeddingsProviderName = diff --git a/core/config/util.ts b/core/config/util.ts index 5abf0b9b5..0247aa25d 100644 --- a/core/config/util.ts +++ b/core/config/util.ts @@ -1,4 +1,10 @@ -import { ContextProviderWithParams, ModelDescription } from "../"; +import { + ContextProviderWithParams, + ContinueConfig, + ILLM, + ModelDescription, + ModelRoles, +} from "../"; import { editConfigJson } from "../util/paths"; function stringify(obj: any, indentation?: number): string { @@ -23,7 +29,7 @@ export function addContextProvider(provider: ContextProviderWithParams) { }); } -export function addModel(model: ModelDescription) { +export function addModel(model: ModelDescription, role?: keyof ModelRoles) { editConfigJson((config) => { if (config.models?.some((m: any) => stringify(m) === stringify(model))) { return config; @@ -33,6 +39,18 @@ export function addModel(model: ModelDescription) { } config.models.push(model); + + // Set the role for the model + if (role) { + if (!config.experimental) { + config.experimental = {}; + } + if (!config.experimental.modelRoles) { + config.experimental.modelRoles = {}; + } + config.experimental.modelRoles[role] = model.title; + } + return config; }); } @@ -61,3 +79,20 @@ export function deleteModel(title: string) { return config; }); } + +export function getModelByRole( + config: ContinueConfig, + role: T, +): ILLM | undefined { + const roleTitle = config.experimental?.modelRoles?.[role]; + + if (!roleTitle) { + return undefined; + } + + const matchingModel = config.models.find( + (model) => model.title === roleTitle, + ); + + return matchingModel; +} diff --git a/core/context/providers/CodebaseContextProvider.ts b/core/context/providers/CodebaseContextProvider.ts index 2de4352d9..5e77c537b 100644 --- a/core/context/providers/CodebaseContextProvider.ts +++ b/core/context/providers/CodebaseContextProvider.ts @@ -2,9 +2,9 @@ import { ContextItem, ContextProviderDescription, ContextProviderExtras, -} from "../../index.js"; -import { BaseContextProvider } from "../index.js"; -import { retrieveContextItemsFromEmbeddings } from "../retrieval/retrieval.js"; +} from "../../"; +import { BaseContextProvider } from "../"; +import { retrieveContextItemsFromEmbeddings } from "../retrieval/retrieval"; class CodebaseContextProvider extends BaseContextProvider { static description: ContextProviderDescription = { diff --git a/core/context/providers/CurrentFileContextProvider.ts b/core/context/providers/CurrentFileContextProvider.ts index e149c8079..575350b49 100644 --- a/core/context/providers/CurrentFileContextProvider.ts +++ b/core/context/providers/CurrentFileContextProvider.ts @@ -2,9 +2,9 @@ import { ContextItem, ContextProviderDescription, ContextProviderExtras, -} from "../../index.js"; -import { getBasename } from "../../util/index.js"; -import { BaseContextProvider } from "../index.js"; +} from "../../"; +import { getBasename } from "../../util/"; +import { BaseContextProvider } from "../"; class CurrentFileContextProvider extends BaseContextProvider { static description: ContextProviderDescription = { @@ -32,6 +32,10 @@ class CurrentFileContextProvider extends BaseContextProvider { currentFile, )}\n${contents}\n\`\`\``, name: getBasename(currentFile), + uri: { + type: "file", + value: currentFile, + }, }, ]; } diff --git a/core/context/providers/DatabaseContextProvider.ts b/core/context/providers/DatabaseContextProvider.ts index 81a0a2710..3e7b54f0e 100644 --- a/core/context/providers/DatabaseContextProvider.ts +++ b/core/context/providers/DatabaseContextProvider.ts @@ -6,7 +6,7 @@ import { LoadSubmenuItemsArgs, } from "../../index.js"; import { BaseContextProvider } from "../index.js"; -import getDatabaseAdapter from "dbinfoz"; +import { getDatabaseAdapter } from "dbinfoz"; class DatabaseContextProvider extends BaseContextProvider { static description: ContextProviderDescription = { diff --git a/core/context/providers/DocsContextProvider.ts b/core/context/providers/DocsContextProvider.ts index 88df47318..f54692c47 100644 --- a/core/context/providers/DocsContextProvider.ts +++ b/core/context/providers/DocsContextProvider.ts @@ -1,3 +1,4 @@ +import { INSTRUCTIONS_BASE_ITEM } from "./utils"; import { BaseContextProvider } from "../"; import { Chunk, @@ -90,7 +91,7 @@ class DocsContextProvider extends BaseContextProvider { await docsService.isJetBrainsAndPreIndexedDocsProvider(); if (isJetBrainsAndPreIndexedDocsProvider) { - extras.ide.showToast( + await extras.ide.showToast( "error", `${DocsService.preIndexedDocsEmbeddingsProvider.id} is configured as ` + "the embeddings provider, but it cannot be used with JetBrains. " + @@ -104,7 +105,7 @@ class DocsContextProvider extends BaseContextProvider { const preIndexedDoc = preIndexedDocs[query]; if (!!preIndexedDoc) { - Telemetry.capture("docs_pre_indexed_doc_used", { + void Telemetry.capture("docs_pre_indexed_doc_used", { doc: preIndexedDoc["title"], }); } @@ -146,11 +147,14 @@ class DocsContextProvider extends BaseContextProvider { : chunk.otherMetadata?.title || chunk.filepath, description: chunk.filepath, content: chunk.content, + uri: { + type: "url" as const, + value: chunk.filepath, + }, })) .reverse(), { - name: "Instructions", - description: "Instructions", + ...INSTRUCTIONS_BASE_ITEM, content: "Use the above documentation to answer the following question. You should not reference " + "anything outside of what is shown, unless it is a commonly known concept. Reference URLs " + diff --git a/core/context/providers/FileContextProvider.ts b/core/context/providers/FileContextProvider.ts index ef0bfeb54..d1ac2d6e2 100644 --- a/core/context/providers/FileContextProvider.ts +++ b/core/context/providers/FileContextProvider.ts @@ -4,14 +4,14 @@ import { ContextProviderExtras, ContextSubmenuItem, LoadSubmenuItemsArgs, -} from "../../index.js"; -import { walkDir } from "../../indexing/walkDir.js"; +} from "../../"; +import { walkDir } from "../../indexing/walkDir"; import { getBasename, getUniqueFilePath, groupByLastNPathParts, -} from "../../util/index.js"; -import { BaseContextProvider } from "../index.js"; +} from "../../util/"; +import { BaseContextProvider } from "../"; const MAX_SUBMENU_ITEMS = 10_000; @@ -36,6 +36,10 @@ class FileContextProvider extends BaseContextProvider { name: query.split(/[\\/]/).pop() ?? query, description: query, content: `\`\`\`${query}\n${content}\n\`\`\``, + uri: { + type: "file", + value: query, + }, }, ]; } diff --git a/core/context/providers/GreptileContextProvider.ts b/core/context/providers/GreptileContextProvider.ts new file mode 100644 index 000000000..c6b7620c4 --- /dev/null +++ b/core/context/providers/GreptileContextProvider.ts @@ -0,0 +1,186 @@ +import { + ContextItem, + ContextProviderDescription, + ContextProviderExtras, + } from "../../index.js"; + import { BaseContextProvider } from "../index.js"; + import { execSync } from "child_process"; + import * as path from "path"; + import * as fs from "fs"; + + class GreptileContextProvider extends BaseContextProvider { + static description: ContextProviderDescription = { + title: "greptile", + displayTitle: "Greptile", + description: "Insert query to Greptile", + type: "query", + }; + + async getContextItems( + query: string, + extras: ContextProviderExtras, + ): Promise { + const greptileToken = this.getGreptileToken(); + if (!greptileToken) { + throw new Error("Greptile token not found."); + } + + const githubToken = this.getGithubToken(); + if (!githubToken) { + throw new Error("GitHub token not found."); + } + + let absPath = await this.getWorkspaceDir(extras); + if (!absPath) { + throw new Error("Failed to determine the workspace directory."); + } + + var remoteUrl = getRemoteUrl(absPath) + remoteUrl = getRemoteUrl(absPath); + const repoName = extractRepoName(remoteUrl); + const branch = getCurrentBranch(absPath); + const remoteType = getRemoteType(remoteUrl); + + if (!remoteType) { + throw new Error("Unable to determine remote type."); + } + + const options = { + method: 'POST', + headers: { + Authorization: `Bearer ${greptileToken}`, + 'X-GitHub-Token': githubToken, + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + messages: [{ id: "", content: query, role: "user" }], + repositories: [{ + remote: remoteType, + branch: branch, + repository: repoName + }], + sessionId: extras.config.userToken || "default-session", + stream: false, + genius: true, + }), + }; + + try { + const response = await extras.fetch('https://api.greptile.com/v2/query', options); + const rawText = await response.text(); + + // Check for HTTP errors + if (!response.ok) { + throw new Error(`HTTP error! status: ${response.status}`); + } + + // Parse the response as JSON + const json = JSON.parse(rawText); + + return json.sources.map((source: any) => ({ + description: source.filepath, + content: `File: ${source.filepath}\nLines: ${source.linestart}-${source.lineend}\n\n${source.summary}`, + name: (source.filepath.split("/").pop() ?? "").split("\\").pop() ?? "", + })); + } catch (error) { + console.error("Error getting context items from Greptile:", error); + throw new Error(`Error getting context items from Greptile`); + } + } + + private getGreptileToken(): string | undefined { + return this.options.GreptileToken || process.env.GREPTILE_AUTH_TOKEN; + } + + private getGithubToken(): string | undefined { + return this.options.GithubToken || process.env.GITHUB_TOKEN; + } + + private async getWorkspaceDir(extras: ContextProviderExtras): Promise { + try { + const workspaceDirs = await extras.ide.getWorkspaceDirs(); + if (workspaceDirs && workspaceDirs.length > 0) { + return workspaceDirs[0]; + } else { + console.warn(`extras.ide.getWorkspaceDirs() returned undefined or empty array.`); + } + } catch (err) { + console.warn(`Failed to get workspace directories from extras.ide.getWorkspaceDirs():`); + } + + // Fallback to using Git commands + try { + const currentDir = process.cwd(); + if (this.isGitRepository(currentDir)) { + const workspaceDir = execSync('git rev-parse --show-toplevel').toString().trim(); + return workspaceDir; + } else { + console.warn(`Current directory is not a Git repository: ${currentDir}`); + return null; + } + } catch (err) { + console.warn(`Failed to get workspace directory using Git commands: `); + return null; + } + } + + private isGitRepository(dir: string): boolean { + try { + const gitDir = path.join(dir, '.git'); + return fs.existsSync(gitDir); + } catch (err) { + console.warn(`Failed to check if directory is a Git repository:`); + return false; + } + } + } + + // Helper functions + function getRemoteUrl(absPath: string): string { + try { + const remote = execSync(`git -C ${absPath} remote get-url origin`).toString().trim(); + return remote; + } catch (err) { + console.warn(`Failed to get remote URL`); + return ""; + } + } + + function getCurrentBranch(absPath: string): string { + try { + const branch = execSync(`git -C ${absPath} rev-parse --abbrev-ref HEAD`).toString().trim(); + return branch; + } catch (err) { + console.warn(`Failed to get current branch`); + return "master"; // Default to 'master' if the current branch cannot be determined + } + } + + function extractRepoName(remote: string): string { + if (remote.startsWith("http://") || remote.startsWith("https://")) { + const parts = remote.split("/"); + if (parts.length >= 2) { + return parts[parts.length - 2] + "/" + parts[parts.length - 1].replace(".git", ""); + } + } else if (remote.startsWith("git@")) { + const parts = remote.split(":"); + if (parts.length >= 2) { + return parts[1].replace(".git", ""); + } + } + return ""; + } + + function getRemoteType(remote: string): string { + if (remote.includes("github.com")) { + return "github"; + } else if (remote.includes("gitlab.com")) { + return "gitlab"; + } else if (remote.includes("azure.com")) { + return "azure"; + } + return ""; + } + + export default GreptileContextProvider; + \ No newline at end of file diff --git a/core/context/providers/HttpContextProvider.ts b/core/context/providers/HttpContextProvider.ts index a33bcb775..9e6aaa8c7 100644 --- a/core/context/providers/HttpContextProvider.ts +++ b/core/context/providers/HttpContextProvider.ts @@ -39,14 +39,15 @@ class HttpContextProvider extends BaseContextProvider { }), }); - const json: any = await response.json(); - return [ - { - description: json.description || "HTTP Context Item", - content: json.content || "", - name: json.name || this.options.title || "HTTP", - }, - ]; + const json = await response.json(); + + const createContextItem = (item: any) => ({ + description: item.description ?? "HTTP Context Item", + content: item.content ?? "", + name: item.name ?? this.options.title ?? "HTTP", + }); + + return Array.isArray(json) ? json.map(createContextItem) : [createContextItem(json)]; } } diff --git a/core/context/providers/OSContextProvider.ts b/core/context/providers/OSContextProvider.ts index 5f06e5f3d..45852c934 100644 --- a/core/context/providers/OSContextProvider.ts +++ b/core/context/providers/OSContextProvider.ts @@ -23,8 +23,10 @@ class OSContextProvider extends BaseContextProvider { return [ { description: "Your operating system and CPU", - content: `I am running ${platform} on ${cpu}.`, - name: "os", + content: `I am running ${ + platform === "win32" ? "Windows" : platform + } on ${cpu}.`, + name: "Operating System", }, ]; } diff --git a/core/context/providers/OpenFilesContextProvider.ts b/core/context/providers/OpenFilesContextProvider.ts index b0c85bc2e..c00121a96 100644 --- a/core/context/providers/OpenFilesContextProvider.ts +++ b/core/context/providers/OpenFilesContextProvider.ts @@ -28,10 +28,15 @@ class OpenFilesContextProvider extends BaseContextProvider { openFiles.map(async (filepath: string) => { return { description: filepath, - content: `\`\`\`${await getRelativePath(filepath, workspaceDirs)}\n${await ide.readFile( + content: `\`\`\`${await getRelativePath( filepath, - )}\n\`\`\``, + workspaceDirs, + )}\n${await ide.readFile(filepath)}\n\`\`\``, name: (filepath.split("/").pop() ?? "").split("\\").pop() ?? "", + uri: { + type: "file", + value: filepath, + }, }; }), ); diff --git a/core/context/providers/RepoMapContextProvider.ts b/core/context/providers/RepoMapContextProvider.ts index 3d6c1d63f..6aefe0301 100644 --- a/core/context/providers/RepoMapContextProvider.ts +++ b/core/context/providers/RepoMapContextProvider.ts @@ -3,15 +3,28 @@ import { ContextItem, ContextProviderDescription, ContextProviderExtras, + ContextSubmenuItem, + LoadSubmenuItemsArgs, } from "../../"; -import generateRepoMap from "../../util/repoMap"; +import { + groupByLastNPathParts, + getBasename, + getUniqueFilePath, +} from "../../util"; +import generateRepoMap from "../../util/generateRepoMap"; + +const ENTIRE_PROJECT_ITEM: ContextSubmenuItem = { + id: "entire-codebase", + title: "Entire codebase", + description: "Search the entire codebase", +}; class RepoMapContextProvider extends BaseContextProvider { static description: ContextProviderDescription = { title: "repo-map", displayTitle: "Repository Map", - description: "List of files and signatures", - type: "normal", + description: "Select a folder", + type: "submenu", dependsOnIndexing: true, }; @@ -23,10 +36,28 @@ class RepoMapContextProvider extends BaseContextProvider { { name: "Repository Map", description: "Overview of the repository structure", - content: await generateRepoMap(extras.llm, extras.ide), + content: await generateRepoMap(extras.llm, extras.ide, { + dirs: query === ENTIRE_PROJECT_ITEM.id ? undefined : [query], + }), }, ]; } + + async loadSubmenuItems( + args: LoadSubmenuItemsArgs, + ): Promise { + const folders = await args.ide.listFolders(); + const folderGroups = groupByLastNPathParts(folders, 2); + + return [ + ENTIRE_PROJECT_ITEM, + ...folders.map((folder) => ({ + id: folder, + title: getBasename(folder), + description: getUniqueFilePath(folder, folderGroups), + })), + ]; + } } export default RepoMapContextProvider; diff --git a/core/context/providers/URLContextProvider.ts b/core/context/providers/URLContextProvider.ts index 2e864fbb9..b0f4bd9ce 100644 --- a/core/context/providers/URLContextProvider.ts +++ b/core/context/providers/URLContextProvider.ts @@ -1,12 +1,13 @@ import { Readability } from "@mozilla/readability"; import { JSDOM } from "jsdom"; import { NodeHtmlMarkdown } from "node-html-markdown"; -import { BaseContextProvider } from "../index.js"; +import { BaseContextProvider } from "../"; import { ContextItem, ContextProviderDescription, ContextProviderExtras, } from "../../index.js"; +import { fetchFavicon } from "../../util/fetchFavicon"; class URLContextProvider extends BaseContextProvider { static description: ContextProviderDescription = { @@ -22,6 +23,7 @@ class URLContextProvider extends BaseContextProvider { ): Promise { try { const url = new URL(query); + const icon = await fetchFavicon(url); const resp = await extras.fetch(url); const html = await resp.text(); @@ -37,11 +39,17 @@ class URLContextProvider extends BaseContextProvider { ); const title = article?.title || url.pathname; + return [ { - description: title, + icon, + description: url.toString(), content: markdown, name: title, + uri: { + type: "url", + value: url.toString(), + }, }, ]; } catch (e) { diff --git a/core/context/providers/index.ts b/core/context/providers/index.ts index 92cabb222..7ee2881be 100644 --- a/core/context/providers/index.ts +++ b/core/context/providers/index.ts @@ -1,4 +1,4 @@ -import { ContextProviderName } from "../../"; +import { ContextItem, ContextProviderName } from "../../"; import { BaseContextProvider } from "../"; import CodeContextProvider from "./CodeContextProvider"; import ContinueProxyContextProvider from "./ContinueProxyContextProvider"; @@ -22,6 +22,7 @@ import SearchContextProvider from "./SearchContextProvider"; import TerminalContextProvider from "./TerminalContextProvider"; import URLContextProvider from "./URLContextProvider"; import RepoMapContextProvider from "./RepoMapContextProvider"; +import GreptileContextProvider from "./GreptileContextProvider"; /** * Note: We are currently omitting the following providers due to bugs: @@ -30,7 +31,7 @@ import RepoMapContextProvider from "./RepoMapContextProvider"; * * See this issue for details: https://github.com/continuedev/continue/issues/1365 */ -const Providers: (typeof BaseContextProvider)[] = [ +export const Providers: (typeof BaseContextProvider)[] = [ DiffContextProvider, FileTreeContextProvider, GitHubIssuesContextProvider, @@ -53,6 +54,7 @@ const Providers: (typeof BaseContextProvider)[] = [ URLContextProvider, ContinueProxyContextProvider, RepoMapContextProvider, + GreptileContextProvider, ]; export function contextProviderClassFromName( diff --git a/core/context/providers/utils.ts b/core/context/providers/utils.ts new file mode 100644 index 000000000..7bc20e491 --- /dev/null +++ b/core/context/providers/utils.ts @@ -0,0 +1,7 @@ +import { ContextItem } from "../.."; + +export const INSTRUCTIONS_BASE_ITEM: ContextItem = { + name: "Instructions", + description: "Instructions", + content: "", +}; diff --git a/core/context/rerankers/ContinueProxyReranker.ts b/core/context/rerankers/ContinueProxyReranker.ts index abeff24dc..1ca10436b 100644 --- a/core/context/rerankers/ContinueProxyReranker.ts +++ b/core/context/rerankers/ContinueProxyReranker.ts @@ -1,21 +1,15 @@ import fetch from "node-fetch"; -import { CONTROL_PLANE_URL } from "../../control-plane/client.js"; +import { ControlPlaneProxyInfo } from "../../control-plane/analytics/IAnalyticsProvider.js"; import { Chunk, Reranker } from "../../index.js"; export class ContinueProxyReranker implements Reranker { name = "continue-proxy"; - private _workOsAccessToken: string | undefined = undefined; + private _controlPlaneProxyInfo?: ControlPlaneProxyInfo; - get workOsAccessToken(): string | undefined { - return this._workOsAccessToken; - } - - set workOsAccessToken(value: string | undefined) { - if (this._workOsAccessToken !== value) { - this._workOsAccessToken = value; - this.params.apiKey = value!; - } + set controlPlaneProxyInfo(value: ControlPlaneProxyInfo) { + this.params.apiKey = value.workOsAccessToken!; + this._controlPlaneProxyInfo = value; } constructor( @@ -26,7 +20,10 @@ export class ContinueProxyReranker implements Reranker { ) {} async rerank(query: string, chunks: Chunk[]): Promise { - const url = new URL("/model-proxy/v1/rerank", CONTROL_PLANE_URL); + const url = new URL( + "openai/v1/rerank", + this._controlPlaneProxyInfo?.controlPlaneProxyUrl, + ); const resp = await fetch(url, { method: "POST", headers: { diff --git a/core/context/retrieval/repoMapRequest.ts b/core/context/retrieval/repoMapRequest.ts index 8d2eb9e4f..618be4808 100644 --- a/core/context/retrieval/repoMapRequest.ts +++ b/core/context/retrieval/repoMapRequest.ts @@ -1,6 +1,33 @@ import { Chunk, ContinueConfig, IDE, ILLM } from "../.."; +import { getModelByRole } from "../../config/util"; import { stripImages } from "../../llm/images"; -import generateRepoMap from "../../util/repoMap"; +import generateRepoMap from "../../util/generateRepoMap"; + +const SUPPORTED_MODEL_TITLE_FAMILIES = [ + "claude-3", + "llama3.1", + "gemini-1.5", + "gpt-4", +]; + +function isSupportedModel( + config: ContinueConfig, + modelTitle?: string, +): boolean { + if (config.experimental?.modelRoles?.applyCodeBlock) { + return true; + } + + if (!modelTitle) { + return false; + } + + const lowercaseModelTitle = modelTitle.toLowerCase(); + + return SUPPORTED_MODEL_TITLE_FAMILIES.some((title) => + lowercaseModelTitle.includes(title), + ); +} export async function requestFilesFromRepoMap( defaultLlm: ILLM, @@ -9,20 +36,16 @@ export async function requestFilesFromRepoMap( input: string, filterDirectory?: string, ): Promise { - const llm = - config.models.find( - (model) => - model.title === config.experimental?.modelRoles?.repoMapFileSelection, - ) ?? defaultLlm; + const llm = getModelByRole(config, "repoMapFileSelection") ?? defaultLlm; // Only supported for Claude models right now - if (!llm.model.toLowerCase().includes("claude")) { + if (!isSupportedModel(config, llm.title)) { return []; } try { const repoMap = await generateRepoMap(llm, ide, { - signatures: false, + includeSignatures: false, dirs: filterDirectory ? [filterDirectory] : undefined, }); diff --git a/core/context/retrieval/retrieval.ts b/core/context/retrieval/retrieval.ts index 34c6bd87c..9d19a33f7 100644 --- a/core/context/retrieval/retrieval.ts +++ b/core/context/retrieval/retrieval.ts @@ -1,14 +1,12 @@ -import { - BranchAndDir, - ContextItem, - ContextProviderExtras, -} from "../../index.js"; -import TransformersJsEmbeddingsProvider from "../../indexing/embeddings/TransformersJsEmbeddingsProvider.js"; -import { resolveRelativePathInWorkspace } from "../../util/ideUtils.js"; -import { getRelativePath } from "../../util/index.js"; -import { RetrievalPipelineOptions } from "./pipelines/BaseRetrievalPipeline.js"; -import NoRerankerRetrievalPipeline from "./pipelines/NoRerankerRetrievalPipeline.js"; -import RerankerRetrievalPipeline from "./pipelines/RerankerRetrievalPipeline.js"; +import { BranchAndDir, ContextItem, ContextProviderExtras } from "../../"; +import TransformersJsEmbeddingsProvider from "../../indexing/embeddings/TransformersJsEmbeddingsProvider"; +import { resolveRelativePathInWorkspace } from "../../util/ideUtils"; +import { getRelativePath } from "../../util/"; +import { INSTRUCTIONS_BASE_ITEM } from "../providers/utils"; +import { RetrievalPipelineOptions } from "./pipelines/BaseRetrievalPipeline"; +import NoRerankerRetrievalPipeline from "./pipelines/NoRerankerRetrievalPipeline"; +import RerankerRetrievalPipeline from "./pipelines/RerankerRetrievalPipeline"; +import path from "path"; export async function retrieveContextItemsFromEmbeddings( extras: ContextProviderExtras, @@ -97,22 +95,32 @@ export async function retrieveContextItemsFromEmbeddings( } return [ - ...results.map((r) => { - const name = `${getRelativePath(r.filepath, workspaceDirs)} (${ - r.startLine - }-${r.endLine})`; - const description = `${r.filepath} (${r.startLine}-${r.endLine})`; - return { - name, - description, - content: `\`\`\`${name}\n${r.content}\n\`\`\``, - }; - }), { - name: "Instructions", - description: "Instructions", + ...INSTRUCTIONS_BASE_ITEM, content: "Use the above code to answer the following question. You should not reference any files outside of what is shown, unless they are commonly known files, like a .gitignore or package.json. Reference the filenames whenever possible. If there isn't enough information to answer the question, suggest where the user might look to learn more.", }, + ...results + .sort((a, b) => a.filepath.localeCompare(b.filepath)) + .map((r) => { + const name = `${path.basename(r.filepath)} (${r.startLine}-${ + r.endLine + })`; + const description = `${r.filepath}`; + + if (r.filepath.includes("package.json")) { + console.log(); + } + + return { + name, + description, + content: `\`\`\`${name}\n${r.content}\n\`\`\``, + uri: { + type: "file" as const, + value: r.filepath, + }, + }; + }), ]; } diff --git a/core/control-plane/TeamAnalytics.ts b/core/control-plane/TeamAnalytics.ts index f39bc261e..e6ad9e364 100644 --- a/core/control-plane/TeamAnalytics.ts +++ b/core/control-plane/TeamAnalytics.ts @@ -1,7 +1,10 @@ import { Analytics } from "@continuedev/config-types"; import os from "node:os"; import ContinueProxyAnalyticsProvider from "./analytics/ContinueProxyAnalyticsProvider.js"; -import { IAnalyticsProvider } from "./analytics/IAnalyticsProvider.js"; +import { + ControlPlaneProxyInfo, + IAnalyticsProvider, +} from "./analytics/IAnalyticsProvider.js"; import LogStashAnalyticsProvider from "./analytics/LogStashAnalyticsProvider.js"; import PostHogAnalyticsProvider from "./analytics/PostHogAnalyticsProvider.js"; import { ControlPlaneClient } from "./client.js"; @@ -41,7 +44,7 @@ export class TeamAnalytics { uniqueId: string, extensionVersion: string, controlPlaneClient: ControlPlaneClient, - workspaceId?: string, + controlPlaneProxyInfo: ControlPlaneProxyInfo, ) { TeamAnalytics.uniqueId = uniqueId; TeamAnalytics.os = os.platform(); @@ -52,7 +55,11 @@ export class TeamAnalytics { TeamAnalytics.provider = undefined; } else { TeamAnalytics.provider = createAnalyticsProvider(config); - await TeamAnalytics.provider?.setup(config, uniqueId, workspaceId); + await TeamAnalytics.provider?.setup( + config, + uniqueId, + controlPlaneProxyInfo, + ); if (config.provider === "continue-proxy") { ( diff --git a/core/control-plane/analytics/ContinueProxyAnalyticsProvider.ts b/core/control-plane/analytics/ContinueProxyAnalyticsProvider.ts index de9d9efbe..284a3ce3e 100644 --- a/core/control-plane/analytics/ContinueProxyAnalyticsProvider.ts +++ b/core/control-plane/analytics/ContinueProxyAnalyticsProvider.ts @@ -1,13 +1,16 @@ import { Analytics } from "@continuedev/config-types"; import fetch from "node-fetch"; -import { CONTROL_PLANE_URL, ControlPlaneClient } from "../client.js"; -import { IAnalyticsProvider } from "./IAnalyticsProvider.js"; +import { ControlPlaneClient } from "../client.js"; +import { + ControlPlaneProxyInfo, + IAnalyticsProvider, +} from "./IAnalyticsProvider.js"; export default class ContinueProxyAnalyticsProvider implements IAnalyticsProvider { uniqueId?: string; - workspaceId?: string; + controlPlaneProxyInfo?: ControlPlaneProxyInfo; controlPlaneClient?: ControlPlaneClient; @@ -16,8 +19,8 @@ export default class ContinueProxyAnalyticsProvider properties: { [key: string]: any }, ): Promise { const url = new URL( - `proxy/analytics/${this.workspaceId}/capture`, - CONTROL_PLANE_URL, + `proxy/analytics/${this.controlPlaneProxyInfo?.workspaceId}/capture`, + this.controlPlaneProxyInfo?.controlPlaneProxyUrl, ).toString(); fetch(url, { method: "POST", @@ -35,10 +38,10 @@ export default class ContinueProxyAnalyticsProvider async setup( config: Analytics, uniqueId: string, - workspaceId?: string, + controlPlaneProxyInfo?: ControlPlaneProxyInfo, ): Promise { this.uniqueId = uniqueId; - this.workspaceId = workspaceId; + this.controlPlaneProxyInfo = controlPlaneProxyInfo; } async shutdown(): Promise {} diff --git a/core/control-plane/analytics/IAnalyticsProvider.ts b/core/control-plane/analytics/IAnalyticsProvider.ts index 1bb2a727c..c069695d0 100644 --- a/core/control-plane/analytics/IAnalyticsProvider.ts +++ b/core/control-plane/analytics/IAnalyticsProvider.ts @@ -4,12 +4,18 @@ export interface AnalyticsMetadata { extensionVersion: string; } +export interface ControlPlaneProxyInfo { + workspaceId?: string; + controlPlaneProxyUrl: string; + workOsAccessToken?: string; +} + export interface IAnalyticsProvider { capture(event: string, properties: { [key: string]: any }): Promise; setup( config: Analytics, uniqueId: string, - workspaceId?: string, + controlPlaneProxyInfo?: ControlPlaneProxyInfo, ): Promise; shutdown(): Promise; } diff --git a/core/control-plane/analytics/LogStashAnalyticsProvider.ts b/core/control-plane/analytics/LogStashAnalyticsProvider.ts index ccf445474..3a94bd9d6 100644 --- a/core/control-plane/analytics/LogStashAnalyticsProvider.ts +++ b/core/control-plane/analytics/LogStashAnalyticsProvider.ts @@ -1,6 +1,9 @@ import { Analytics } from "@continuedev/config-types"; import net from "node:net"; -import { IAnalyticsProvider } from "./IAnalyticsProvider.js"; +import { + ControlPlaneProxyInfo, + IAnalyticsProvider, +} from "./IAnalyticsProvider.js"; export default class LogStashAnalyticsProvider implements IAnalyticsProvider { private host?: string; @@ -31,7 +34,7 @@ export default class LogStashAnalyticsProvider implements IAnalyticsProvider { async setup( config: Analytics, uniqueId: string, - workspaceId?: string, + controlPlaneProxyInfo?: ControlPlaneProxyInfo, ): Promise { if (!config.url) { console.warn("LogStashAnalyticsProvider is missing a URL"); diff --git a/core/control-plane/analytics/PostHogAnalyticsProvider.ts b/core/control-plane/analytics/PostHogAnalyticsProvider.ts index ecb4e071a..db8ac1065 100644 --- a/core/control-plane/analytics/PostHogAnalyticsProvider.ts +++ b/core/control-plane/analytics/PostHogAnalyticsProvider.ts @@ -1,5 +1,8 @@ import { Analytics } from "@continuedev/config-types"; -import { IAnalyticsProvider } from "./IAnalyticsProvider.js"; +import { + ControlPlaneProxyInfo, + IAnalyticsProvider, +} from "./IAnalyticsProvider.js"; export default class PostHogAnalyticsProvider implements IAnalyticsProvider { client?: any; @@ -19,7 +22,7 @@ export default class PostHogAnalyticsProvider implements IAnalyticsProvider { async setup( config: Analytics, uniqueId: string, - workspaceId?: string, + controlPlaneProxyInfo?: ControlPlaneProxyInfo, ): Promise { if (!config || !config.clientKey || !config.url) { this.client = undefined; diff --git a/core/control-plane/client.ts b/core/control-plane/client.ts index d34ac5ff8..25ae3e962 100644 --- a/core/control-plane/client.ts +++ b/core/control-plane/client.ts @@ -18,6 +18,11 @@ export interface ControlPlaneWorkspace { export interface ControlPlaneModelDescription extends ModelDescription {} +export const DEFAULT_CONTROL_PLANE_PROXY_URL = + process.env.CONTROL_PLANE_ENV === "local" + ? "http://localhost:3001/" + : "https://control-plane-proxy.continue.dev/"; + export const CONTROL_PLANE_URL = process.env.CONTROL_PLANE_ENV === "local" ? "http://localhost:3001/" diff --git a/core/core.ts b/core/core.ts index 7148c8c15..ebd08f3bf 100644 --- a/core/core.ts +++ b/core/core.ts @@ -14,6 +14,7 @@ import { recentlyEditedFilesCache } from "./context/retrieval/recentlyEditedFile import { ContinueServerClient } from "./continueServer/stubs/client"; import { getAuthUrlForTokenPage } from "./control-plane/auth/index"; import { ControlPlaneClient } from "./control-plane/client"; +import { streamDiffLines } from "./edit/streamDiffLines"; import { CodebaseIndexer, PauseToken } from "./indexing/CodebaseIndexer"; import DocsService from "./indexing/docs/DocsService"; import Ollama from "./llm/llms/Ollama"; @@ -27,7 +28,6 @@ import type { IMessenger, Message } from "./util/messenger"; import { editConfigJson } from "./util/paths"; import { Telemetry } from "./util/posthog"; import { TTS } from "./util/tts"; -import { streamDiffLines } from "./util/verticalEdit"; export class Core { // implements IMessenger @@ -119,7 +119,7 @@ export class Core { (resolve) => (continueServerClientResolve = resolve), ); - ideSettingsPromise.then((ideSettings) => { + void ideSettingsPromise.then((ideSettings) => { const continueServerClient = new ContinueServerClient( ideSettings.remoteConfigServerUrl, ideSettings.userToken, @@ -136,18 +136,18 @@ export class Core { ); // Index on initialization - this.ide.getWorkspaceDirs().then(async (dirs) => { + void this.ide.getWorkspaceDirs().then(async (dirs) => { // Respect pauseCodebaseIndexOnStart user settings if (ideSettings.pauseCodebaseIndexOnStart) { await this.messenger.request("indexProgress", { - progress: 100, + progress: 1, desc: "Initial Indexing Skipped", status: "paused", }); return; } - this.refreshCodebaseIndex(dirs); + void this.refreshCodebaseIndex(dirs); }); }); @@ -172,11 +172,11 @@ export class Core { this.messenger.onError((err) => { console.error(err); - Telemetry.capture("core_messenger_error", { + void Telemetry.capture("core_messenger_error", { message: err.message, stack: err.stack, }); - this.ide.showToast("error", err.message); + void this.ide.showToast("error", err.message); }); // New @@ -186,7 +186,7 @@ export class Core { on("update/selectTabAutocompleteModel", async (msg) => { this.globalContext.update("selectedTabAutocompleteModel", msg.data); - this.configHandler.reloadConfig(); + void this.configHandler.reloadConfig(); }); // Special @@ -226,30 +226,30 @@ export class Core { // Edit config on("config/addModel", (msg) => { const model = msg.data.model; - addModel(model); - this.configHandler.reloadConfig(); + addModel(model, msg.data.role); + void this.configHandler.reloadConfig(); }); on("config/addOpenAiKey", (msg) => { addOpenAIKey(msg.data); - this.configHandler.reloadConfig(); + void this.configHandler.reloadConfig(); }); on("config/deleteModel", (msg) => { deleteModel(msg.data.title); - this.configHandler.reloadConfig(); + void this.configHandler.reloadConfig(); }); on("config/newPromptFile", async (msg) => { - createNewPromptFile( + void createNewPromptFile( this.ide, (await this.config()).experimental?.promptPath, ); - this.configHandler.reloadConfig(); + void this.configHandler.reloadConfig(); }); on("config/reload", (msg) => { - this.configHandler.reloadConfig(); + void this.configHandler.reloadConfig(); return this.configHandler.getSerializedConfig(); }); @@ -272,9 +272,12 @@ export class Core { } if (hasFailed) { - this.ide.showToast("info", `Failed to index ${msg.data.startUrl}`); + void this.ide.showToast("info", `Failed to index ${msg.data.startUrl}`); } else { - this.ide.showToast("info", `Successfully indexed ${msg.data.startUrl}`); + void this.ide.showToast( + "info", + `Successfully indexed ${msg.data.startUrl}`, + ); this.messenger.send("refreshSubmenuItems", undefined); } }); @@ -331,7 +334,7 @@ export class Core { fetchwithRequestOptions(url, init, config.requestOptions), }); - Telemetry.capture( + void Telemetry.capture( "useContextProvider", { name: provider.description.title, @@ -344,7 +347,7 @@ export class Core { id, })); } catch (e) { - this.ide.showToast( + void this.ide.showToast( "error", `Error getting context items from ${name}: ${e}`, ); @@ -368,7 +371,7 @@ export class Core { // Stop TTS on new StreamChat if (config.experimental?.readResponseTTS) { - TTS.kill(); + void TTS.kill(); } const model = await configHandler.llmFromTitle(msg.data.title); @@ -396,7 +399,7 @@ export class Core { } if (config.experimental?.readResponseTTS && "completion" in next.value) { - TTS.read(next.value?.completion); + void TTS.read(next.value?.completion); } return { done: true, content: next.value }; @@ -477,7 +480,7 @@ export class Core { TTS.messenger = this.messenger; on("tts/kill", async () => { - TTS.kill(); + void TTS.kill(); }); async function* runNodeJsSlashCommand( @@ -506,7 +509,7 @@ export class Core { throw new Error(`Unknown slash command ${slashCommandName}`); } - Telemetry.capture( + void Telemetry.capture( "useSlashCommand", { name: slashCommandName, @@ -529,7 +532,7 @@ export class Core { params, ide, addContextItem: (item) => { - messenger.request("addContextItem", { + void messenger.request("addContextItem", { item, historyIndex, }); @@ -568,7 +571,9 @@ export class Core { ); return outcome ? [outcome.completion] : []; }); - on("autocomplete/accept", async (msg) => {}); + on("autocomplete/accept", async (msg) => { + this.completionProvider.accept(msg.data.completionId); + }); on("autocomplete/cancel", async (msg) => { this.completionProvider.cancel(); }); @@ -636,7 +641,7 @@ export class Core { editConfigJson(editConfigJsonCallback); - this.configHandler.reloadConfig(); + void this.configHandler.reloadConfig(); }); on("addAutocompleteModel", (msg) => { @@ -646,7 +651,7 @@ export class Core { tabAutocompleteModel: msg.data.model, }; }); - this.configHandler.reloadConfig(); + void this.configHandler.reloadConfig(); }); on("stats/getTokensPerDay", async (msg) => { @@ -674,13 +679,13 @@ export class Core { // Triggered when progress bar is initialized. // If a non-default state has been stored, update the indexing display to that state if (this.indexingState.status !== "loading") { - this.messenger.request("indexProgress", this.indexingState); + void this.messenger.request("indexProgress", this.indexingState); } }); on("didChangeSelectedProfile", (msg) => { - this.configHandler.setSelectedProfile(msg.data.id); - this.configHandler.reloadConfig(); + void this.configHandler.setSelectedProfile(msg.data.id); + void this.configHandler.reloadConfig(); }); on("didChangeControlPlaneSessionInfo", async (msg) => { this.configHandler.updateControlPlaneSessionInfo(msg.data.sessionInfo); @@ -713,7 +718,7 @@ export class Core { updateToSend.progress = 1.0; } - this.messenger.request("indexProgress", updateToSend); + void this.messenger.request("indexProgress", updateToSend); this.indexingState = updateToSend; if (update.status === "failed") { @@ -722,7 +727,7 @@ export class Core { update.desc, update.debugInfo, ); - Telemetry.capture( + void Telemetry.capture( "indexing_error", { error: update.desc, diff --git a/core/diff/myers.test.ts b/core/diff/myers.test.ts new file mode 100644 index 000000000..5d68cfabf --- /dev/null +++ b/core/diff/myers.test.ts @@ -0,0 +1,23 @@ +import { dedent } from "../util"; +import { myersDiff } from "./myers"; + +describe("Test myers diff function", () => { + test("should ...", () => { + const linesA = dedent` + A + B + C + D + E + `; + const linesB = dedent` + A + B + C' + D' + E + `; + const diffLines = myersDiff(linesA, linesB); + console.log(diffLines); + }); +}); diff --git a/core/diff/myers.ts b/core/diff/myers.ts new file mode 100644 index 000000000..06b0ce7ec --- /dev/null +++ b/core/diff/myers.ts @@ -0,0 +1,25 @@ +import { diffLines, type Change } from "diff"; +import { DiffLine } from ".."; + +export function convertMyersChangeToDiffLines(change: Change): DiffLine[] { + const type: DiffLine["type"] = change.added + ? "new" + : change.removed + ? "old" + : "same"; + const lines = change.value.split("\n"); + + // `diff` package is always adding an extra new line at the end of the array + if (lines[lines.length - 1] === "") { + lines.pop(); + } + + return lines.map((line) => ({ type, line })); +} + +export function myersDiff(oldContent: string, newContent: string): DiffLine[] { + const theirFormat = diffLines(oldContent, newContent); + const ourFormat = theirFormat.flatMap(convertMyersChangeToDiffLines); + + return ourFormat; +} diff --git a/core/diff/streamDiff.test.ts b/core/diff/streamDiff.test.ts index 0ad669280..0b884369e 100644 --- a/core/diff/streamDiff.test.ts +++ b/core/diff/streamDiff.test.ts @@ -4,6 +4,7 @@ import { DiffLine, DiffLineType } from "../index.js"; // @ts-ignore no typings available import { changed, diff as myersDiff } from "myers-diff"; import path from "node:path"; +import { generateLines } from "./util.js"; // "modification" is an extra type used to represent an "old" + "new" diff line type MyersDiffTypes = Extract | "modification"; @@ -14,12 +15,6 @@ const UNIFIED_DIFF_SYMBOLS = { old: "-", }; -async function* generateLines(lines: string[]): AsyncGenerator { - for (const line of lines) { - yield line; - } -} - async function collectDiffs( oldLines: string[], newLines: string[], @@ -224,18 +219,18 @@ describe("streamDiff(", () => { }); test("tabs vs. spaces differences are ignored", async () => { - await expectDiff("fastapi-tabs-vs-spaces"); + await expectDiff("fastapi-tabs-vs-spaces.py"); }); test("FastAPI example", async () => { - await expectDiff("fastapi"); + await expectDiff("fastapi.py"); }); test("FastAPI comments", async () => { - await expectDiff("add-comments"); + await expectDiff("add-comments.py"); }); test("Mock LLM example", async () => { - await expectDiff("mock-llm"); + await expectDiff("mock-llm.ts"); }); }); diff --git a/core/diff/test-examples/add-comments.diff b/core/diff/test-examples/add-comments.py.diff similarity index 100% rename from core/diff/test-examples/add-comments.diff rename to core/diff/test-examples/add-comments.py.diff diff --git a/core/diff/test-examples/fastapi-tabs-vs-spaces.diff b/core/diff/test-examples/fastapi-tabs-vs-spaces.py.diff similarity index 100% rename from core/diff/test-examples/fastapi-tabs-vs-spaces.diff rename to core/diff/test-examples/fastapi-tabs-vs-spaces.py.diff diff --git a/core/diff/test-examples/fastapi.diff b/core/diff/test-examples/fastapi.py.diff similarity index 100% rename from core/diff/test-examples/fastapi.diff rename to core/diff/test-examples/fastapi.py.diff diff --git a/core/diff/test-examples/mock-llm.diff b/core/diff/test-examples/mock-llm.ts.diff similarity index 100% rename from core/diff/test-examples/mock-llm.diff rename to core/diff/test-examples/mock-llm.ts.diff diff --git a/core/diff/util.ts b/core/diff/util.ts index 0e24ee373..6d218bcbf 100644 --- a/core/diff/util.ts +++ b/core/diff/util.ts @@ -93,19 +93,38 @@ export function matchLine( */ export async function* streamLines( streamCompletion: AsyncGenerator, + log: boolean = false, ): LineStream { + let allLines = []; + let buffer = ""; - for await (const update of streamCompletion) { - const chunk = - typeof update === "string" ? update : stripImages(update.content); - buffer += chunk; - const lines = buffer.split("\n"); - buffer = lines.pop() ?? ""; - for (const line of lines) { - yield line; + + try { + for await (const update of streamCompletion) { + const chunk = + typeof update === "string" ? update : stripImages(update.content); + buffer += chunk; + const lines = buffer.split("\n"); + buffer = lines.pop() ?? ""; + for (const line of lines) { + yield line; + allLines.push(line); + } + } + if (buffer.length > 0) { + yield buffer; + allLines.push(buffer); + } + } finally { + if (log) { + console.log("Streamed lines: ", allLines.join("\n")); } } - if (buffer.length > 0) { - yield buffer; +} + +export async function* generateLines(lines: T[]): AsyncGenerator { + for (const line of lines) { + yield line; + // await new Promise((resolve, reject) => setTimeout(() => resolve(null), 50)); } } diff --git a/core/edit/lazy/applyCodeBlock.ts b/core/edit/lazy/applyCodeBlock.ts new file mode 100644 index 000000000..3a0083d65 --- /dev/null +++ b/core/edit/lazy/applyCodeBlock.ts @@ -0,0 +1,35 @@ +import path from "path"; +import { DiffLine, ILLM } from "../.."; +import { generateLines } from "../../diff/util"; +import { supportedLanguages } from "../../util/treeSitter"; +import { deterministicApplyLazyEdit } from "./deterministic"; +import { streamLazyApply } from "./streamLazyApply"; + +function canUseInstantApply(filename: string) { + const fileExtension = path.extname(filename).toLowerCase().slice(1); + return supportedLanguages[fileExtension] !== undefined; +} + +export async function applyCodeBlock( + oldFile: string, + newFile: string, + filename: string, + llm: ILLM, + fastLlm: ILLM, +): Promise<[boolean, AsyncGenerator]> { + if (canUseInstantApply(filename)) { + const diffLines = await deterministicApplyLazyEdit( + oldFile, + newFile, + filename, + ); + + // Fall back to LLM method if we couldn't apply deterministically + if (diffLines !== undefined) { + const diffGenerator = generateLines(diffLines!); + return [true, diffGenerator]; + } + } + + return [false, streamLazyApply(oldFile, filename, newFile, llm, fastLlm)]; +} diff --git a/core/edit/lazy/deterministic.test.ts b/core/edit/lazy/deterministic.test.ts new file mode 100644 index 000000000..7194c0083 --- /dev/null +++ b/core/edit/lazy/deterministic.test.ts @@ -0,0 +1,161 @@ +import fs from "node:fs"; + +// @ts-ignore no typings available +import { diff as myersDiff } from "myers-diff"; +import path from "node:path"; +import { DiffLine } from "../.."; +import { myersDiff as continueMyersDiff } from "../../diff/myers"; +import { dedent } from "../../util"; +import { deterministicApplyLazyEdit } from "./deterministic"; + +const UNIFIED_DIFF_SYMBOLS = { + same: "", + new: "+", + old: "-", +}; + +async function collectDiffs( + oldFile: string, + newFile: string, + filename: string, +): Promise<{ ourDiffs: DiffLine[]; myersDiffs: any }> { + const ourDiffs: DiffLine[] = []; + + for (const diffLine of (await deterministicApplyLazyEdit( + oldFile, + newFile, + filename, + )) ?? []) { + ourDiffs.push(diffLine); + } + + const myersDiffs = myersDiff(oldFile, newFile); + + return { ourDiffs, myersDiffs }; +} + +function displayDiff(diff: DiffLine[]) { + return diff + .map(({ type, line }) => + type === "same" ? line : `${UNIFIED_DIFF_SYMBOLS[type]} ${line}`, + ) + .join("\n"); +} + +function normalizeDisplayedDiff(d: string): string { + return d + .split("\n") + .map((line) => (line.trim() === "" ? "" : line)) + .join("\n"); +} + +async function expectDiff(file: string) { + const testFilePath = path.join( + __dirname, + "edit", + "lazy", + "test-examples", + file + ".diff", + ); + const testFileContents = fs.readFileSync(testFilePath, "utf-8"); + const [oldFile, newFile, expectedDiff] = testFileContents + .split("\n---\n") + .map((s) => s.replace(/^\n+/, "").trimEnd()); + const { ourDiffs: streamDiffs } = await collectDiffs(oldFile, newFile, file); + const displayedDiff = displayDiff(streamDiffs); + + if (!expectedDiff || expectedDiff.trim() === "") { + console.log( + "Expected diff was empty. Writing computed diff to the test file", + ); + fs.writeFileSync( + testFilePath, + `${oldFile}\n\n---\n\n${newFile}\n\n---\n\n${displayDiff( + continueMyersDiff(oldFile, newFile), + )}`, + ); + + throw new Error("Expected diff is empty"); + } + + expect(normalizeDisplayedDiff(displayedDiff)).toEqual( + normalizeDisplayedDiff(expectedDiff), + ); +} + +describe("deterministicApplyLazyEdit(", () => { + test("no changes", async () => { + const file = dedent` + function test() { + return 1; + } + + function test2(a) { + return a * 2; + } + `; + + const { ourDiffs: streamDiffs, myersDiffs } = await collectDiffs( + file, + file, + "test.js", + ); + + expect(streamDiffs).toEqual( + file.split("\n").map((line) => ({ + line, + type: "same", + })), + ); + + expect(myersDiffs).toEqual([]); + }); + + test("fastapi", async () => { + await expectDiff("fastapi.py"); + }); + + test("calculator exp", async () => { + await expectDiff("calculator-exp.js"); + }); + + test("calculator exp2", async () => { + await expectDiff("calculator-exp2.js"); + }); + + test("calculator comments", async () => { + await expectDiff("calculator-comments.js"); + }); + + test("calculator docstrings", async () => { + await expectDiff("calculator-docstrings.js"); + }); + + test("calculator stateless", async () => { + await expectDiff("calculator-stateless.js"); + }); + + test("top level same blocks", async () => { + await expectDiff("top-level-same.js"); + }); + + test.skip("gui add toggle", async () => { + await expectDiff("gui.js"); + }); + + test("rust calculator", async () => { + await expectDiff("rust-calc-exp.rs"); + }); + + test("no lazy blocks", async () => { + await expectDiff("no-lazy.js"); + }); + + test("no lazy blocks in single top level class", async () => { + await expectDiff("no-lazy-single-class.js"); + }); + + test("should acknowledge jsx_expression lazy comments", async () => { + await expectDiff("migration-page.tsx"); + }); +}); diff --git a/core/edit/lazy/deterministic.ts b/core/edit/lazy/deterministic.ts new file mode 100644 index 000000000..e9cbdf921 --- /dev/null +++ b/core/edit/lazy/deterministic.ts @@ -0,0 +1,323 @@ +import { distance } from "fastest-levenshtein"; +import path from "path"; +import Parser from "web-tree-sitter"; +import { DiffLine } from "../.."; +import { LANGUAGES } from "../../autocomplete/languages"; +import { myersDiff } from "../../diff/myers"; +import { getParserForFile } from "../../util/treeSitter"; +import { findInAst } from "./findInAst"; + +type AstReplacements = Array<{ + nodeToReplace: Parser.SyntaxNode; + replacementNodes: Parser.SyntaxNode[]; +}>; + +function reconstructNewFile( + oldFile: string, + newFile: string, + lazyBlockReplacements: AstReplacements, +): string { + // Sort acc by reverse line number + lazyBlockReplacements + .sort((a, b) => a.nodeToReplace.startIndex - b.nodeToReplace.startIndex) + .reverse(); + + // Reconstruct entire file by replacing lazy blocks with the replacement nodes + const oldFileLines = oldFile.split("\n"); + const newFileChars = newFile.split(""); + for (const { + nodeToReplace: lazyBlockNode, + replacementNodes, + } of lazyBlockReplacements) { + // Get the full string from the replacement nodes + let replacementText = ""; + if (replacementNodes.length > 0) { + const startPosition = replacementNodes[0].startPosition; + const endPosition = + replacementNodes[replacementNodes.length - 1].endPosition; + const replacementLines = oldFileLines.slice( + startPosition.row, + endPosition.row + 1, + ); + replacementLines[0] = replacementLines[0].slice(startPosition.column); + replacementLines[replacementLines.length - 1] = replacementLines[ + replacementLines.length - 1 + ].slice(0, endPosition.column); + replacementText = replacementLines.join("\n"); + + // Replace the lazy block + newFileChars.splice( + lazyBlockNode.startIndex, + lazyBlockNode.text.length, + replacementText, + ); + } else { + // If there are no replacements, then we want to strip the surrounding whitespace + // The example in calculator-exp.js.diff is a test where this is necessary + const lazyBlockStart = lazyBlockNode.startIndex; + const lazyBlockEnd = lazyBlockNode.endIndex - 1; + + // Remove leading whitespace up to two new lines + let startIndex = lazyBlockStart; + let newLinesFound = 0; + while ( + startIndex > 0 && + newFileChars[startIndex - 1]?.trim() === "" && + newLinesFound < 2 + ) { + startIndex--; + if (newFileChars[startIndex - 1] === "\n") { + newLinesFound++; + } + } + + // Remove trailing whitespace up to two new lines + const charAfter = newFileChars[lazyBlockEnd + 1]; + const secondCharAfter = newFileChars[lazyBlockEnd + 2]; + let endIndex = lazyBlockEnd; + if (charAfter === "\n") { + endIndex++; + if (secondCharAfter === "\n") { + endIndex++; + } + } + + // Remove the lazy block + newFileChars.splice(startIndex, endIndex - startIndex + 1); + } + } + + return newFileChars.join(""); +} + +const REMOVAL_PERCENTAGE_THRESHOLD = 0.3; +function shouldRejectDiff(diff: DiffLine[]): boolean { + const numRemovals = diff.filter((line) => line.type === "old").length; + if (numRemovals / diff.length > REMOVAL_PERCENTAGE_THRESHOLD) { + return true; + } + return false; +} + +// TODO: If we don't have high confidence, return undefined to fall back to slower methods +export async function deterministicApplyLazyEdit( + oldFile: string, + newLazyFile: string, + filename: string, +): Promise { + const parser = await getParserForFile(filename); + if (!parser) { + return undefined; + } + + const oldTree = parser.parse(oldFile); + let newTree = parser.parse(newLazyFile); + + // If there is no lazy block anywhere, we add our own to the outsides + // so that large chunks of the file don't get removed + if (!findInAst(newTree.rootNode, isLazyBlock)) { + // First, we need to check whether there are matching (similar) nodes at the root level + const firstSimilarNode = findInAst(oldTree.rootNode, (node) => + nodesAreSimilar(node, newTree.rootNode.children[0]), + ); + if (firstSimilarNode?.parent?.equals(oldTree.rootNode)) { + // If so, we tack lazy blocks to start and end, and run the usual algorithm + const ext = path.extname(filename).slice(1); + const language = LANGUAGES[ext]; + if (language) { + newLazyFile = `${language.singleLineComment} ... existing code ...\n\n${newLazyFile}\n\n${language.singleLineComment} ... existing code...`; + newTree = parser.parse(newLazyFile); + } + } else { + // If not, we need to recursively search for the nodes that are being rewritten, + // and we apply a slightly different algorithm + return undefined; // TODO + } + } + + const replacements: AstReplacements = []; + findLazyBlockReplacements(oldTree.rootNode, newTree.rootNode, replacements); + + const newFullFile = reconstructNewFile(oldFile, newLazyFile, replacements); + const diff = myersDiff(oldFile, newFullFile); + + // If the diff is too messy and seems likely borked, we fall back to LLM strategy + if (shouldRejectDiff(diff)) { + return undefined; + } + + return diff; +} + +const LAZY_COMMENT_REGEX = /\.{3}\s*(.+?)\s*\.{3}/; +export function isLazyLine(text: string): boolean { + return LAZY_COMMENT_REGEX.test(text); +} + +function isLazyBlock(node: Parser.SyntaxNode): boolean { + // Special case for "{/* ... existing code ... */}" + if ( + node.type === "jsx_expression" && + node.namedChildCount === 1 && + isLazyBlock(node.namedChildren[0]) + ) { + return true; + } + + return node.type.includes("comment") && isLazyLine(node.text); +} + +function stringsWithinLevDistThreshold( + a: string, + b: string, + threshold: number, +) { + const dist = distance(a, b); + return dist / Math.min(a.length, b.length) <= threshold; +} + +/** + * Determine whether two nodes are similar + * @param a + * @param b + * @returns + */ +function nodesAreSimilar(a: Parser.SyntaxNode, b: Parser.SyntaxNode): boolean { + if (a.type !== b.type) { + return false; + } + + // Check if they have the same name + if ( + a.childForFieldName("name") !== null && + a.childForFieldName("name")?.text === b.childForFieldName("name")?.text + ) { + return true; + } + + if ( + a.namedChildren[0]?.text === b.namedChildren[0]?.text && + a.children[1]?.text === b.children[1]?.text + ) { + return true; + } + + // Matching jsx_elements needs to be different because they have such a minimal first line + if ( + a.type === "jsx_element" && + b.type === "jsx_element" && + // Check that the tag names match + a.namedChildren[0]?.children[1]?.text === + b.namedChildren[0]?.children[1]?.text + ) { + if (stringsWithinLevDistThreshold(a.text, b.text, 0.3)) { + return true; + } + } + + const lineOneA = a.text.split("\n")[0]; + const lineOneB = b.text.split("\n")[0]; + + return stringsWithinLevDistThreshold(lineOneA, lineOneB, 0.2); +} + +function nodesAreExact(a: Parser.SyntaxNode, b: Parser.SyntaxNode): boolean { + return a.text === b.text; +} + +/** + * Should be like Myers diff, but lazy blocks consume all nodes until the next match + * @param newNode + * @param oldNode + * @returns + */ +function findLazyBlockReplacements( + oldNode: Parser.SyntaxNode, + newNode: Parser.SyntaxNode, + replacements: AstReplacements, +): void { + // Base case + if (nodesAreExact(oldNode, newNode)) { + return; + } + + // Other base case: no lazy blocks => use line-by-line diff + if (!findInAst(newNode, isLazyBlock)) { + return; + } + + const leftChildren = oldNode.namedChildren; + const rightChildren = newNode.namedChildren; + let isLazy = false; + let currentLazyBlockNode: Parser.SyntaxNode | undefined = undefined; + const currentLazyBlockReplacementNodes = []; + + while (leftChildren.length > 0 && rightChildren.length > 0) { + const L = leftChildren[0]; + const R = rightChildren[0]; + + // Consume lazy block + if (isLazyBlock(R)) { + // Enter "lazy mode" + isLazy = true; + currentLazyBlockNode = R; + rightChildren.shift(); + continue; + } + + // Look for the first match of L + const index = rightChildren.findIndex((node) => nodesAreSimilar(L, node)); + + if (index === -1) { + // No match + if (isLazy) { + // Add to replacements if in lazy mode + currentLazyBlockReplacementNodes.push(L); + } + + // Consume + leftChildren.shift(); + } else { + // Match found, insert all right nodes before the match + for (let i = 0; i < index; i++) { + rightChildren.shift(); + } + + // then recurse at the match + findLazyBlockReplacements(L, rightChildren[0], replacements); + + // then consume L and R + leftChildren.shift(); + rightChildren.shift(); + + // Exit "lazy mode" + if (isLazy) { + // Record the replacement lines + replacements.push({ + nodeToReplace: currentLazyBlockNode!, + replacementNodes: [...currentLazyBlockReplacementNodes], + }); + isLazy = false; + currentLazyBlockReplacementNodes.length = 0; + currentLazyBlockNode = undefined; + } + } + } + + if (isLazy) { + replacements.push({ + nodeToReplace: currentLazyBlockNode!, + replacementNodes: [...currentLazyBlockReplacementNodes, ...leftChildren], + }); + } + + // Cut out any extraneous lazy blocks + for (const R of rightChildren) { + if (isLazyBlock(R)) { + replacements.push({ + nodeToReplace: R, + replacementNodes: [], + }); + } + } +} diff --git a/core/edit/lazy/findInAst.ts b/core/edit/lazy/findInAst.ts new file mode 100644 index 000000000..9f47355b8 --- /dev/null +++ b/core/edit/lazy/findInAst.ts @@ -0,0 +1,16 @@ +import Parser from "web-tree-sitter"; + +export function findInAst( + node: Parser.SyntaxNode, + criterion: (node: Parser.SyntaxNode) => boolean, +): Parser.SyntaxNode | null { + const stack = [node]; + while (stack.length > 0) { + let node = stack.pop()!; + if (criterion(node)) { + return node; + } + stack.push(...node.children); + } + return null; +} diff --git a/core/edit/lazy/prompts.ts b/core/edit/lazy/prompts.ts new file mode 100644 index 000000000..9b8d6abb9 --- /dev/null +++ b/core/edit/lazy/prompts.ts @@ -0,0 +1,62 @@ +import { ChatMessage, ModelProvider } from "../.."; +import { dedent } from "../../util"; + +export const UNCHANGED_CODE = "UNCHANGED CODE"; + +type LazyApplyPrompt = ( + oldCode: string, + filename: string, + newCode: string, +) => ChatMessage[]; + +const RULES = [ + "Your response should be a code block containing a rewritten version of the file.", + `Whenever any part of the code is the same as before, you may simply indicate this with a comment that says "${UNCHANGED_CODE}" instead of rewriting.`, + "You must keep at least one line above and below from the original code, so that we can identify what the previous code was.", + `Do not place miscellaneous "${UNCHANGED_CODE}" comments at the top or bottom of the file when there is nothing to replace them.`, + // `You should write "${UNCHANGED_CODE}" at least for each function that is unchanged, rather than grouping them into a single comment.`, + // `You should lean toward using a smaller number of these comments rather than rewriting it for every function if all of them are unchanged.`, + // `You may do this for imports as well if needed.`, + // `Do not explain your changes either before or after the code block.`, + "The code should always be syntactically valid, even with the comments.", +]; + +function claude35SonnetLazyApplyPrompt( + ...args: Parameters +): ReturnType { + const userContent = dedent` + ORIGINAL CODE: + \`\`\`${args[1]} + ${args[0]} + \`\`\` + + NEW CODE: + \`\`\` + ${args[2]} + \`\`\` + + Above is a code block containing the original version of a file (ORIGINAL CODE) and below it is a code snippet (NEW CODE) that was suggested as modification to the original file. Your task is to apply the NEW CODE to the ORIGINAL CODE and show what the entire file would look like after it is applied. + - ${RULES.join("\n- ")} + `; + + const assistantContent = dedent` + Sure! Here's the modified version of the file after applying the new code: + \`\`\`${args[1]} + `; + + return [ + { role: "user", content: userContent }, + { role: "assistant", content: assistantContent }, + ]; +} + +export function lazyApplyPromptForModel( + model: string, + provider: ModelProvider, +): LazyApplyPrompt | undefined { + if (model.includes("sonnet")) { + return claude35SonnetLazyApplyPrompt; + } + + return undefined; +} diff --git a/core/edit/lazy/replace.ts b/core/edit/lazy/replace.ts new file mode 100644 index 000000000..b4b6164cc --- /dev/null +++ b/core/edit/lazy/replace.ts @@ -0,0 +1,98 @@ +import { ILLM } from "../.."; +import { + filterLeadingNewline, + stopAtLines, +} from "../../autocomplete/streamTransforms/lineStream"; +import { streamLines } from "../../diff/util"; +import { dedent } from "../../util"; + +export const BUFFER_LINES_BELOW = 3; + +const MATCH_LINES_ABOVE = 1; +export function getReplacementByMatching( + oldCode: string, + linesBefore: string[], + linesAfter: string[], +): string | undefined { + const oldLines = oldCode.split("\n"); + const linesToMatchAbove = MATCH_LINES_ABOVE; + const linesToMatchBelow = Math.min(BUFFER_LINES_BELOW, linesAfter.length); + + // Get surrounding lines around the gap + const beforeContext = linesBefore.slice(-linesToMatchAbove).join("\n"); + const afterContext = linesAfter.slice(0, linesToMatchBelow).join("\n"); + + // Find the start index in the old code + const startIndex = oldLines.findIndex((line, index) => { + const chunk = oldLines.slice(index, index + linesToMatchAbove).join("\n"); + return chunk === beforeContext; + }); + + if (startIndex === -1) { + return undefined; // Couldn't find matching start + } + + // Find the end index in the old code + const endIndex = oldLines.findIndex((line, index) => { + if (index <= startIndex + linesToMatchBelow) { + return false; + } + const chunk = oldLines.slice(index, index + linesToMatchBelow).join("\n"); + return chunk === afterContext; + }); + + if (endIndex === -1) { + return undefined; // Couldn't find matching end + } + + // Extract the replacement code + const replacement = oldLines + .slice(startIndex + linesToMatchAbove, endIndex) + .join("\n"); + + return replacement; +} + +const REPLACE_HERE = "// REPLACE HERE //"; +export async function* getReplacementWithLlm( + oldCode: string, + linesBefore: string[], + linesAfter: string[], + llm: ILLM, +): AsyncGenerator { + const userPrompt = dedent` + ORIGINAL CODE: + \`\`\` + ${oldCode} + \`\`\` + + UPDATED CODE: + \`\`\` + ${linesBefore.join("\n")} + ${REPLACE_HERE} + ${linesAfter.join("\n")} + \`\`\` + + Above is an original version of a file, followed by a newer version that is in the process of being written. The new version contains a section which is exactly the same as in the original code, and has been marked with "${REPLACE_HERE}". Your task is to give the exact snippet of code from the original code that should replace "${REPLACE_HERE}" in the new version. + + Your output should be a single code block. We will paste the contents of that code block directly into the new version, so make sure that it has correct indentation. + `; + + const assistantPrompt = dedent` + Here is the snippet of code that will replace "${REPLACE_HERE}" in the new version: + \`\`\` + `; + + const completion = await llm.streamChat([ + { role: "user", content: userPrompt }, + { role: "assistant", content: assistantPrompt }, + ]); + + let lines = streamLines(completion); + lines = filterLeadingNewline(lines); + lines = stopAtLines(lines, () => {}, ["```"]); + + for await (const line of lines) { + yield line; + } +} diff --git a/core/edit/lazy/streamLazyApply.ts b/core/edit/lazy/streamLazyApply.ts new file mode 100644 index 000000000..6dd9cef6d --- /dev/null +++ b/core/edit/lazy/streamLazyApply.ts @@ -0,0 +1,130 @@ +import { + filterLeadingAndTrailingNewLineInsertion, + filterLeadingNewline, + stopAtLines, +} from "../../autocomplete/streamTransforms/lineStream"; +import { streamDiff } from "../../diff/streamDiff.js"; +import { LineStream, streamLines } from "../../diff/util.js"; +import { DiffLine, ILLM } from "../../index.js"; +import { lazyApplyPromptForModel, UNCHANGED_CODE } from "./prompts.js"; +import { BUFFER_LINES_BELOW, getReplacementWithLlm } from "./replace.js"; + +export async function* streamLazyApply( + oldCode: string, + filename: string, + newCode: string, + llm: ILLM, + fastLlm: ILLM, +): AsyncGenerator { + const promptFactory = lazyApplyPromptForModel(llm.model, llm.providerName); + if (!promptFactory) { + throw new Error(`Lazy apply not supported for model ${llm.model}`); + } + + const promptMessages = promptFactory(oldCode, filename, newCode); + const lazyCompletion = llm.streamChat(promptMessages); + + // Do find and replace over the lazy edit response + async function* replacementFunction( + oldCode: string, + linesBefore: string[], + linesAfter: string[], + ): AsyncGenerator { + for await (const line of getReplacementWithLlm( + oldCode, + linesBefore, + linesAfter, + fastLlm, + )) { + yield line; + } + } + + let lazyCompletionLines = streamLines(lazyCompletion, true); + // Process line output + // lazyCompletionLines = filterEnglishLinesAtStart(lazyCompletionLines); + lazyCompletionLines = stopAtLines(lazyCompletionLines, () => {}, ["```"]); + lazyCompletionLines = filterLeadingNewline(lazyCompletionLines); + + // Fill in unchanged code + let lines = streamFillUnchangedCode( + lazyCompletionLines, + oldCode, + replacementFunction, + ); + + // Convert output to diff + const oldLines = oldCode.split(/\r?\n/); + let diffLines = streamDiff(oldLines, lines); + diffLines = filterLeadingAndTrailingNewLineInsertion(diffLines); + for await (const diffLine of diffLines) { + yield diffLine; + } +} + +async function* streamFillUnchangedCode( + lines: LineStream, + oldCode: string, + replacementFunction: ( + oldCode: string, + linesBefore: string[], + linesAfter: string[], + ) => AsyncGenerator, +): LineStream { + const newLines = []; + let buffer = []; + let waitingForBuffer = false; + + for await (const line of lines) { + if (waitingForBuffer) { + buffer.push(line); + + if (buffer.length >= BUFFER_LINES_BELOW) { + // Find the replacement and continue streaming once we have it + const replacementLines = replacementFunction(oldCode, newLines, buffer); + let replacement = ""; + for await (const replacementLine of replacementLines) { + yield replacementLine; + newLines.push(replacementLine); + replacement += replacementLine + "\n"; + } + + // Yield the buffered lines + for (const bufferedLine of buffer) { + yield bufferedLine; + newLines.push(bufferedLine); + } + + waitingForBuffer = false; + buffer = []; + continue; + } else { + continue; + } + } + + if (line.includes(UNCHANGED_CODE)) { + // Buffer so we can give the context of BUFFER_LINES_BELOW lines below + waitingForBuffer = true; + // TODO: If the UNCHANGED CODE is at the very top of the file we need to handle a bit differently + } else { + yield line; + newLines.push(line); + } + } + + if (waitingForBuffer) { + // If we're still waiting for a buffer, we've reached the end of the stream + // and we should just look for the replacement with what we have + const replacementLines = replacementFunction(oldCode, newLines, buffer); + for await (const replacementLine of replacementLines) { + yield replacementLine; + newLines.push(replacementLine); + } + // Yield the buffered lines + for (const bufferedLine of buffer) { + yield bufferedLine; + newLines.push(bufferedLine); + } + } +} diff --git a/core/edit/lazy/test-examples/calculator-comments.js.diff b/core/edit/lazy/test-examples/calculator-comments.js.diff new file mode 100644 index 000000000..5aa52aead --- /dev/null +++ b/core/edit/lazy/test-examples/calculator-comments.js.diff @@ -0,0 +1,129 @@ +class Calculator { + constructor() { + this.result = 0; + } + + add(number) { + this.result += number; + return this; + } + + subtract(number) { + this.result -= number; + return this; + } + + multiply(number) { + this.result *= number; + return this; + } + + divide(number) { + if (number === 0) { + throw new Error("Cannot divide by zero"); + } + this.result /= number; + return this; + } + + getResult() { + return this.result; + } + + reset() { + this.result = 0; + return this; + } +} + +--- + +class Calculator { + // ... existing code ... + + // Adds the given number to the result + add(number) { + this.result += number; + return this; + } + + // Subtracts the given number from the result + subtract(number) { + this.result -= number; + return this; + } + + // Multiplies the result by the given number + multiply(number) { + this.result *= number; + return this; + } + + // Divides the result by the given number + // Throws an error if attempting to divide by zero + divide(number) { + if (number === 0) { + throw new Error("Cannot divide by zero"); + } + this.result /= number; + return this; + } + + // Returns the current result + getResult() { + return this.result; + } + + // Resets the result to zero + reset() { + this.result = 0; + return this; + } +} + +--- + +class Calculator { + constructor() { + this.result = 0; + } + ++ // Adds the given number to the result + add(number) { + this.result += number; + return this; + } + ++ // Subtracts the given number from the result + subtract(number) { + this.result -= number; + return this; + } + ++ // Multiplies the result by the given number + multiply(number) { + this.result *= number; + return this; + } + ++ // Divides the result by the given number ++ // Throws an error if attempting to divide by zero + divide(number) { + if (number === 0) { + throw new Error("Cannot divide by zero"); + } + this.result /= number; + return this; + } + ++ // Returns the current result + getResult() { + return this.result; + } + ++ // Resets the result to zero + reset() { + this.result = 0; + return this; + } +} \ No newline at end of file diff --git a/core/edit/lazy/test-examples/calculator-docstrings.js.diff b/core/edit/lazy/test-examples/calculator-docstrings.js.diff new file mode 100644 index 000000000..a7702238a --- /dev/null +++ b/core/edit/lazy/test-examples/calculator-docstrings.js.diff @@ -0,0 +1,189 @@ +class Calculator { + constructor() { + this.result = 0; + } + + add(number) { + this.result += number; + return this; + } + + subtract(number) { + this.result -= number; + return this; + } + + multiply(number) { + this.result *= number; + return this; + } + + divide(number) { + if (number === 0) { + throw new Error("Cannot divide by zero"); + } + this.result /= number; + return this; + } + + getResult() { + return this.result; + } + + reset() { + this.result = 0; + return this; + } +} + +--- + +/** + * Calculator class for performing basic arithmetic operations. + */ +class Calculator { + /** + * Creates a new Calculator instance. + * Initializes the result to 0. + */ + constructor() { + this.result = 0; + } + + /** + * Adds a number to the current result. + * @param {number} number - The number to add. + * @returns {Calculator} The Calculator instance for method chaining. + */ + add(number) { + this.result += number; + return this; + } + + /** + * Subtracts a number from the current result. + * @param {number} number - The number to subtract. + * @returns {Calculator} The Calculator instance for method chaining. + */ + subtract(number) { + this.result -= number; + return this; + } + + /** + * Multiplies the current result by a number. + * @param {number} number - The number to multiply by. + * @returns {Calculator} The Calculator instance for method chaining. + */ + multiply(number) { + this.result *= number; + return this; + } + + /** + * Divides the current result by a number. + * @param {number} number - The number to divide by. + * @returns {Calculator} The Calculator instance for method chaining. + * @throws {Error} If attempting to divide by zero. + */ + divide(number) { + if (number === 0) { + throw new Error("Cannot divide by zero"); + } + this.result /= number; + return this; + } + + /** + * Returns the current result. + * @returns {number} The current result. + */ + getResult() { + return this.result; + } + + /** + * Resets the calculator's result to 0. + * @returns {Calculator} The Calculator instance for method chaining. + */ + reset() { + this.result = 0; + return this; + } +} + +--- + ++ /** ++ * Calculator class for performing basic arithmetic operations. ++ */ +class Calculator { ++ /** ++ * Creates a new Calculator instance. ++ * Initializes the result to 0. ++ */ + constructor() { + this.result = 0; + } + ++ /** ++ * Adds a number to the current result. ++ * @param {number} number - The number to add. ++ * @returns {Calculator} The Calculator instance for method chaining. ++ */ + add(number) { + this.result += number; + return this; + } + ++ /** ++ * Subtracts a number from the current result. ++ * @param {number} number - The number to subtract. ++ * @returns {Calculator} The Calculator instance for method chaining. ++ */ + subtract(number) { + this.result -= number; + return this; + } + ++ /** ++ * Multiplies the current result by a number. ++ * @param {number} number - The number to multiply by. ++ * @returns {Calculator} The Calculator instance for method chaining. ++ */ + multiply(number) { + this.result *= number; + return this; + } + ++ /** ++ * Divides the current result by a number. ++ * @param {number} number - The number to divide by. ++ * @returns {Calculator} The Calculator instance for method chaining. ++ * @throws {Error} If attempting to divide by zero. ++ */ + divide(number) { + if (number === 0) { + throw new Error("Cannot divide by zero"); + } + this.result /= number; + return this; + } + ++ /** ++ * Returns the current result. ++ * @returns {number} The current result. ++ */ + getResult() { + return this.result; + } + ++ /** ++ * Resets the calculator's result to 0. ++ * @returns {Calculator} The Calculator instance for method chaining. ++ */ + reset() { + this.result = 0; + return this; + } +} \ No newline at end of file diff --git a/core/edit/lazy/test-examples/calculator-exp.js.diff b/core/edit/lazy/test-examples/calculator-exp.js.diff new file mode 100644 index 000000000..4708a76a0 --- /dev/null +++ b/core/edit/lazy/test-examples/calculator-exp.js.diff @@ -0,0 +1,99 @@ +class Calculator { + constructor() { + this.result = 0; + } + + add(number) { + this.result += number; + return this; + } + + subtract(number) { + this.result -= number; + return this; + } + + multiply(number) { + this.result *= number; + return this; + } + + divide(number) { + if (number === 0) { + throw new Error("Cannot divide by zero"); + } + this.result /= number; + return this; + } + + getResult() { + return this.result; + } + + reset() { + this.result = 0; + return this; + } +} + +--- + +class Calculator { + constructor() { + this.result = 0; + } + + // ... same ... + + exp(a) { + this.result = Math.pow(this.result, a); + return this; + } + + // ... same ... +} + +--- + +class Calculator { + constructor() { + this.result = 0; + } + + add(number) { + this.result += number; + return this; + } + + subtract(number) { + this.result -= number; + return this; + } + + multiply(number) { + this.result *= number; + return this; + } + + divide(number) { + if (number === 0) { + throw new Error("Cannot divide by zero"); + } + this.result /= number; + return this; + } + + getResult() { + return this.result; + } + + reset() { + this.result = 0; + return this; + } ++ ++ exp(a) { ++ this.result = Math.pow(this.result, a); ++ return this; ++ } +} \ No newline at end of file diff --git a/core/edit/lazy/test-examples/calculator-exp2.js.diff b/core/edit/lazy/test-examples/calculator-exp2.js.diff new file mode 100644 index 000000000..b845f5e5b --- /dev/null +++ b/core/edit/lazy/test-examples/calculator-exp2.js.diff @@ -0,0 +1,93 @@ +class Calculator { + constructor() { + this.result = 0; + } + + add(number) { + this.result += number; + return this; + } + + subtract(number) { + this.result -= number; + return this; + } + + multiply(number) { + this.result *= number; + return this; + } + + divide(number) { + if (number === 0) { + throw new Error("Cannot divide by zero"); + } + this.result /= number; + return this; + } + + getResult() { + return this.result; + } + + reset() { + this.result = 0; + return this; + } +} + +--- + +class Calculator { + // ... existing code ... + + exp(number) { + this.result = Math.pow(this.result, number); + return this; + } +} + +--- + +class Calculator { + constructor() { + this.result = 0; + } + + add(number) { + this.result += number; + return this; + } + + subtract(number) { + this.result -= number; + return this; + } + + multiply(number) { + this.result *= number; + return this; + } + + divide(number) { + if (number === 0) { + throw new Error("Cannot divide by zero"); + } + this.result /= number; + return this; + } + + getResult() { + return this.result; + } + + reset() { + this.result = 0; + return this; + } ++ ++ exp(number) { ++ this.result = Math.pow(this.result, number); ++ return this; ++ } +} \ No newline at end of file diff --git a/core/edit/lazy/test-examples/calculator-stateless.js.diff b/core/edit/lazy/test-examples/calculator-stateless.js.diff new file mode 100644 index 000000000..93d1a1dd5 --- /dev/null +++ b/core/edit/lazy/test-examples/calculator-stateless.js.diff @@ -0,0 +1,111 @@ +class Calculator { + constructor() { + this.result = 0; + } + + add(number) { + this.result += number; + return this; + } + + subtract(number) { + this.result -= number; + return this; + } + + multiply(number) { + this.result *= number; + return this; + } + + divide(number) { + if (number === 0) { + throw new Error("Cannot divide by zero"); + } + this.result /= number; + return this; + } + + getResult() { + return this.result; + } + + reset() { + this.result = 0; + return this; + } +} + +--- + +class Calculator { + // ... existing code ... + + static add(a, b) { + return a + b; + } + + static subtract(a, b) { + return a - b; + } + + static multiply(a, b) { + return a * b; + } + + static divide(a, b) { + if (b === 0) { + throw new Error("Cannot divide by zero"); + } + return a / b; + } +} + +--- + +class Calculator { + constructor() { + this.result = 0; + } + +- add(number) { +- this.result += number; +- return this; ++ static add(a, b) { ++ return a + b; + } + +- subtract(number) { +- this.result -= number; +- return this; ++ static subtract(a, b) { ++ return a - b; + } + +- multiply(number) { +- this.result *= number; +- return this; ++ static multiply(a, b) { ++ return a * b; + } + +- divide(number) { +- if (number === 0) { ++ static divide(a, b) { ++ if (b === 0) { + throw new Error("Cannot divide by zero"); + } +- this.result /= number; +- return this; ++ return a / b; + } +- +- getResult() { +- return this.result; +- } +- +- reset() { +- this.result = 0; +- return this; +- } +} \ No newline at end of file diff --git a/core/edit/lazy/test-examples/fastapi.py.diff b/core/edit/lazy/test-examples/fastapi.py.diff new file mode 100644 index 000000000..12d60c3b3 --- /dev/null +++ b/core/edit/lazy/test-examples/fastapi.py.diff @@ -0,0 +1,37 @@ +from fastapi import FastAPI + +app = FastAPI() + +@app.get("/") +def read_root(): + return {"Hello": "World"} + +@app.get("/landing") +def read_landing_page(): + return {"message": "Welcome to the landing page"} + +--- + +from fastapi import FastAPI, HTTPException + +# ... same ... + +@app.get("/landing") +def read_landing_page(): + raise HTTPException(status_code=404, detail="Page not found") + +--- + +- from fastapi import FastAPI ++ from fastapi import FastAPI, HTTPException + +app = FastAPI() + +@app.get("/") +def read_root(): + return {"Hello": "World"} + +@app.get("/landing") +def read_landing_page(): +- return {"message": "Welcome to the landing page"} ++ raise HTTPException(status_code=404, detail="Page not found") \ No newline at end of file diff --git a/core/edit/lazy/test-examples/gui.js.diff b/core/edit/lazy/test-examples/gui.js.diff new file mode 100644 index 000000000..9b6ed209a --- /dev/null +++ b/core/edit/lazy/test-examples/gui.js.diff @@ -0,0 +1,1186 @@ +import { + ArrowLeftIcon, + ChatBubbleOvalLeftIcon, + CodeBracketSquareIcon, + ExclamationTriangleIcon, +} from "@heroicons/react/24/outline"; +import { JSONContent } from "@tiptap/react"; +import { InputModifiers } from "core"; +import { usePostHog } from "posthog-js/react"; +import { + Fragment, + useCallback, + useContext, + useEffect, + useRef, + useState, +} from "react"; +import { ErrorBoundary } from "react-error-boundary"; +import { useDispatch, useSelector } from "react-redux"; +import styled from "styled-components"; +import { + Button, + defaultBorderRadius, + lightGray, + vscBackground, + vscForeground, +} from "../components"; +import { ChatScrollAnchor } from "../components/ChatScrollAnchor"; +import StepContainer from "../components/gui/StepContainer"; +import TimelineItem from "../components/gui/TimelineItem"; +import ContinueInputBox from "../components/mainInput/ContinueInputBox"; +import { defaultInputModifiers } from "../components/mainInput/inputModifiers"; +import { TutorialCard } from "../components/mainInput/TutorialCard"; +import { + OnboardingCard, + useOnboardingCard, +} from "../components/OnboardingCard"; +import { IdeMessengerContext } from "../context/IdeMessenger"; +import useChatHandler from "../hooks/useChatHandler"; +import useHistory from "../hooks/useHistory"; +import { useTutorialCard } from "../hooks/useTutorialCard"; +import { useWebviewListener } from "../hooks/useWebviewListener"; +import { defaultModelSelector } from "../redux/selectors/modelSelectors"; +import { + clearLastResponse, + deleteMessage, + newSession, + setInactive, +} from "../redux/slices/stateSlice"; +import { + setDialogEntryOn, + setDialogMessage, + setShowDialog, +} from "../redux/slices/uiStateSlice"; +import { RootState } from "../redux/store"; +import { + getFontSize, + getMetaKeyLabel, + isJetBrains, + isMetaEquivalentKeyPressed, +} from "../util"; +import { FREE_TRIAL_LIMIT_REQUESTS } from "../util/freeTrial"; +import { getLocalStorage, setLocalStorage } from "../util/localStorage"; + +const TopGuiDiv = styled.div<{ + showScrollbar?: boolean; +}>` + overflow-y: auto; + height: 100%; + scrollbar-width: ${(props) => (props.showScrollbar ? "thin" : "none")}; + + &::-webkit-scrollbar { + display: ${(props) => (props.showScrollbar ? "block" : "none")}; + } +`; + +const StopButton = styled.div` + width: fit-content; + margin-right: auto; + margin-left: auto; + + font-size: ${getFontSize() - 2}px; + + border: 0.5px solid ${lightGray}; + border-radius: ${defaultBorderRadius}; + padding: 4px 8px; + color: ${lightGray}; + + cursor: pointer; +`; + +const StepsDiv = styled.div` + position: relative; + background-color: transparent; + + & > * { + position: relative; + } + + .thread-message { + margin: 8px 4px 0 4px; + padding-bottom: 8px; + } +`; + +const NewSessionButton = styled.div` + width: fit-content; + margin-right: auto; + margin-left: 6px; + margin-top: 2px; + margin-bottom: 8px; + font-size: ${getFontSize() - 2}px; + + border-radius: ${defaultBorderRadius}; + padding: 2px 6px; + color: ${lightGray}; + + &:hover { + background-color: ${lightGray}33; + color: ${vscForeground}; + } + + cursor: pointer; +`; + +function fallbackRender({ error, resetErrorBoundary }: any) { + // Call resetErrorBoundary() to reset the error boundary and retry the render. + + return ( +
+

Something went wrong:

+
{error.message}
+ +
+ +
+
+ ); +} + +function GUI() { + const posthog = usePostHog(); + const dispatch = useDispatch(); + const ideMessenger = useContext(IdeMessengerContext); + + const onboardingCard = useOnboardingCard(); + const { showTutorialCard, closeTutorialCard } = useTutorialCard(); + + const sessionState = useSelector((state: RootState) => state.state); + + const defaultModel = useSelector(defaultModelSelector); + + const ttsActive = useSelector((state: RootState) => state.state.ttsActive); + const active = useSelector((state: RootState) => state.state.active); + + const [stepsOpen, setStepsOpen] = useState<(boolean | undefined)[]>([]); + + const mainTextInputRef = useRef(null); + const topGuiDivRef = useRef(null); + + const [isAtBottom, setIsAtBottom] = useState(false); + + const state = useSelector((state: RootState) => state.state); + + const handleScroll = () => { + // Temporary fix to account for additional height when code blocks are added + const OFFSET_HERUISTIC = 300; + if (!topGuiDivRef.current) return; + + const { scrollTop, scrollHeight, clientHeight } = topGuiDivRef.current; + const atBottom = + scrollHeight - clientHeight <= scrollTop + OFFSET_HERUISTIC; + + setIsAtBottom(atBottom); + }; + + useEffect(() => { + if (!active || !topGuiDivRef.current) return; + + const scrollAreaElement = topGuiDivRef.current; + + scrollAreaElement.scrollTop = + scrollAreaElement.scrollHeight - scrollAreaElement.clientHeight; + + setIsAtBottom(true); + }, [active]); + + useEffect(() => { + // Cmd + Backspace to delete current step + const listener = (e: any) => { + if ( + e.key === "Backspace" && + isMetaEquivalentKeyPressed(e) && + !e.shiftKey + ) { + dispatch(setInactive()); + } + }; + window.addEventListener("keydown", listener); + + return () => { + window.removeEventListener("keydown", listener); + }; + }, [active]); + + // #endregion + + const { streamResponse } = useChatHandler(dispatch, ideMessenger); + + const sendInput = useCallback( + (editorState: JSONContent, modifiers: InputModifiers) => { + if (defaultModel?.provider === "free-trial") { + const u = getLocalStorage("ftc"); + if (u) { + setLocalStorage("ftc", u + 1); + + if (u >= FREE_TRIAL_LIMIT_REQUESTS) { + onboardingCard.open("Best"); + posthog?.capture("ftc_reached"); + ideMessenger.ide.showToast( + "info", + "You've reached the free trial limit. Please configure a model to continue.", + ); + return; + } + } else { + setLocalStorage("ftc", 1); + } + } + + streamResponse(editorState, modifiers, ideMessenger); + + // Increment localstorage counter for popup + const currentCount = getLocalStorage("mainTextEntryCounter"); + if (currentCount) { + setLocalStorage("mainTextEntryCounter", currentCount + 1); + if (currentCount === 300) { + dispatch( + setDialogMessage( +
+ 👋 Thanks for using Continue. We are always trying to improve + and love hearing from users. If you're interested in speaking, + enter your name and email. We won't use this information for + anything other than reaching out. +
+
+
{ + e.preventDefault(); + posthog?.capture("user_interest_form", { + name: e.target.elements[0].value, + email: e.target.elements[1].value, + }); + dispatch( + setDialogMessage( +
+ Thanks! We'll be in touch soon. +
, + ), + ); + }} + style={{ + display: "flex", + flexDirection: "column", + gap: "10px", + }} + > + + + +
+
, + ), + ); + dispatch(setDialogEntryOn(false)); + dispatch(setShowDialog(true)); + } + } else { + setLocalStorage("mainTextEntryCounter", 1); + } + }, + [ + sessionState.history, + sessionState.contextItems, + defaultModel, + state, + streamResponse, + ], + ); + + const { saveSession, getLastSessionId, loadLastSession } = + useHistory(dispatch); + + useWebviewListener( + "newSession", + async () => { + saveSession(); + mainTextInputRef.current?.focus?.(); + }, + [saveSession], + ); + + const isLastUserInput = useCallback( + (index: number): boolean => { + let foundLaterUserInput = false; + for (let i = index + 1; i < state.history.length; i++) { + if (state.history[i].message.role === "user") { + foundLaterUserInput = true; + break; + } + } + return !foundLaterUserInput; + }, + [state.history], + ); + + return ( + <> + +
+ + {state.history.map((item, index: number) => { + return ( + + { + dispatch(newSession()); + }} + > + {item.message.role === "user" ? ( + { + streamResponse( + editorState, + modifiers, + ideMessenger, + index, + ); + }} + isLastUserInput={isLastUserInput(index)} + isMainInput={false} + editorState={item.editorState} + contextItems={item.contextItems} + > + ) : ( +
+ + ) : false ? ( + + ) : ( + + ) + } + open={ + typeof stepsOpen[index] === "undefined" + ? false + ? false + : true + : stepsOpen[index]! + } + onToggle={() => {}} + > + {}} + item={item} + onReverse={() => {}} + onRetry={() => { + streamResponse( + state.history[index - 1].editorState, + state.history[index - 1].modifiers ?? + defaultInputModifiers, + ideMessenger, + index - 1, + ); + }} + onContinueGeneration={() => { + window.postMessage( + { + messageType: "userInput", + data: { + input: + "Continue your response exactly where you left off:", + }, + }, + "*", + ); + }} + onDelete={() => { + dispatch(deleteMessage(index)); + }} + modelTitle={item.promptLogs?.[0]?.modelTitle ?? ""} + /> + +
+ )} +
+
+ ); + })} +
+ { + sendInput(editorContent, modifiers); + }} + isLastUserInput={false} + isMainInput={true} + hidden={active} + > + + {active ? ( + <> +
+
+ + ) : state.history.length > 0 ? ( +
+ { + saveSession(); + }} + className="mr-auto" + > + New Session ({getMetaKeyLabel()} {isJetBrains() ? "J" : "L"}) + {" "} +
+ ) : ( + <> + {getLastSessionId() ? ( +
+ { + loadLastSession().catch((e) => + console.error(`Failed to load last session: ${e}`), + ); + }} + className="mr-auto flex items-center gap-2" + > + + Last Session + +
+ ) : null} + + {onboardingCard.show && ( +
+ +
+ )} + + {showTutorialCard !== false && !onboardingCard.open && ( +
+ +
+ )} + + )} +
+ + +
+ {ttsActive && ( + { + ideMessenger.post("tts/kill", undefined); + }} + > + ■ Stop TTS + + )} + {active && ( + { + dispatch(setInactive()); + if ( + state.history[state.history.length - 1]?.message.content + .length === 0 + ) { + dispatch(clearLastResponse()); + } + }} + > + {getMetaKeyLabel()} ⌫ Cancel + + )} + + ); +} + +export default GUI; + +--- + +import { + ArrowLeftIcon, + ChatBubbleOvalLeftIcon, + CodeBracketSquareIcon, + ExclamationTriangleIcon, +} from "@heroicons/react/24/outline"; +import { JSONContent } from "@tiptap/react"; +import { InputModifiers } from "core"; +import { usePostHog } from "posthog-js/react"; +import { + Fragment, + useCallback, + useContext, + useEffect, + useRef, + useState, +} from "react"; +// ... existing imports ... + +function GUI() { + const posthog = usePostHog(); + const dispatch = useDispatch(); + const ideMessenger = useContext(IdeMessengerContext); + + // ... existing code ... + + const [hello, setHello] = useState(false); + + // ... existing code ... + + return ( + <> + +
+
+ + {hello && world} +
+ + + {state.history.map((item, index: number) => { + // ... existing code ... + })} + + + // ... rest of the existing code ... +
+ + // ... existing code ... +
+ // ... rest of the existing code ... + + ); +} + +export default GUI; + + +--- + +import { + ArrowLeftIcon, + ChatBubbleOvalLeftIcon, + CodeBracketSquareIcon, + ExclamationTriangleIcon, +} from "@heroicons/react/24/outline"; +import { JSONContent } from "@tiptap/react"; +import { InputModifiers } from "core"; +import { usePostHog } from "posthog-js/react"; +import { + Fragment, + useCallback, + useContext, + useEffect, + useRef, + useState, +} from "react"; +import { ErrorBoundary } from "react-error-boundary"; +import { useDispatch, useSelector } from "react-redux"; +import styled from "styled-components"; +import { + Button, + defaultBorderRadius, + lightGray, + vscBackground, + vscForeground, +} from "../components"; +import { ChatScrollAnchor } from "../components/ChatScrollAnchor"; +import StepContainer from "../components/gui/StepContainer"; +import TimelineItem from "../components/gui/TimelineItem"; +import ContinueInputBox from "../components/mainInput/ContinueInputBox"; +import { defaultInputModifiers } from "../components/mainInput/inputModifiers"; +import { TutorialCard } from "../components/mainInput/TutorialCard"; +import { + OnboardingCard, + useOnboardingCard, +} from "../components/OnboardingCard"; +import { IdeMessengerContext } from "../context/IdeMessenger"; +import useChatHandler from "../hooks/useChatHandler"; +import useHistory from "../hooks/useHistory"; +import { useTutorialCard } from "../hooks/useTutorialCard"; +import { useWebviewListener } from "../hooks/useWebviewListener"; +import { defaultModelSelector } from "../redux/selectors/modelSelectors"; +import { + clearLastResponse, + deleteMessage, + newSession, + setInactive, +} from "../redux/slices/stateSlice"; +import { + setDialogEntryOn, + setDialogMessage, + setShowDialog, +} from "../redux/slices/uiStateSlice"; +import { RootState } from "../redux/store"; +import { + getFontSize, + getMetaKeyLabel, + isJetBrains, + isMetaEquivalentKeyPressed, +} from "../util"; +import { FREE_TRIAL_LIMIT_REQUESTS } from "../util/freeTrial"; +import { getLocalStorage, setLocalStorage } from "../util/localStorage"; + +const TopGuiDiv = styled.div<{ + showScrollbar?: boolean; +}>` + overflow-y: auto; + height: 100%; + scrollbar-width: ${(props) => (props.showScrollbar ? "thin" : "none")}; + + &::-webkit-scrollbar { + display: ${(props) => (props.showScrollbar ? "block" : "none")}; + } +`; + +const StopButton = styled.div` + width: fit-content; + margin-right: auto; + margin-left: auto; + + font-size: ${getFontSize() - 2}px; + + border: 0.5px solid ${lightGray}; + border-radius: ${defaultBorderRadius}; + padding: 4px 8px; + color: ${lightGray}; + + cursor: pointer; +`; + +const StepsDiv = styled.div` + position: relative; + background-color: transparent; + + & > * { + position: relative; + } + + .thread-message { + margin: 8px 4px 0 4px; + padding-bottom: 8px; + } +`; + +const NewSessionButton = styled.div` + width: fit-content; + margin-right: auto; + margin-left: 6px; + margin-top: 2px; + margin-bottom: 8px; + font-size: ${getFontSize() - 2}px; + + border-radius: ${defaultBorderRadius}; + padding: 2px 6px; + color: ${lightGray}; + + &:hover { + background-color: ${lightGray}33; + color: ${vscForeground}; + } + + cursor: pointer; +`; + +function fallbackRender({ error, resetErrorBoundary }: any) { + // Call resetErrorBoundary() to reset the error boundary and retry the render. + + return ( +
+

Something went wrong:

+
{error.message}
+ +
+ +
+
+ ); +} + +function GUI() { + const posthog = usePostHog(); + const dispatch = useDispatch(); + const ideMessenger = useContext(IdeMessengerContext); + ++ const [hello, setHello] = useState(false); + + const onboardingCard = useOnboardingCard(); + const { showTutorialCard, closeTutorialCard } = useTutorialCard(); + + const sessionState = useSelector((state: RootState) => state.state); + + const defaultModel = useSelector(defaultModelSelector); + + const ttsActive = useSelector((state: RootState) => state.state.ttsActive); + const active = useSelector((state: RootState) => state.state.active); + + const [stepsOpen, setStepsOpen] = useState<(boolean | undefined)[]>([]); + + const mainTextInputRef = useRef(null); + const topGuiDivRef = useRef(null); + + const [isAtBottom, setIsAtBottom] = useState(false); + + const state = useSelector((state: RootState) => state.state); + + const handleScroll = () => { + // Temporary fix to account for additional height when code blocks are added + const OFFSET_HERUISTIC = 300; + if (!topGuiDivRef.current) return; + + const { scrollTop, scrollHeight, clientHeight } = topGuiDivRef.current; + const atBottom = + scrollHeight - clientHeight <= scrollTop + OFFSET_HERUISTIC; + + setIsAtBottom(atBottom); + }; + + useEffect(() => { + if (!active || !topGuiDivRef.current) return; + + const scrollAreaElement = topGuiDivRef.current; + + scrollAreaElement.scrollTop = + scrollAreaElement.scrollHeight - scrollAreaElement.clientHeight; + + setIsAtBottom(true); + }, [active]); + + useEffect(() => { + // Cmd + Backspace to delete current step + const listener = (e: any) => { + if ( + e.key === "Backspace" && + isMetaEquivalentKeyPressed(e) && + !e.shiftKey + ) { + dispatch(setInactive()); + } + }; + window.addEventListener("keydown", listener); + + return () => { + window.removeEventListener("keydown", listener); + }; + }, [active]); + + // #endregion + + const { streamResponse } = useChatHandler(dispatch, ideMessenger); + + const sendInput = useCallback( + (editorState: JSONContent, modifiers: InputModifiers) => { + if (defaultModel?.provider === "free-trial") { + const u = getLocalStorage("ftc"); + if (u) { + setLocalStorage("ftc", u + 1); + + if (u >= FREE_TRIAL_LIMIT_REQUESTS) { + onboardingCard.open("Best"); + posthog?.capture("ftc_reached"); + ideMessenger.ide.showToast( + "info", + "You've reached the free trial limit. Please configure a model to continue.", + ); + return; + } + } else { + setLocalStorage("ftc", 1); + } + } + + streamResponse(editorState, modifiers, ideMessenger); + + // Increment localstorage counter for popup + const currentCount = getLocalStorage("mainTextEntryCounter"); + if (currentCount) { + setLocalStorage("mainTextEntryCounter", currentCount + 1); + if (currentCount === 300) { + dispatch( + setDialogMessage( +
+ 👋 Thanks for using Continue. We are always trying to improve + and love hearing from users. If you're interested in speaking, + enter your name and email. We won't use this information for + anything other than reaching out. +
+
+
{ + e.preventDefault(); + posthog?.capture("user_interest_form", { + name: e.target.elements[0].value, + email: e.target.elements[1].value, + }); + dispatch( + setDialogMessage( +
+ Thanks! We'll be in touch soon. +
, + ), + ); + }} + style={{ + display: "flex", + flexDirection: "column", + gap: "10px", + }} + > + + + +
+
, + ), + ); + dispatch(setDialogEntryOn(false)); + dispatch(setShowDialog(true)); + } + } else { + setLocalStorage("mainTextEntryCounter", 1); + } + }, + [ + sessionState.history, + sessionState.contextItems, + defaultModel, + state, + streamResponse, + ], + ); + + const { saveSession, getLastSessionId, loadLastSession } = + useHistory(dispatch); + + useWebviewListener( + "newSession", + async () => { + saveSession(); + mainTextInputRef.current?.focus?.(); + }, + [saveSession], + ); + + const isLastUserInput = useCallback( + (index: number): boolean => { + let foundLaterUserInput = false; + for (let i = index + 1; i < state.history.length; i++) { + if (state.history[i].message.role === "user") { + foundLaterUserInput = true; + break; + } + } + return !foundLaterUserInput; + }, + [state.history], + ); + + return ( + <> + +
++
++ ++ {hello && world} ++
+ + + {state.history.map((item, index: number) => { + return ( + + { + dispatch(newSession()); + }} + > + {item.message.role === "user" ? ( + { + streamResponse( + editorState, + modifiers, + ideMessenger, + index, + ); + }} + isLastUserInput={isLastUserInput(index)} + isMainInput={false} + editorState={item.editorState} + contextItems={item.contextItems} + > + ) : ( +
+ + ) : false ? ( + + ) : ( + + ) + } + open={ + typeof stepsOpen[index] === "undefined" + ? false + ? false + : true + : stepsOpen[index]! + } + onToggle={() => {}} + > + {}} + item={item} + onReverse={() => {}} + onRetry={() => { + streamResponse( + state.history[index - 1].editorState, + state.history[index - 1].modifiers ?? + defaultInputModifiers, + ideMessenger, + index - 1, + ); + }} + onContinueGeneration={() => { + window.postMessage( + { + messageType: "userInput", + data: { + input: + "Continue your response exactly where you left off:", + }, + }, + "*", + ); + }} + onDelete={() => { + dispatch(deleteMessage(index)); + }} + modelTitle={item.promptLogs?.[0]?.modelTitle ?? ""} + /> + +
+ )} +
+
+ ); + })} +
+ { + sendInput(editorContent, modifiers); + }} + isLastUserInput={false} + isMainInput={true} + hidden={active} + > + + {active ? ( + <> +
+
+ + ) : state.history.length > 0 ? ( +
+ { + saveSession(); + }} + className="mr-auto" + > + New Session ({getMetaKeyLabel()} {isJetBrains() ? "J" : "L"}) + {" "} +
+ ) : ( + <> + {getLastSessionId() ? ( +
+ { + loadLastSession().catch((e) => + console.error(`Failed to load last session: ${e}`), + ); + }} + className="mr-auto flex items-center gap-2" + > + + Last Session + +
+ ) : null} + + {onboardingCard.show && ( +
+ +
+ )} + + {showTutorialCard !== false && !onboardingCard.open && ( +
+ +
+ )} + + )} +
+ + +
+ {ttsActive && ( + { + ideMessenger.post("tts/kill", undefined); + }} + > + ■ Stop TTS + + )} + {active && ( + { + dispatch(setInactive()); + if ( + state.history[state.history.length - 1]?.message.content + .length === 0 + ) { + dispatch(clearLastResponse()); + } + }} + > + {getMetaKeyLabel()} ⌫ Cancel + + )} + + ); +} + +export default GUI; diff --git a/core/edit/lazy/test-examples/migration-page.tsx.diff b/core/edit/lazy/test-examples/migration-page.tsx.diff new file mode 100644 index 000000000..3ff1810c5 --- /dev/null +++ b/core/edit/lazy/test-examples/migration-page.tsx.diff @@ -0,0 +1,166 @@ +import { useNavigate } from "react-router-dom"; +import ContinueButton from "../components/mainInput/ContinueButton"; + +function MigrationPage() { + const navigate = useNavigate(); + return ( +
+

+ Migration to config.json +

+ +

+ Continue now uses a .json config file. We hope that this takes the + guesswork out of setting up. +

+ +

+ Your configuration should have been automatically migrated, but we + recommend double-checking that everything looks correct. +

+ +

+ For a summary of what changed and examples of config.json, + please see the{" "} + + migration walkthrough + + , and if you have any questions please reach out to us on{" "} + + Discord + + . +

+ + + Note: If you are running the server manually and have not updated the + server, this message does not apply. + + + { + navigate("/"); + }} + disabled={false} + /> +
+ ); +} + +export default MigrationPage; + +--- + +import { useNavigate } from "react-router-dom"; +import ContinueButton from "../components/mainInput/ContinueButton"; + +function MigrationPage() { + const navigate = useNavigate(); + return ( +
+

+ Migration to config.json +

+ +

+ Continue now uses a .json config file. We hope that this takes the + guesswork out of setting up. +

+ +

+ Your configuration should have been automatically migrated, but we + recommend double-checking that everything looks correct. +

+ +

+ For a summary of what changed and examples of config.json, + please see the{" "} + + migration walkthrough + + , and if you have any questions please reach out to us on{" "} + + Discord + + . +

+ + + Note: If you are running the server manually and have not updated the + server, this message does not apply. + + + {/* ... existing code ... */} +
+ ); +} + +export default MigrationPage; + +--- + +import { useNavigate } from "react-router-dom"; +import ContinueButton from "../components/mainInput/ContinueButton"; + +function MigrationPage() { + const navigate = useNavigate(); + return ( +
+

+ Migration to config.json +

+ +-

++

+ Continue now uses a .json config file. We hope that this takes the + guesswork out of setting up. +

+ +-

++

+ Your configuration should have been automatically migrated, but we + recommend double-checking that everything looks correct. +

+ +-

++

+ For a summary of what changed and examples of config.json, + please see the{" "} + + migration walkthrough + + , and if you have any questions please reach out to us on{" "} + + Discord + + . +

+ +- ++ + Note: If you are running the server manually and have not updated the + server, this message does not apply. + + + { + navigate("/"); + }} + disabled={false} + /> +
+ ); +} + +export default MigrationPage; \ No newline at end of file diff --git a/core/edit/lazy/test-examples/no-lazy-single-class.js.diff b/core/edit/lazy/test-examples/no-lazy-single-class.js.diff new file mode 100644 index 000000000..bb561271d --- /dev/null +++ b/core/edit/lazy/test-examples/no-lazy-single-class.js.diff @@ -0,0 +1,30 @@ +class Calculator { + constructor() { + this.result = 0; + } + + reset() { + this.result = 0; + return this; + } +} +--- + + reset() { + this.result = 1; + return this; + } + +--- + +class Calculator { + constructor() { + this.result = 0; + } + + reset() { +- this.result = 0; ++ this.result = 1; + return this; + } +} \ No newline at end of file diff --git a/core/edit/lazy/test-examples/no-lazy.js.diff b/core/edit/lazy/test-examples/no-lazy.js.diff new file mode 100644 index 000000000..c5195628f --- /dev/null +++ b/core/edit/lazy/test-examples/no-lazy.js.diff @@ -0,0 +1,34 @@ +class Hello { + hello() { + return "Hello World"; + } +} + +class Goodbye { + goodbye() { + return "Goodbye World"; + } +} + +--- + +class Goodbye { + goodbye() { + return "Au revoir le monde"; + } +} + +--- + +class Hello { + hello() { + return "Hello World"; + } +} + +class Goodbye { + goodbye() { +- return "Goodbye World"; ++ return "Au revoir le monde"; + } +} \ No newline at end of file diff --git a/core/edit/lazy/test-examples/rust-calc-exp.rs.diff b/core/edit/lazy/test-examples/rust-calc-exp.rs.diff new file mode 100644 index 000000000..21ab8bd10 --- /dev/null +++ b/core/edit/lazy/test-examples/rust-calc-exp.rs.diff @@ -0,0 +1,126 @@ +use std::io; + +fn main() { + println!("Welcome to the Calculator!"); + + loop { + println!("Please enter an operator (+, -, *, /) or 'q' to quit:"); + let operator = read_input(); + + if operator == "q" { + break; + } + + println!("Please enter the first number:"); + let num1 = read_input().parse::().unwrap(); + + println!("Please enter the second number:"); + let num2 = read_input().parse::().unwrap(); + + let result = match operator.as_str() { + "+" => num1 + num2, + "-" => num1 - num2, + "*" => num1 * num2, + "/" => num1 / num2, + _ => { + println!("Invalid operator. Please try again."); + continue; + } + }; + + println!("Result: {}", result); + } +} + +fn read_input() -> String { + let mut input = String::new(); + io::stdin() + .read_line(&mut input) + .expect("Failed to read input"); + input.trim().to_string() +} + +--- + +use std::io; + +fn main() { + println!("Welcome to the Calculator!"); + + loop { + println!("Please enter an operator (+, -, *, /, ^) or 'q' to quit:"); + let operator = read_input(); + + if operator == "q" { + break; + } + + println!("Please enter the first number:"); + let num1 = read_input().parse::().unwrap(); + + println!("Please enter the second number:"); + let num2 = read_input().parse::().unwrap(); + + let result = match operator.as_str() { + "+" => num1 + num2, + "-" => num1 - num2, + "*" => num1 * num2, + "/" => num1 / num2, + "^" => num1.powf(num2), + _ => { + println!("Invalid operator. Please try again."); + continue; + } + }; + + println!("Result: {}", result); + } +} + +// ... existing code ... + +--- + +use std::io; + +fn main() { + println!("Welcome to the Calculator!"); + + loop { +- println!("Please enter an operator (+, -, *, /) or 'q' to quit:"); ++ println!("Please enter an operator (+, -, *, /, ^) or 'q' to quit:"); + let operator = read_input(); + + if operator == "q" { + break; + } + + println!("Please enter the first number:"); + let num1 = read_input().parse::().unwrap(); + + println!("Please enter the second number:"); + let num2 = read_input().parse::().unwrap(); + + let result = match operator.as_str() { + "+" => num1 + num2, + "-" => num1 - num2, + "*" => num1 * num2, + "/" => num1 / num2, ++ "^" => num1.powf(num2), + _ => { + println!("Invalid operator. Please try again."); + continue; + } + }; + + println!("Result: {}", result); + } +} + +fn read_input() -> String { + let mut input = String::new(); + io::stdin() + .read_line(&mut input) + .expect("Failed to read input"); + input.trim().to_string() +} \ No newline at end of file diff --git a/core/edit/lazy/test-examples/top-level-same.js.diff b/core/edit/lazy/test-examples/top-level-same.js.diff new file mode 100644 index 000000000..97b65a51c --- /dev/null +++ b/core/edit/lazy/test-examples/top-level-same.js.diff @@ -0,0 +1,64 @@ +class Calculator { + constructor() { + this.result = 0; + } +} + +class Subtract extends Calculator { + sub(num1, num2) { + this.result = num1 - num2; + return this.result; + } +} + +class Add extends Calculator { + add(num1, num2) { + this.result = num1 + num2; + return this.result; + } +} + +--- + +// ... existing code ... + +class Subtract extends Calculator { + sub(num1, num2) { + this.result = num1 - num2; + + if (this.result < 0) { + throw new Error("Result cannot be negative"); + } + + return this.result; + } +} + +// ... existing code ... + +--- + +class Calculator { + constructor() { + this.result = 0; + } +} + +class Subtract extends Calculator { + sub(num1, num2) { + this.result = num1 - num2; ++ ++ if (this.result < 0) { ++ throw new Error("Result cannot be negative"); ++ } ++ + return this.result; + } +} + +class Add extends Calculator { + add(num1, num2) { + this.result = num1 + num2; + return this.result; + } +} \ No newline at end of file diff --git a/core/util/verticalEdit.ts b/core/edit/streamDiffLines.ts similarity index 97% rename from core/util/verticalEdit.ts rename to core/edit/streamDiffLines.ts index 34a17ebd4..cad33b3a2 100644 --- a/core/util/verticalEdit.ts +++ b/core/edit/streamDiffLines.ts @@ -5,7 +5,7 @@ import { filterLeadingAndTrailingNewLineInsertion, skipLines, stopAtLines, -} from "../autocomplete/lineStream.js"; +} from "../autocomplete/streamTransforms/lineStream.js"; import { streamDiff } from "../diff/streamDiff.js"; import { streamLines } from "../diff/util.js"; import { @@ -15,7 +15,7 @@ import { LLMFullCompletionOptions, } from "../index.js"; import { gptEditPrompt } from "../llm/templates/edit.js"; -import { Telemetry } from "./posthog.js"; +import { Telemetry } from "../util/posthog.js"; function constructPrompt( prefix: string, diff --git a/core/index.d.ts b/core/index.d.ts index 0c7c9b521..c1c8ddc04 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -70,6 +70,7 @@ export interface ILLM extends LLMOptions { llmRequestHook?: (model: string, prompt: string) => any; apiKey?: string; apiBase?: string; + cacheBehavior?: CacheBehavior; engine?: string; apiVersion?: string; @@ -271,6 +272,13 @@ export interface ContextItemId { itemId: string; } +export type ContextItemUriTypes = "file" | "url"; + +export interface ContextItemUri { + type: ContextItemUriTypes; + value: string; +} + export interface ContextItem { content: string; name: string; @@ -278,16 +286,11 @@ export interface ContextItem { editing?: boolean; editable?: boolean; icon?: string; + uri?: ContextItemUri; } -export interface ContextItemWithId { - content: string; - name: string; - description: string; +export interface ContextItemWithId extends ContextItem { id: ContextItemId; - editing?: boolean; - editable?: boolean; - icon?: string; } export interface InputModifiers { @@ -340,6 +343,7 @@ export interface LLMOptions { apiKey?: string; aiGatewaySlug?: string; apiBase?: string; + cacheBehavior?: CacheBehavior; useLegacyCompletionsEndpoint?: boolean; @@ -369,8 +373,6 @@ export interface LLMOptions { watsonxStopToken?: string; watsonxApiVersion?: string; watsonxFullUrl?: string; - - cacheSystemMessage?: boolean; } type RequireAtLeastOne = Pick< T, @@ -578,6 +580,7 @@ type ContextProviderName = | "gitlab-mr" | "os" | "currentFile" + | "greptile" | "outline" | "continue-proxy" | "highlights" @@ -691,6 +694,8 @@ export type ModelName = | "deepseek-7b" | "deepseek-33b" | "neural-chat-7b" + | "gemma-7b-it" + | "gemma2-9b-it" // Anthropic | "claude-3-5-sonnet-20240620" | "claude-3-opus-20240229" @@ -725,6 +730,11 @@ export interface RequestOptions { clientCertificate?: ClientCertificateOptions; } +export interface CacheBehavior { + cacheSystemMessage?: boolean; + cacheConversation?: boolean; +} + export interface ClientCertificateOptions { cert: string; key: string; @@ -787,6 +797,7 @@ export interface ModelDescription { requestOptions?: RequestOptions; promptTemplates?: { [key: string]: string }; capabilities?: ModelCapability; + cacheBehavior?: CacheBehavior; } export type EmbeddingsProviderName = @@ -871,6 +882,7 @@ export interface TabAutocompleteOptions { recentLinePrefixMatchMinLength: number; disableInFiles?: string[]; useImports?: boolean; + useRootPathContext?: boolean; } export interface ContinueUIConfig { diff --git a/core/indexing/CodeSnippetsIndex.ts b/core/indexing/CodeSnippetsIndex.ts index f567a48d2..a8b41cafe 100644 --- a/core/indexing/CodeSnippetsIndex.ts +++ b/core/indexing/CodeSnippetsIndex.ts @@ -341,6 +341,10 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { name: row.title, description: getLastNPathParts(row.path, 2), content: `\`\`\`${getBasename(row.path)}\n${row.content}\n\`\`\``, + uri: { + type: "file", + value: row.path, + }, }; } @@ -383,20 +387,18 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { const placeholders = likePatterns.map(() => "?").join(" OR path LIKE "); const query = ` - SELECT path, signature - FROM code_snippets - WHERE path LIKE ${placeholders} - ORDER BY path - LIMIT ? OFFSET ? -`; + SELECT DISTINCT path, signature + FROM code_snippets + WHERE path LIKE ${placeholders} + ORDER BY path, signature + LIMIT ? OFFSET ? + `; const rows = await db.all(query, [...likePatterns, batchSize, offset]); - const validRows = rows.filter((row) => row.path && row.signature !== null); - const groupedByPath: { [path: string]: string[] } = {}; - for (const { path, signature } of validRows) { + for (const { path, signature } of rows) { if (!groupedByPath[path]) { groupedByPath[path] = []; } diff --git a/core/indexing/CodebaseIndexer.ts b/core/indexing/CodebaseIndexer.ts index bc53539f4..6eca76268 100644 --- a/core/indexing/CodebaseIndexer.ts +++ b/core/indexing/CodebaseIndexer.ts @@ -249,10 +249,11 @@ export class CodebaseIndexer { } } yield { - progress: 100, + progress: 1, desc: "Indexing Complete", status: "done", }; + this.logProgress(beginTime, 0, 1); } private handleErrorAndGetProgressUpdate( @@ -303,9 +304,9 @@ export class CodebaseIndexer { const seconds = Math.round(timeTaken / 1000); const progressPercentage = (progress * 100).toFixed(1); const filesPerSec = (completedFileCount / seconds).toFixed(2); - console.debug( - `Indexing: ${progressPercentage}% complete, elapsed time: ${seconds}s, ${filesPerSec} file/sec`, - ); + // console.debug( + // `Indexing: ${progressPercentage}% complete, elapsed time: ${seconds}s, ${filesPerSec} file/sec`, + // ); } private async *yieldUpdateAndPause(): AsyncGenerator { diff --git a/core/indexing/docs/DocsCrawler.ts b/core/indexing/docs/DocsCrawler.ts index aea21e3cf..70d6ead29 100644 --- a/core/indexing/docs/DocsCrawler.ts +++ b/core/indexing/docs/DocsCrawler.ts @@ -411,7 +411,7 @@ class ChromiumCrawler { for (const link of linkGroup) { enqueuedLinkCount++; - console.log({ enqueuedLinkCount, url: this.startUrl }); + console.log({ enqueuedLinkCount, url: this.startUrl.toString() }); if (enqueuedLinkCount <= this.maxRequestsPerCrawl) { yield* this.crawlSitePages(page, new URL(link), visitedLinks); } diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index 79e6dc86f..30e205c3b 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -1,8 +1,6 @@ import { open, type Database } from "sqlite"; import sqlite3 from "sqlite3"; import lancedb, { Connection } from "vectordb"; -import { ConfigHandler } from "../../config/ConfigHandler"; -import DocsContextProvider from "../../context/providers/DocsContextProvider"; import { Chunk, ContinueConfig, @@ -11,6 +9,9 @@ import { IndexingProgressUpdate, SiteIndexingConfig, } from "../.."; +import { ConfigHandler } from "../../config/ConfigHandler"; +import { addContextProvider } from "../../config/util"; +import DocsContextProvider from "../../context/providers/DocsContextProvider"; import { FromCoreProtocol, ToCoreProtocol } from "../../protocol"; import { GlobalContext } from "../../util/GlobalContext"; import { IMessenger } from "../../util/messenger"; @@ -31,7 +32,7 @@ import { SiteIndexingResults, } from "./preIndexed"; import preIndexedDocs from "./preIndexedDocs"; -import { addContextProvider } from "../../config/util"; +import { fetchFavicon, getFaviconBase64 } from "../../util/fetchFavicon"; // Purposefully lowercase because lancedb converts export interface LanceDbDocsRow { @@ -154,7 +155,10 @@ export default class DocsService { params: {}, }); - this.ide.showToast("info", "Successfuly added docs context provider"); + await this.ide.showToast( + "info", + "Successfuly added docs context provider", + ); } return res === actionMsg; @@ -177,7 +181,7 @@ export default class DocsService { while (!(await generator.next()).done) {} } - this.ide.showToast("info", "Docs indexing completed"); + await this.ide.showToast("info", "Docs indexing completed"); } async list() { @@ -250,6 +254,10 @@ export default class DocsService { } } + void Telemetry.capture("docs_pages_crawled", { + count: processedPages, + }); + const chunks: Chunk[] = []; const embeddings: number[][] = []; @@ -317,7 +325,7 @@ export default class DocsService { await this.delete(startUrl); } - const favicon = await this.fetchFavicon(siteIndexingConfig); + const favicon = await fetchFavicon(new URL(siteIndexingConfig.startUrl)); await this.add({ siteIndexingConfig, @@ -456,14 +464,14 @@ export default class DocsService { for (const doc of newDocs) { console.log(`Indexing new doc: ${doc.startUrl}`); - Telemetry.capture("add_docs_config", { url: doc.startUrl }); + void Telemetry.capture("add_docs_config", { url: doc.startUrl }); const generator = this.indexAndAdd(doc); while (!(await generator.next()).done) {} } for (const doc of deletedDocs) { - console.log(`Deleting doc: ${doc.startUrl}`); + // console.debug(`Deleting doc: ${doc.startUrl}`); await this.delete(doc.startUrl); } @@ -691,7 +699,12 @@ export default class DocsService { const siteEmbeddings = JSON.parse(data) as SiteIndexingResults; const startUrl = new URL(siteEmbeddings.url).toString(); - const favicon = await this.fetchFavicon(preIndexedDocs[startUrl]); + + const faviconUrl = preIndexedDocs[startUrl].faviconUrl; + const favicon = + typeof faviconUrl === "string" + ? await getFaviconBase64(faviconUrl) + : undefined; await this.add({ favicon, @@ -704,30 +717,6 @@ export default class DocsService { }); } - private async fetchFavicon(siteIndexingConfig: SiteIndexingConfig) { - const faviconUrl = - siteIndexingConfig.faviconUrl ?? - new URL("/favicon.ico", siteIndexingConfig.startUrl); - - try { - const response = await fetch(faviconUrl); - const arrayBuffer = await response.arrayBuffer(); - const base64 = btoa( - new Uint8Array(arrayBuffer).reduce( - (data, byte) => data + String.fromCharCode(byte), - "", - ), - ); - const mimeType = response.headers.get("content-type") || "image/x-icon"; - - return `data:${mimeType};base64,${base64}`; - } catch { - console.error(`Failed to fetch favicon: ${faviconUrl}`); - } - - return undefined; - } - private async shouldReindexDocsOnNewEmbeddingsProvider( curEmbeddingsProviderId: EmbeddingsProvider["id"], ): Promise { diff --git a/core/indexing/embeddings/BedrockEmbeddingsProvider.ts b/core/indexing/embeddings/BedrockEmbeddingsProvider.ts index aa9e8bd41..bf3bcac88 100644 --- a/core/indexing/embeddings/BedrockEmbeddingsProvider.ts +++ b/core/indexing/embeddings/BedrockEmbeddingsProvider.ts @@ -78,7 +78,8 @@ class BedrockEmbeddingsProvider extends BaseEmbeddingsProvider { try { return await fromIni({ - profile: this.profile + profile: this.profile, + ignoreCache: true })(); } catch (e) { console.warn( diff --git a/core/indexing/embeddings/ContinueProxyEmbeddingsProvider.ts b/core/indexing/embeddings/ContinueProxyEmbeddingsProvider.ts index c02685af7..811a4fb0f 100644 --- a/core/indexing/embeddings/ContinueProxyEmbeddingsProvider.ts +++ b/core/indexing/embeddings/ContinueProxyEmbeddingsProvider.ts @@ -1,24 +1,16 @@ -import { CONTROL_PLANE_URL } from "../../control-plane/client.js"; -import { EmbeddingsProviderName, EmbedOptions } from "../../index.js"; +import { ControlPlaneProxyInfo } from "../../control-plane/analytics/IAnalyticsProvider.js"; +import { EmbeddingsProviderName } from "../../index.js"; import OpenAIEmbeddingsProvider from "./OpenAIEmbeddingsProvider.js"; class ContinueProxyEmbeddingsProvider extends OpenAIEmbeddingsProvider { static providerName: EmbeddingsProviderName = "continue-proxy"; - static defaultOptions: Partial | undefined = { - apiBase: new URL("/model-proxy/v1", CONTROL_PLANE_URL).toString(), - }; - private _workOsAccessToken: string | undefined = undefined; - - get workOsAccessToken(): string | undefined { - return this._workOsAccessToken; - } - - set workOsAccessToken(value: string | undefined) { - if (this._workOsAccessToken !== value) { - this._workOsAccessToken = value; - this.options.apiKey = value; - } + set controlPlaneProxyInfo(value: ControlPlaneProxyInfo) { + this.options.apiKey = value.workOsAccessToken; + this.options.apiBase = new URL( + "openai/v1", + value.controlPlaneProxyUrl, + ).toString(); } } diff --git a/core/llm/autodetect.ts b/core/llm/autodetect.ts index 523bcb028..31eccfc8f 100644 --- a/core/llm/autodetect.ts +++ b/core/llm/autodetect.ts @@ -58,6 +58,7 @@ const PROVIDER_SUPPORTS_IMAGES: ModelProvider[] = [ "bedrock", "sagemaker", "continue-proxy", + "openrouter", ]; const MODEL_SUPPORTS_IMAGES: string[] = [ @@ -73,15 +74,18 @@ const MODEL_SUPPORTS_IMAGES: string[] = [ "sonnet", "opus", "haiku", + "pixtral", ]; function modelSupportsImages( provider: ModelProvider, model: string, title: string | undefined, - capabilities: ModelCapability | undefined + capabilities: ModelCapability | undefined, ): boolean { - if (capabilities?.uploadImage !== undefined) {return capabilities.uploadImage;} + if (capabilities?.uploadImage !== undefined) { + return capabilities.uploadImage; + } if (!PROVIDER_SUPPORTS_IMAGES.includes(provider)) { return false; } diff --git a/core/llm/constants.ts b/core/llm/constants.ts index cc1866d4b..52265d509 100644 --- a/core/llm/constants.ts +++ b/core/llm/constants.ts @@ -1,5 +1,5 @@ -const DEFAULT_MAX_TOKENS = 1024; -const DEFAULT_CONTEXT_LENGTH = 4096; +const DEFAULT_MAX_TOKENS = 2048; +const DEFAULT_CONTEXT_LENGTH = 8096; const DEFAULT_TEMPERATURE = 0.5; const DEFAULT_ARGS = { diff --git a/core/llm/constructMessages.ts b/core/llm/constructMessages.ts index aaf23563e..13d538be8 100644 --- a/core/llm/constructMessages.ts +++ b/core/llm/constructMessages.ts @@ -1,8 +1,91 @@ import { ChatHistory, ChatMessage, MessagePart } from "../index.js"; -export function constructMessages(history: ChatHistory): ChatMessage[] { +const SYSTEM_MESSAGE = `When generating new code: + +1. Always produce a single code block. +2. Never separate the code into multiple code blocks. +3. Only include the code that is being added. +4. Replace existing code with a "lazy" comment like this: "// ... existing code ..." +5. The "lazy" comment must always be a valid comment in the current context (e.g. "" for HTML, "// ... existing code ..." for JavaScript, "{/* ... existing code */}" for TSX, etc.) +6. You must always provide 1-2 lines of context above and below a "lazy" comment +7. If the user submits a code block that contains a filename in the language specifier, always include the filename in any code block you generate based on that file. The filename should be on the same line as the language specifier in your code block. + +Example 1: +Input: +\`\`\`test.js +import addition from "addition" + +class Calculator { + constructor() { + this.result = 0; + } + + add(number) { + this.result += number; + return this; + } +} +\`\`\` +User request: Add a subtract method + +Output: +\`\`\`javascript test.js +// ... existing code ... +import subtraction from "subtraction" + +class Calculator { + // ... existing code ... + + subtract(number) { + this.result -= number; + return this; + } +} +\`\`\` + +Example 2: +Input: +\`\`\`javascript test.js (6-9) +function helloWorld() {} +\`\`\` + +Output: +\`\`\`javascript test.js +function helloWorld() { + // New code here +} +\`\`\` + +Always follow these guidelines when generating code responses.`; + +function hasCodeBlockWithFilename(content: ChatMessage["content"]): boolean { + const contentStr = typeof content === "string" ? content : content[0].text; + + if (!contentStr) { + return false; + } + + const codeBlockRegex = /```[\w\W]*?\.[\w\W]*/; + return codeBlockRegex.test(contentStr); +} + +export function constructMessages( + history: ChatHistory, + model: string, +): ChatMessage[] { const msgs = []; + // Only using this system message with Sonnet right now + if ( + // hasCodeBlockWithFilename(history[0].message.content) && + model.includes("sonnet") + ) { + msgs.push({ + role: "system" as const, + content: SYSTEM_MESSAGE, + }); + } + for (let i = 0; i < history.length; i++) { const historyItem = history[i]; diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index 06cd4a3bb..0fbadf68b 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -332,7 +332,9 @@ function compileChatMessages( systemMessage: string | undefined = undefined, ): ChatMessage[] { const msgsCopy = msgs - ? msgs.map((msg) => ({ ...msg })).filter((msg) => msg.content !== "") + ? msgs + .map((msg) => ({ ...msg })) + .filter((msg) => msg.content !== "" && msg.role !== "system") : []; if (prompt) { @@ -343,10 +345,24 @@ function compileChatMessages( msgsCopy.push(promptMsg); } - if (systemMessage && systemMessage.trim() !== "") { + if ( + (systemMessage && systemMessage.trim() !== "") || + msgs?.[0].role === "system" + ) { + let content = ""; + if (msgs?.[0].role === "system") { + content = stripImages(msgs?.[0].content); + } + if (systemMessage && systemMessage.trim() !== "") { + const shouldAddNewLines = content !== ""; + if (shouldAddNewLines) { + content += "\n\n"; + } + content += systemMessage; + } const systemChatMsg: ChatMessage = { role: "system", - content: systemMessage, + content, }; // Insert as second to last // Later moved to top, but want second-priority to last user message diff --git a/core/llm/index.ts b/core/llm/index.ts index 9a1ddaf46..53c984b43 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -1,6 +1,7 @@ import { findLlmInfo } from "@continuedev/llm-info"; import Handlebars from "handlebars"; import { + CacheBehavior, ChatMessage, ChatMessageRole, CompletionOptions, @@ -102,6 +103,7 @@ export abstract class BaseLLM implements ILLM { llmRequestHook?: (model: string, prompt: string) => any; apiKey?: string; apiBase?: string; + cacheBehavior?: CacheBehavior; capabilities?: ModelCapability; engine?: string; @@ -120,8 +122,6 @@ export abstract class BaseLLM implements ILLM { watsonxApiVersion?: string; watsonxFullUrl?: string; - cacheSystemMessage?: boolean; - private _llmOptions: LLMOptions; constructor(_options: LLMOptions) { @@ -135,6 +135,7 @@ export abstract class BaseLLM implements ILLM { }; this.model = options.model; + // Use @continuedev/llm-info package to autodetect certain parameters const llmInfo = findLlmInfo(this.model); const templateType = @@ -149,7 +150,16 @@ export abstract class BaseLLM implements ILLM { this.completionOptions = { ...options.completionOptions, model: options.model || "gpt-4", - maxTokens: options.completionOptions?.maxTokens ?? DEFAULT_MAX_TOKENS, + maxTokens: + options.completionOptions?.maxTokens ?? + (llmInfo?.maxCompletionTokens + ? Math.min( + llmInfo.maxCompletionTokens, + // Even if the model has a large maxTokens, we don't want to use that every time, + // because it takes away from the context length + this.contextLength / 4, + ) + : DEFAULT_MAX_TOKENS), }; if (CompletionOptionsForModels[options.model as ModelName]) { this.completionOptions = mergeJson( @@ -174,6 +184,7 @@ export abstract class BaseLLM implements ILLM { this.apiKey = options.apiKey; this.aiGatewaySlug = options.aiGatewaySlug; this.apiBase = options.apiBase; + this.cacheBehavior = options.cacheBehavior; // for watsonx only this.watsonxUrl = options.watsonxUrl; @@ -183,8 +194,6 @@ export abstract class BaseLLM implements ILLM { this.watsonxApiVersion = options.watsonxApiVersion; this.watsonxFullUrl = options.watsonxFullUrl; - this.cacheSystemMessage = options.cacheSystemMessage; - if (this.apiBase && !this.apiBase.endsWith("/")) { this.apiBase = `${this.apiBase}/`; } @@ -252,16 +261,29 @@ export abstract class BaseLLM implements ILLM { prompt: string, completionOptions: CompletionOptions, ): string { - const dict = { contextLength: this.contextLength, ...completionOptions }; - const settings = Object.entries(dict) - .map(([key, value]) => `${key}: ${value}`) - .join("\n"); - return `Settings: -${settings} + const completionOptionsLog = JSON.stringify( + { + contextLength: this.contextLength, + ...completionOptions, + }, + null, + 2, + ); -############################################ + let requestOptionsLog = ""; + if (this.requestOptions) { + requestOptionsLog = JSON.stringify(this.requestOptions, null, 2); + } -${prompt}`; + return ( + "##### Completion options #####\n" + + completionOptionsLog + + (requestOptionsLog + ? "\n\n##### Request options #####\n" + requestOptionsLog + : "") + + "\n\n##### Prompt #####\n" + + prompt + ); } private _logTokensGenerated( @@ -271,7 +293,8 @@ ${prompt}`; ) { let promptTokens = this.countTokens(prompt); let generatedTokens = this.countTokens(completion); - Telemetry.capture( + + void Telemetry.capture( "tokens_generated", { model: model, @@ -281,12 +304,14 @@ ${prompt}`; }, true, ); - DevDataSqliteDb.logTokensGenerated( + + void DevDataSqliteDb.logTokensGenerated( model, this.providerName, promptTokens, generatedTokens, ); + logDevData("tokens_generated", { model: model, provider: this.providerName, @@ -332,11 +357,11 @@ ${prompt}`; ) { if (resp.url.includes("codestral.mistral.ai")) { throw new Error( - `You are using a Mistral API key, which is not compatible with the Codestral API. Please either obtain a Codestral API key, or use the Mistral API by setting "apiBase" to "https://api.mistral.ai/v1" in config.json.`, + "You are using a Mistral API key, which is not compatible with the Codestral API. Please either obtain a Codestral API key, or use the Mistral API by setting 'apiBase' to 'https://api.mistral.ai/v1' in config.json.", ); } else { throw new Error( - `You are using a Codestral API key, which is not compatible with the Mistral API. Please either obtain a Mistral API key, or use the the Codestral API by setting "apiBase" to "https://codestral.mistral.ai/v1" in config.json.`, + "You are using a Codestral API key, which is not compatible with the Mistral API. Please either obtain a Mistral API key, or use the the Codestral API by setting 'apiBase' to 'https://codestral.mistral.ai/v1' in config.json.", ); } } @@ -404,7 +429,7 @@ ${prompt}`; return formatted; } - async *_streamFim( + protected async *_streamFim( prefix: string, suffix: string, options: CompletionOptions, @@ -532,6 +557,7 @@ ${prompt}`; const completion = await this._complete(prompt, completionOptions); this._logTokensGenerated(completionOptions.model, prompt, completion); + if (log && this.writeLog) { await this.writeLog(`Completion:\n\n${completion}\n\n`); } @@ -594,6 +620,7 @@ ${prompt}`; } this._logTokensGenerated(completionOptions.model, prompt, completion); + if (log && this.writeLog) { await this.writeLog(`Completion:\n\n${completion}\n\n`); } diff --git a/core/llm/llms/Anthropic.ts b/core/llm/llms/Anthropic.ts index 320dd9798..f2182d851 100644 --- a/core/llm/llms/Anthropic.ts +++ b/core/llm/llms/Anthropic.ts @@ -35,17 +35,40 @@ class Anthropic extends BaseLLM { } private _convertMessages(msgs: ChatMessage[]): any[] { - const messages = msgs - .filter((m) => m.role !== "system") - .map((message) => { + const filteredmessages = msgs.filter((m) => m.role !== "system") + const lastTwoUserMsgIndices = filteredmessages + .map((msg, index) => (msg.role === "user" ? index : -1)) + .filter((index) => index !== -1).slice(-2); + + const messages = filteredmessages.map((message, filteredMsgIdx) => { + // Add cache_control parameter to the last two user messages + // The second-to-last because it retrieves potentially already cached contents, + // The last one because we want it cached for later retrieval. + // See: https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching + const addCaching = this.cacheBehavior?.cacheConversation && lastTwoUserMsgIndices.includes(filteredMsgIdx); + if (typeof message.content === "string") { - return message; + var chatMessage = { + ...message, + content: [{ + type: "text", + text: message.content, + ...(addCaching? { cache_control: { type: "ephemeral" } } : {}) + }] + }; + return chatMessage; } + return { ...message, - content: message.content.map((part) => { + content: message.content.map((part, contentIdx) => { if (part.type === "text") { - return part; + const newpart = { + ...part, + // If multiple text parts, only add cache_control to the last one + ...((addCaching && contentIdx == message.content.length - 1) ? { cache_control: { type: "ephemeral" } } : {}) + }; + return newpart; } return { type: "image", @@ -75,8 +98,10 @@ class Anthropic extends BaseLLM { messages: ChatMessage[], options: CompletionOptions, ): AsyncGenerator { - const shouldCacheSystemMessage = - !!this.systemMessage && !!this.cacheSystemMessage; + const shouldCacheSystemMessage = !!this.systemMessage && this.cacheBehavior?.cacheSystemMessage; + const systemMessage: string = stripImages( + messages.filter((m) => m.role === "system")[0]?.content, + ); const response = await this.fetch(new URL("messages", this.apiBase), { method: "POST", @@ -85,7 +110,7 @@ class Anthropic extends BaseLLM { Accept: "application/json", "anthropic-version": "2023-06-01", "x-api-key": this.apiKey as string, - ...(shouldCacheSystemMessage + ...(shouldCacheSystemMessage || this.cacheBehavior?.cacheConversation ? { "anthropic-beta": "prompt-caching-2024-07-31" } : {}), }, @@ -100,7 +125,7 @@ class Anthropic extends BaseLLM { cache_control: { type: "ephemeral" }, }, ] - : this.systemMessage, + : systemMessage, }), }); @@ -111,6 +136,7 @@ class Anthropic extends BaseLLM { } for await (const value of streamSse(response)) { + if (value.type == "message_start") console.log(value); if (value.delta?.text) { yield { role: "assistant", content: value.delta.text }; } diff --git a/core/llm/llms/Azure.ts b/core/llm/llms/Azure.ts index ce20b4ecc..be7d1c18c 100644 --- a/core/llm/llms/Azure.ts +++ b/core/llm/llms/Azure.ts @@ -1,8 +1,18 @@ -import { ModelProvider } from "../../index.js"; +import { LLMOptions, ModelProvider } from "../../index.js"; import OpenAI from "./OpenAI.js"; class Azure extends OpenAI { static providerName: ModelProvider = "azure"; + + static defaultOptions: Partial = { + apiVersion: "2024-02-15-preview", + apiType: "azure", + }; + + constructor(options: LLMOptions) { + super(options); + this.engine = options.model; + } } export default Azure; diff --git a/core/llm/llms/Bedrock.ts b/core/llm/llms/Bedrock.ts index db2603c03..485b87015 100644 --- a/core/llm/llms/Bedrock.ts +++ b/core/llm/llms/Bedrock.ts @@ -153,6 +153,7 @@ class Bedrock extends BaseLLM { try { return await fromIni({ profile: this.profile, + ignoreCache: true })(); } catch (e) { console.warn( diff --git a/core/llm/llms/BedrockImport.ts b/core/llm/llms/BedrockImport.ts index f53d4b15e..a265c7679 100644 --- a/core/llm/llms/BedrockImport.ts +++ b/core/llm/llms/BedrockImport.ts @@ -82,7 +82,8 @@ class BedrockImport extends BaseLLM { try { return await fromIni({ - profile: this.profile + profile: this.profile, + ignoreCache: true })(); } catch (e) { console.warn( diff --git a/core/llm/llms/Groq.ts b/core/llm/llms/Groq.ts index 7115bcc32..bc05263c9 100644 --- a/core/llm/llms/Groq.ts +++ b/core/llm/llms/Groq.ts @@ -12,6 +12,7 @@ class Groq extends OpenAI { "llama2-70b": "llama2-70b-4096", "mistral-8x7b": "mixtral-8x7b-32768", gemma: "gemma-7b-it", + gemma2: "gemma2-9b-it", "llama3-8b": "llama3-8b-8192", "llama3-70b": "llama3-70b-8192", "llama3.1-8b": "llama-3.1-8b-instant", diff --git a/core/llm/llms/HuggingFaceTGI.ts b/core/llm/llms/HuggingFaceTGI.ts index 947e15e6f..9636dbc63 100644 --- a/core/llm/llms/HuggingFaceTGI.ts +++ b/core/llm/llms/HuggingFaceTGI.ts @@ -3,6 +3,7 @@ import { BaseLLM } from "../index.js"; import { streamSse } from "../stream.js"; class HuggingFaceTGI extends BaseLLM { + private static MAX_STOP_TOKENS = 4; static providerName: ModelProvider = "huggingface-tgi"; static defaultOptions: Partial = { apiBase: "http://localhost:8080/", @@ -36,7 +37,10 @@ class HuggingFaceTGI extends BaseLLM { top_k: options.topK, presence_penalty: options.presencePenalty, frequency_penalty: options.frequencyPenalty, - stop: options.stop, + stop: options.stop?.slice( + 0, + this.maxStopWords ?? HuggingFaceTGI.MAX_STOP_TOKENS, + ), }; return finalOptions; diff --git a/core/llm/llms/Ollama.ts b/core/llm/llms/Ollama.ts index f830b7f0f..3b16d0456 100644 --- a/core/llm/llms/Ollama.ts +++ b/core/llm/llms/Ollama.ts @@ -61,7 +61,7 @@ class Ollama extends BaseLLM { this.completionOptions.stop.push(JSON.parse(value)); } catch (e) { console.warn( - "Error parsing stop parameter value \"{value}: ${e}", + 'Error parsing stop parameter value "{value}: ${e}', ); } break; @@ -132,11 +132,13 @@ class Ollama extends BaseLLM { private _convertArgs( options: CompletionOptions, prompt: string | ChatMessage[], + suffix?: string, ) { const finalOptions: any = { model: this._getModel(), raw: true, keep_alive: options.keepAlive ?? 60 * 30, // 30 minutes + suffix, options: { temperature: options.temperature, top_p: options.topP, @@ -248,6 +250,50 @@ class Ollama extends BaseLLM { } } + supportsFim(): boolean { + return true; + } + + protected async *_streamFim( + prefix: string, + suffix: string, + options: CompletionOptions, + ): AsyncGenerator { + const response = await this.fetch(this.getEndpoint("api/generate"), { + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${this.apiKey}`, + }, + body: JSON.stringify(this._convertArgs(options, prefix, suffix)), + }); + + let buffer = ""; + for await (const value of streamResponse(response)) { + // Append the received chunk to the buffer + buffer += value; + // Split the buffer into individual JSON chunks + const chunks = buffer.split("\n"); + buffer = chunks.pop() ?? ""; + + for (let i = 0; i < chunks.length; i++) { + const chunk = chunks[i]; + if (chunk.trim() !== "") { + try { + const j = JSON.parse(chunk); + if ("response" in j) { + yield j.response; + } else if ("error" in j) { + throw new Error(j.error); + } + } catch (e) { + throw new Error(`Error parsing Ollama response: ${e} ${chunk}`); + } + } + } + } + } + async listModels(): Promise { const response = await this.fetch( // localhost was causing fetch failed in pkg binary only for this Ollama endpoint diff --git a/core/llm/llms/OpenAI.ts b/core/llm/llms/OpenAI.ts index e37b43799..9366a7954 100644 --- a/core/llm/llms/OpenAI.ts +++ b/core/llm/llms/OpenAI.ts @@ -264,7 +264,7 @@ class OpenAI extends BaseLLM { } } - async *_streamFim( + protected async *_streamFim( prefix: string, suffix: string, options: CompletionOptions, diff --git a/core/llm/llms/WatsonX.ts b/core/llm/llms/WatsonX.ts index f7ea473e0..d9b61a3f1 100644 --- a/core/llm/llms/WatsonX.ts +++ b/core/llm/llms/WatsonX.ts @@ -20,8 +20,8 @@ class WatsonX extends BaseLLM { super(options); } async getBearerToken(): Promise<{ token: string; expiration: number }> { - if ( + this.watsonxFullUrl?.includes("cloud.ibm.com") || this.watsonxUrl?.includes("cloud.ibm.com") ) { // watsonx SaaS @@ -43,14 +43,12 @@ class WatsonX extends BaseLLM { }; } else { // watsonx Software - if ( - !this.watsonxCreds?.includes(":") - ) { - // Using ZenApiKey auth - return { - token: this.watsonxCreds ?? "", - expiration: -1, - }; + if (!this.watsonxCreds?.includes(":")) { + // Using ZenApiKey auth + return { + token: this.watsonxCreds ?? "", + expiration: -1, + }; } else { // Using username/password auth const userPass = this.watsonxCreds?.split(":"); @@ -85,7 +83,10 @@ class WatsonX extends BaseLLM { } getWatsonxEndpoint(): string { - return this.watsonxFullUrl ?? `${this.watsonxUrl}/ml/v1/text/generation_stream?version=${this.watsonxApiVersion}`; + return ( + this.watsonxFullUrl ?? + `${this.watsonxUrl}/ml/v1/text/generation_stream?version=${this.watsonxApiVersion}` + ); } static providerName: ModelProvider = "watsonx"; @@ -132,9 +133,8 @@ class WatsonX extends BaseLLM { protected _getHeaders() { return { "Content-Type": "application/json", - Authorization: `${ - watsonxConfig.accessToken.expiration === -1 ? "ZenApiKey" : "Bearer" - } ${watsonxConfig.accessToken.token}`, + Authorization: `${watsonxConfig.accessToken.expiration === -1 ? "ZenApiKey" : "Bearer" + } ${watsonxConfig.accessToken.token}`, }; } @@ -178,8 +178,7 @@ class WatsonX extends BaseLLM { watsonxConfig.accessToken = await this.getBearerToken(); } else { console.log( - `Reusing token (expires in ${ - (watsonxConfig.accessToken.expiration - now) / 60 + `Reusing token (expires in ${(watsonxConfig.accessToken.expiration - now) / 60 } mins)`, ); } @@ -191,31 +190,37 @@ class WatsonX extends BaseLLM { this.watsonxStopToken ?? (options.model?.includes("granite") ? "<|im_end|>" : undefined); const url = this.getWatsonxEndpoint(); - var response = await this.fetch( - url, - { - method: "POST", - headers: { - "Content-Type": "application/json", - Authorization: `${ - watsonxConfig.accessToken.expiration === -1 ? "ZenApiKey" : "Bearer" - } ${watsonxConfig.accessToken.token}`, - }, - body: JSON.stringify({ - input: messages[messages.length - 1].content, - parameters: { - decoding_method: "greedy", - max_new_tokens: options.maxTokens ?? 1024, - min_new_tokens: 1, - stop_sequences: stopToken ? [stopToken] : [], - include_stop_sequence: false, - repetition_penalty: 1, - }, - model_id: options.model, - project_id: this.watsonxProjectId - }), - }, - ); + const headers = this._getHeaders(); + + const parameters: any = { + decoding_method: "greedy", + max_new_tokens: options.maxTokens ?? 1024, + min_new_tokens: 1, + stop_sequences: stopToken ? [stopToken] : [], + include_stop_sequence: false, + repetition_penalty: 1, + }; + if (!!options.temperature) { + parameters.decoding_method = "sample"; + parameters.temperature = options.temperature; + parameters.top_p = options.topP || 1.0; + parameters.top_k = options.topK; + } + + const payload: any = { + input: messages[messages.length - 1].content, + parameters: parameters, + }; + if (!this.watsonxFullUrl) { + payload.model_id = options.model; + payload.project_id = this.watsonxProjectId; + } + + var response = await this.fetch(url, { + method: "POST", + headers: headers, + body: JSON.stringify(payload), + }); if (!response.ok || response.body === null) { throw new Error( @@ -223,7 +228,6 @@ class WatsonX extends BaseLLM { ); } else { for await (const value of streamResponse(response)) { - const lines = value.split("\n"); let generatedChunk = ""; let generatedTextIndex = undefined; diff --git a/core/llm/llms/index.ts b/core/llm/llms/index.ts index 2b894f418..dedae7795 100644 --- a/core/llm/llms/index.ts +++ b/core/llm/llms/index.ts @@ -6,7 +6,6 @@ import { ModelDescription, } from "../.."; import { renderTemplatedString } from "../../promptFiles/renderTemplatedString"; -import { DEFAULT_MAX_TOKENS } from "../constants"; import { BaseLLM } from "../index"; import Anthropic from "./Anthropic"; import Azure from "./Azure"; @@ -112,8 +111,7 @@ export async function llmFromDescription( model: (desc.model || cls.defaultOptions?.model) ?? "codellama-7b", maxTokens: finalCompletionOptions.maxTokens ?? - cls.defaultOptions?.completionOptions?.maxTokens ?? - DEFAULT_MAX_TOKENS, + cls.defaultOptions?.completionOptions?.maxTokens, }, systemMessage, writeLog, diff --git a/core/llm/llms/stubs/ContinueProxy.ts b/core/llm/llms/stubs/ContinueProxy.ts index 63712c993..e91e92e06 100644 --- a/core/llm/llms/stubs/ContinueProxy.ts +++ b/core/llm/llms/stubs/ContinueProxy.ts @@ -1,23 +1,15 @@ -import { CONTROL_PLANE_URL } from "../../../control-plane/client.js"; +import { ControlPlaneProxyInfo } from "../../../control-plane/analytics/IAnalyticsProvider.js"; import type { LLMOptions, ModelProvider } from "../../../index.js"; import OpenAI from "../OpenAI.js"; class ContinueProxy extends OpenAI { - private _workOsAccessToken: string | undefined = undefined; - - get workOsAccessToken(): string | undefined { - return this._workOsAccessToken; + set controlPlaneProxyInfo(value: ControlPlaneProxyInfo) { + this.apiKey = value.workOsAccessToken; + this.apiBase = new URL("openai/v1/", value.controlPlaneProxyUrl).toString(); } - set workOsAccessToken(value: string | undefined) { - if (this._workOsAccessToken !== value) { - this._workOsAccessToken = value; - this.apiKey = value; - } - } static providerName: ModelProvider = "continue-proxy"; static defaultOptions: Partial = { - apiBase: new URL("/model-proxy/v1", CONTROL_PLANE_URL).toString(), useLegacyCompletionsEndpoint: false, }; diff --git a/core/package-lock.json b/core/package-lock.json index a3332dc01..fe1e4c48d 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.10", - "@continuedev/llm-info": "^1.0.1", + "@continuedev/llm-info": "^1.0.2", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.0.2", "@typescript-eslint/eslint-plugin": "^7.8.0", @@ -25,7 +25,8 @@ "cheerio": "^1.0.0-rc.12", "commander": "^12.0.0", "comment-json": "^4.2.3", - "dbinfoz": "^0.1.4", + "dbinfoz": "^0.11.0", + "diff": "^7.0.0", "dotenv": "^16.4.5", "fastest-levenshtein": "^1.0.16", "follow-redirects": "^1.15.5", @@ -38,6 +39,7 @@ "jsdom": "^24.0.0", "launchdarkly-node-client-sdk": "^3.2.0", "llm-code-highlighter": "^0.0.14", + "lru-cache": "^10.2.2", "mac-ca": "^3.1.0", "node-fetch": "^3.3.2", "node-html-markdown": "^1.3.0", @@ -69,6 +71,7 @@ "@babel/preset-env": "^7.24.7", "@biomejs/biome": "1.6.4", "@google/generative-ai": "^0.11.4", + "@types/diff": "^5.2.2", "@types/follow-redirects": "^1.14.4", "@types/jest": "^29.5.12", "@types/jquery": "^3.5.29", @@ -1340,6 +1343,15 @@ "node": ">=6.9.0" } }, + "node_modules/@babel/helper-compilation-targets/node_modules/lru-cache": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", + "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", + "dev": true, + "dependencies": { + "yallist": "^3.0.2" + } + }, "node_modules/@babel/helper-compilation-targets/node_modules/semver": { "version": "6.3.1", "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", @@ -3128,9 +3140,9 @@ } }, "node_modules/@continuedev/llm-info": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/@continuedev/llm-info/-/llm-info-1.0.1.tgz", - "integrity": "sha512-fmRXuOSwJ9ogBPSDduoedHF3WVg1rge3o8SRRg1hkUagRnxwZqtQj1sS5SjQyAqjQv6VPMGPDEtD77Za/hc4Jg==" + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@continuedev/llm-info/-/llm-info-1.0.2.tgz", + "integrity": "sha512-B5VFcZlwlwQg6htbIjCjj3z/pj3I929BzgWowiLzxYC40ag+v3e/hM9EDGWCEdNIT+PDMchAwS67iNB+WhE7qg==" }, "node_modules/@esbuild/darwin-x64": { "version": "0.17.19", @@ -4756,6 +4768,12 @@ "integrity": "sha512-n7RlEEJ+4x4TS7ZQddTmNSxP+zziEG0TNsMfiRIxcIVXt71ENJ9ojeXmGO3wPoTdn7pJcU2xc3CJYMktNT6DPg==", "peer": true }, + "node_modules/@types/diff": { + "version": "5.2.2", + "resolved": "https://registry.npmjs.org/@types/diff/-/diff-5.2.2.tgz", + "integrity": "sha512-qVqLpd49rmJA2nZzLVsmfS/aiiBpfVE95dHhPVwG0NmSBAt+riPxnj53wq2oBq5m4Q2RF1IWFEUpnZTgrQZfEQ==", + "dev": true + }, "node_modules/@types/follow-redirects": { "version": "1.14.4", "resolved": "https://registry.npmjs.org/@types/follow-redirects/-/follow-redirects-1.14.4.tgz", @@ -6748,9 +6766,9 @@ } }, "node_modules/dbinfoz": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/dbinfoz/-/dbinfoz-0.1.4.tgz", - "integrity": "sha512-MB56+xS571ip7qoXqxdnOUtXebbWaqoZN+S++W51SQYJRSjQFGEIPucNmxgeQlBGJ1vM4mQNV47wzV6fcrezZg==", + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/dbinfoz/-/dbinfoz-0.11.0.tgz", + "integrity": "sha512-l7REBd9pwTBI6PWSk/dx+zCpSE2tiJdSKfApeoOajnSgyMJgkwGfhpPO2mV76MLQeKPaSm0mMKxmoqd38SaHmw==", "dependencies": { "mysql2": "^3.9.1", "pg": "^8.11.3", @@ -6922,6 +6940,14 @@ "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.1312386.tgz", "integrity": "sha512-DPnhUXvmvKT2dFA/j7B+riVLUt9Q6RKJlcppojL5CoRywJJKLDYnRlw0gTFKfgDPHP5E04UoB71SxoJlVZy8FA==" }, + "node_modules/diff": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/diff/-/diff-7.0.0.tgz", + "integrity": "sha512-PJWHUb1RFevKCwaFA9RlG5tCd+FO5iRh9A8HEtkmBH2Li03iJriB6m6JIN4rGz3K3JLawI7/veA1xzRKP6ISBw==", + "engines": { + "node": ">=0.3.1" + } + }, "node_modules/diff-sequences": { "version": "29.6.3", "resolved": "https://registry.npmjs.org/diff-sequences/-/diff-sequences-29.6.3.tgz", @@ -10465,12 +10491,11 @@ "integrity": "sha512-lcHwpNoggQTObv5apGNCTdJrO69eHOZMi4BNC+rTLER8iHAqGrUVeLh/irVIM7zTw2bOXA8T6uNPeujwOLg/2Q==" }, "node_modules/lru-cache": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", - "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", - "dev": true, - "dependencies": { - "yallist": "^3.0.2" + "version": "10.2.2", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.2.2.tgz", + "integrity": "sha512-9hp3Vp2/hFQUiIwKo8XCeFVnrg8Pk3TYNPIR7tJADKi5YfcF7vEaK7avFHTlSy3kOKYaJQaalfEo6YuXdceBOQ==", + "engines": { + "node": "14 || >=16.14" } }, "node_modules/mac-ca": { diff --git a/core/package.json b/core/package.json index f261f7078..b04da182b 100644 --- a/core/package.json +++ b/core/package.json @@ -15,6 +15,7 @@ "@babel/preset-env": "^7.24.7", "@biomejs/biome": "1.6.4", "@google/generative-ai": "^0.11.4", + "@types/diff": "^5.2.2", "@types/follow-redirects": "^1.14.4", "@types/jest": "^29.5.12", "@types/jquery": "^3.5.29", @@ -42,7 +43,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.621.0", "@aws-sdk/credential-providers": "^3.620.1", "@continuedev/config-types": "^1.0.10", - "@continuedev/llm-info": "^1.0.1", + "@continuedev/llm-info": "^1.0.2", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.0.2", "@typescript-eslint/eslint-plugin": "^7.8.0", @@ -54,7 +55,8 @@ "cheerio": "^1.0.0-rc.12", "commander": "^12.0.0", "comment-json": "^4.2.3", - "dbinfoz": "^0.1.4", + "dbinfoz": "^0.11.0", + "diff": "^7.0.0", "dotenv": "^16.4.5", "fastest-levenshtein": "^1.0.16", "follow-redirects": "^1.15.5", @@ -67,6 +69,7 @@ "jsdom": "^24.0.0", "launchdarkly-node-client-sdk": "^3.2.0", "llm-code-highlighter": "^0.0.14", + "lru-cache": "^10.2.2", "mac-ca": "^3.1.0", "node-fetch": "^3.3.2", "node-html-markdown": "^1.3.0", diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 73f55946c..d5920ca81 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -1,5 +1,3 @@ -import type { AutocompleteInput } from "../autocomplete/completionProvider"; -import { ProfileDescription } from "../config/ConfigHandler"; import type { BrowserSerializedContinueConfig, ChatMessage, @@ -10,12 +8,15 @@ import type { LLMFullCompletionOptions, MessageContent, ModelDescription, + ModelRoles, PersistedSessionInfo, RangeInFile, SerializedContinueConfig, SessionInfo, SiteIndexingConfig, } from "../"; +import type { AutocompleteInput } from "../autocomplete/completionProvider"; +import { ProfileDescription } from "../config/ConfigHandler"; export type ProtocolGeneratorType = AsyncGenerator<{ done?: boolean; @@ -50,7 +51,10 @@ export type ToCoreFromIdeOrWebviewProtocol = { "devdata/log": [{ tableName: string; data: any }, void]; "config/addOpenAiKey": [string, void]; "config/addModel": [ - { model: SerializedContinueConfig["models"][number] }, + { + model: SerializedContinueConfig["models"][number]; + role?: keyof ModelRoles; + }, void, ]; "config/newPromptFile": [undefined, void]; diff --git a/core/protocol/ideWebview.ts b/core/protocol/ideWebview.ts index 33a1ae2a9..774da7ee5 100644 --- a/core/protocol/ideWebview.ts +++ b/core/protocol/ideWebview.ts @@ -15,7 +15,7 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & { }, ]; openUrl: [string, void]; - applyToCurrentFile: [{ text: string }, void]; + applyToCurrentFile: [{ text: string; streamId: string }, void]; showTutorial: [undefined, void]; showFile: [{ filepath: string }, void]; openConfigJson: [undefined, void]; @@ -26,9 +26,17 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & { insertAtCursor: [{ text: string }, void]; copyText: [{ text: string }, void]; "jetbrains/editorInsetHeight": [{ height: number }, void]; + "vscode/openMoveRightMarkdown": [undefined, void]; setGitHubAuthToken: [{ token: string }, void]; + acceptDiff: [{ filepath: string }, void]; + rejectDiff: [{ filepath: string }, void]; }; +export interface ApplyState { + streamId: string; + status: "streaming" | "done" | "closed"; +} + export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & { setInactive: [undefined, void]; setTTSActive: [boolean, void]; @@ -61,4 +69,6 @@ export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & { setupLocalConfig: [undefined, void]; incrementFtc: [undefined, void]; openOnboardingCard: [undefined, void]; + applyCodeFromChat: [undefined, void]; + updateApplyState: [ApplyState, void]; }; diff --git a/core/test/util/dedentAndGetCommonWhitespace.test.ts b/core/test/util/dedentAndGetCommonWhitespace.test.ts new file mode 100644 index 000000000..5f3c6a4be --- /dev/null +++ b/core/test/util/dedentAndGetCommonWhitespace.test.ts @@ -0,0 +1,76 @@ +// File generated by Continue +import { dedentAndGetCommonWhitespace } from "../../util"; + +describe("dedentAndGetCommonWhitespace", () => { + let originalString: string; + + beforeEach(() => { + // Setup any global variables or states if needed + originalString = " line1\n line2\n line3"; + }); + + afterEach(() => { + // Tear down any changes to global variables or states if needed + originalString = ""; + }); + + test("should dedent and return common whitespace for a simple case", () => { + const input = " line1\n line2\n line3"; + const output = dedentAndGetCommonWhitespace(input); + expect(output).toEqual(["line1\nline2\nline3", " "]); + }); + + test("should handle empty string", () => { + const input = ""; + const output = dedentAndGetCommonWhitespace(input); + expect(output).toEqual(["", ""]); + }); + + test("should handle string with only whitespace", () => { + const input = " "; + const output = dedentAndGetCommonWhitespace(input); + expect(output).toEqual(["", ""]); + }); + + test("should handle string with mixed whitespace and content", () => { + const input = " line1\n line2\n line3"; + const output = dedentAndGetCommonWhitespace(input); + expect(output).toEqual([" line1\nline2\n line3", " "]); + }); + + test("should handle string with no common leading whitespace", () => { + const input = "line1\n line2\n line3"; + const output = dedentAndGetCommonWhitespace(input); + expect(output).toEqual([input, ""]); + }); + + test("should handle string with empty lines", () => { + const input = " line1\n\n line3"; + const output = dedentAndGetCommonWhitespace(input); + expect(output).toEqual(["line1\n\nline3", " "]); + }); + + test("should handle string with only empty lines", () => { + const input = "\n\n"; + const output = dedentAndGetCommonWhitespace(input); + expect(output).toEqual(["\n\n", ""]); + }); + + test("should handle string with tabs as whitespace", () => { + const input = "\tline1\n\tline2\n\tline3"; + const output = dedentAndGetCommonWhitespace(input); + expect(output).toEqual(["line1\nline2\nline3", "\t"]); + }); + + test("should handle string with mixed tabs and spaces", () => { + const input = "\t line1\n\t line2\n\t line3"; + const output = dedentAndGetCommonWhitespace(input); + expect(output).toEqual(["line1\nline2\nline3", "\t "]); + }); + + test("should handle string with different leading whitespace lengths", () => { + const input = " line1\n line2\n line3"; + const output = dedentAndGetCommonWhitespace(input); + expect(output).toEqual([" line1\nline2\n line3", " "]); + }); +}); diff --git a/core/test/util/getLastNPathParts.test.ts b/core/test/util/getLastNPathParts.test.ts new file mode 100644 index 000000000..ba72b4520 --- /dev/null +++ b/core/test/util/getLastNPathParts.test.ts @@ -0,0 +1,51 @@ +// File generated by Continue +import { getLastNPathParts } from "../../util"; + +describe("getLastNPathParts", () => { + const SEP_REGEX = /[\\/]+/; + + beforeAll(() => { + // Setup code if needed + }); + + afterAll(() => { + // Teardown code if needed + }); + + test("returns the last N parts of a filepath with forward slashes", () => { + const filepath = "home/user/documents/project/file.txt"; + expect(getLastNPathParts(filepath, 2)).toBe("project/file.txt"); + }); + + test("returns the last N parts of a filepath with backward slashes", () => { + const filepath = "C:\\home\\user\\documents\\project\\file.txt"; + expect(getLastNPathParts(filepath, 3)).toBe("documents/project/file.txt"); + }); + + test("returns the last part if N is 1", () => { + const filepath = "/home/user/documents/project/file.txt"; + expect(getLastNPathParts(filepath, 1)).toBe("file.txt"); + }); + + test("returns the entire path if N is greater than the number of parts", () => { + const filepath = "home/user/documents/project/file.txt"; + expect(getLastNPathParts(filepath, 10)).toBe( + "home/user/documents/project/file.txt", + ); + }); + + test("returns an empty string if N is 0", () => { + const filepath = "home/user/documents/project/file.txt"; + expect(getLastNPathParts(filepath, 0)).toBe(""); + }); + + test("handles paths with mixed forward and backward slashes", () => { + const filepath = "home\\user/documents\\project/file.txt"; + expect(getLastNPathParts(filepath, 3)).toBe("documents/project/file.txt"); + }); + + test("handles edge case with empty filepath", () => { + const filepath = ""; + expect(getLastNPathParts(filepath, 2)).toBe(""); + }); +}); diff --git a/core/test/util/lcs.test.ts b/core/test/util/lcs.test.ts new file mode 100644 index 000000000..da10cdf90 --- /dev/null +++ b/core/test/util/lcs.test.ts @@ -0,0 +1,40 @@ +// This file is generated by Continue +import { longestCommonSubsequence } from "../../util/lcs"; + +describe("longestCommonSubsequence", () => { + beforeAll(() => { + // Setup if needed + }); + + afterAll(() => { + // Teardown if needed + }); + + test("should return the longest common subsequence for non-empty strings", () => { + expect(longestCommonSubsequence("abcde", "ace")).toBe("ace"); + expect(longestCommonSubsequence("abc", "abc")).toBe("abc"); + expect(longestCommonSubsequence("abc", "def")).toBe(""); + }); + + test("should handle cases where one or both strings are empty", () => { + expect(longestCommonSubsequence("", "abc")).toBe(""); + expect(longestCommonSubsequence("abc", "")).toBe(""); + expect(longestCommonSubsequence("", "")).toBe(""); + }); + + test("should handle cases with no common subsequence", () => { + expect(longestCommonSubsequence("abc", "def")).toBe(""); + expect(longestCommonSubsequence("xyz", "abc")).toBe(""); + }); + + test("should handle cases with special characters", () => { + expect(longestCommonSubsequence("a!@#b$c", "!@#$")).toBe("!@#$"); + expect(longestCommonSubsequence("a!@#b$c", "xyz")).toBe(""); + }); + + test("should handle long strings efficiently", () => { + const str1 = "a".repeat(1000) + "b".repeat(1000); + const str2 = "a".repeat(1000) + "c".repeat(1000); + expect(longestCommonSubsequence(str1, str2)).toBe("a".repeat(1000)); + }); +}); diff --git a/core/test/util/merge.test.ts b/core/test/util/merge.test.ts new file mode 100644 index 000000000..a39a5bc30 --- /dev/null +++ b/core/test/util/merge.test.ts @@ -0,0 +1,100 @@ +// File generated by Continue +import { mergeJson } from "../../util/merge"; + +describe("mergeJson", () => { + it("should merge two simple JSON objects", () => { + const first = { a: 1, b: 2 }; + const second = { b: 3, c: 4 }; + const result = mergeJson(first, second); + expect(result).toEqual({ a: 1, b: 3, c: 4 }); + }); + + it('should overwrite values when mergeBehavior is "overwrite"', () => { + const first = { a: 1, b: 2 }; + const second = { b: 3, c: 4 }; + const result = mergeJson(first, second, "overwrite"); + expect(result).toEqual({ a: 1, b: 3, c: 4 }); + }); + + it("should merge nested objects", () => { + const first = { a: { b: 1 } }; + const second = { a: { c: 2 } }; + const result = mergeJson(first, second); + expect(result).toEqual({ a: { b: 1, c: 2 } }); + }); + + it("should merge arrays without mergeKeys", () => { + const first = { a: [1, 2] }; + const second = { a: [3, 4] }; + const result = mergeJson(first, second); + expect(result).toEqual({ a: [1, 2, 3, 4] }); + }); + + it("should merge arrays with mergeKeys", () => { + const first = { + a: [ + { id: 1, value: "first" }, + { id: 2, value: "second" }, + ], + }; + const second = { + a: [ + { id: 2, value: "updated" }, + { id: 3, value: "third" }, + ], + }; + const mergeKeys = { + a: (item1: any, item2: any) => item1.id === item2.id, + }; + const result = mergeJson(first, second, undefined, mergeKeys); + expect(result).toEqual({ + a: [ + { id: 1, value: "first" }, + { id: 2, value: "updated" }, + { id: 3, value: "third" }, + ], + }); + }); + + it("should handle non-object values correctly", () => { + const first = { a: 1, b: "string", c: true }; + const second = { a: 2, b: "new string", c: false }; + const result = mergeJson(first, second); + expect(result).toEqual({ a: 2, b: "new string", c: false }); + }); + + it("should handle null and undefined values correctly", () => { + const first = { a: 1, b: null }; + const second = { b: 2, c: undefined }; + const result = mergeJson(first, second); + expect(result).toEqual({ a: 1, b: 2, c: undefined }); + }); + + it("should handle empty objects", () => { + const first = {}; + const second = { a: 1 }; + const result = mergeJson(first, second); + expect(result).toEqual({ a: 1 }); + }); + + it("should handle empty second object", () => { + const first = { a: 1 }; + const second = {}; + const result = mergeJson(first, second); + expect(result).toEqual({ a: 1 }); + }); + + it("should handle errors gracefully", () => { + const first = { a: 1 }; + const second = { b: () => {} }; // Functions are not serializable in JSON + const result = mergeJson(first, second); + expect(result).toEqual({ a: 1, b: expect.any(Function) }); + }); + + it("should merge deeply nested objects", () => { + const first = { a: { b: { c: 1 } } }; + const second = { a: { b: { d: 2 } } }; + const result = mergeJson(first, second); + expect(result).toEqual({ a: { b: { c: 1, d: 2 } } }); + }); +}); diff --git a/core/test/util/ranges/getRangeInString.test.ts b/core/test/util/ranges/getRangeInString.test.ts new file mode 100644 index 000000000..e0a4df67a --- /dev/null +++ b/core/test/util/ranges/getRangeInString.test.ts @@ -0,0 +1,105 @@ +// This file is generated by Continue + +import { getRangeInString } from "../../../util/ranges"; + +describe.skip("getRangeInString", () => { + let content: string; + + beforeEach(() => { + content = `Line 1 +Line 2 +Line 3 +Line 4 +Line 5`; + }); + + afterEach(() => { + content = ""; + }); + + test("should return substring within the same line", () => { + const range = { + start: { line: 1, character: 0 }, + end: { line: 1, character: 4 }, + }; + expect(getRangeInString(content, range)).toBe("Line"); + }); + + test("should return substring spanning multiple lines", () => { + const range = { + start: { line: 1, character: 2 }, + end: { line: 3, character: 3 }, + }; + const expected = `ne 2 +Line 3 +Line 4`; + expect(getRangeInString(content, range)).toBe(expected); + }); + + test("should handle range that starts and ends at the same character", () => { + const range = { + start: { line: 2, character: 0 }, + end: { line: 2, character: 0 }, + }; + expect(getRangeInString(content, range)).toBe("L"); + }); + + test("should handle range that spans entire content", () => { + const range = { + start: { line: 0, character: 0 }, + end: { line: 4, character: 5 }, + }; + expect(getRangeInString(content, range)).toBe(content); + }); + + test("should handle range that spans to the end of the last line", () => { + const range = { + start: { line: 3, character: 2 }, + end: { line: 4, character: 5 }, + }; + const expected = `ne 4 +Line 5`; + expect(getRangeInString(content, range)).toBe(expected); + }); + + test("should handle empty content", () => { + content = ""; + const range = { + start: { line: 0, character: 0 }, + end: { line: 0, character: 0 }, + }; + expect(getRangeInString(content, range)).toBe(""); + }); + + test("should handle invalid range (start line > end line)", () => { + const range = { + start: { line: 3, character: 0 }, + end: { line: 2, character: 0 }, + }; + expect(getRangeInString(content, range)).toBe(""); + }); + + test("should handle invalid range (start character > end character on same line)", () => { + const range = { + start: { line: 1, character: 5 }, + end: { line: 1, character: 2 }, + }; + expect(getRangeInString(content, range)).toBe(""); + }); + + test("should handle range that starts and ends at the same line but different characters", () => { + const range = { + start: { line: 1, character: 2 }, + end: { line: 1, character: 6 }, + }; + expect(getRangeInString(content, range)).toBe("ne 2"); + }); + + test("should handle range that starts and ends at the same line and same characters", () => { + const range = { + start: { line: 1, character: 2 }, + end: { line: 1, character: 2 }, + }; + expect(getRangeInString(content, range)).toBe("n"); + }); +}); diff --git a/core/test/util/ranges/intersection.test.ts b/core/test/util/ranges/intersection.test.ts new file mode 100644 index 000000000..397dbc1a8 --- /dev/null +++ b/core/test/util/ranges/intersection.test.ts @@ -0,0 +1,123 @@ +// This file is generated by Continue + +import { intersection } from "../../../util/ranges"; + +interface Position { + line: number; + character: number; +} + +interface Range { + start: Position; + end: Position; +} + +describe("intersection", () => { + let rangeA: Range; + let rangeB: Range; + + beforeEach(() => { + rangeA = { + start: { line: 1, character: 0 }, + end: { line: 3, character: 5 }, + }; + + rangeB = { + start: { line: 2, character: 2 }, + end: { line: 4, character: 0 }, + }; + }); + + test("returns correct intersection for overlapping ranges", () => { + const result = intersection(rangeA, rangeB); + expect(result).toEqual({ + start: { line: 2, character: 2 }, + end: { line: 3, character: 5 }, + }); + }); + + test("returns null for non-overlapping ranges", () => { + rangeA = { + start: { line: 1, character: 0 }, + end: { line: 2, character: 0 }, + }; + + rangeB = { + start: { line: 3, character: 0 }, + end: { line: 4, character: 0 }, + }; + + const result = intersection(rangeA, rangeB); + expect(result).toBeNull(); + }); + + // TODO + test.skip("returns correct intersection for single line overlap", () => { + rangeA = { + start: { line: 1, character: 0 }, + end: { line: 1, character: 5 }, + }; + + rangeB = { + start: { line: 1, character: 3 }, + end: { line: 2, character: 0 }, + }; + + const result = intersection(rangeA, rangeB); + expect(result).toEqual({ + start: { line: 1, character: 3 }, + end: { line: 1, character: 5 }, + }); + }); + + test("returns null for single line non-overlapping ranges", () => { + rangeA = { + start: { line: 1, character: 0 }, + end: { line: 1, character: 2 }, + }; + + rangeB = { + start: { line: 1, character: 3 }, + end: { line: 1, character: 5 }, + }; + + const result = intersection(rangeA, rangeB); + expect(result).toBeNull(); + }); + + test("returns correct intersection when one range is fully within another", () => { + rangeA = { + start: { line: 1, character: 0 }, + end: { line: 4, character: 5 }, + }; + + rangeB = { + start: { line: 2, character: 2 }, + end: { line: 3, character: 3 }, + }; + + const result = intersection(rangeA, rangeB); + expect(result).toEqual({ + start: { line: 2, character: 2 }, + end: { line: 3, character: 3 }, + }); + }); + + test("returns correct intersection when ranges touch at the edge", () => { + rangeA = { + start: { line: 1, character: 0 }, + end: { line: 2, character: 0 }, + }; + + rangeB = { + start: { line: 2, character: 0 }, + end: { line: 3, character: 0 }, + }; + + const result = intersection(rangeA, rangeB); + expect(result).toEqual({ + start: { line: 2, character: 0 }, + end: { line: 2, character: 0 }, + }); + }); +}); diff --git a/core/test/util/ranges/maxMinPosition.test.ts b/core/test/util/ranges/maxMinPosition.test.ts new file mode 100644 index 000000000..0468df1cd --- /dev/null +++ b/core/test/util/ranges/maxMinPosition.test.ts @@ -0,0 +1,70 @@ +import { maxPosition, minPosition } from "../../../util/ranges"; + +// This file is generated by Continue +interface Position { + line: number; + character: number; +} + +describe("Position comparison functions", () => { + let pos1: Position; + let pos2: Position; + let pos3: Position; + let pos4: Position; + + beforeAll(() => { + // Setup: Initializing positions + pos1 = { line: 1, character: 5 }; + pos2 = { line: 2, character: 3 }; + pos3 = { line: 1, character: 7 }; + pos4 = { line: 2, character: 3 }; // Same as pos2 to test equality + }); + + describe("maxPosition", () => { + it("should return the position with the greater line number", () => { + expect(maxPosition(pos1, pos2)).toEqual(pos2); + }); + + it("should return the position with the greater character number when lines are equal", () => { + expect(maxPosition(pos1, pos3)).toEqual(pos3); + }); + + it("should return the first position when both positions are equal", () => { + expect(maxPosition(pos2, pos4)).toEqual(pos2); + }); + + it("should handle positions with negative line numbers", () => { + const posNegative = { line: -1, character: 0 }; + expect(maxPosition(posNegative, pos1)).toEqual(pos1); + }); + + it("should handle positions with negative character numbers", () => { + const posNegativeChar = { line: 1, character: -1 }; + expect(maxPosition(posNegativeChar, pos1)).toEqual(pos1); + }); + }); + + describe("minPosition", () => { + it("should return the position with the lesser line number", () => { + expect(minPosition(pos1, pos2)).toEqual(pos1); + }); + + it("should return the position with the lesser character number when lines are equal", () => { + expect(minPosition(pos1, pos3)).toEqual(pos1); + }); + + it("should return the first position when both positions are equal", () => { + expect(minPosition(pos2, pos4)).toEqual(pos2); + }); + + it("should handle positions with negative line numbers", () => { + const posNegative = { line: -1, character: 0 }; + expect(minPosition(posNegative, pos1)).toEqual(posNegative); + }); + + it("should handle positions with negative character numbers", () => { + const posNegativeChar = { line: 1, character: -1 }; + expect(minPosition(posNegativeChar, pos1)).toEqual(posNegativeChar); + }); + }); +}); diff --git a/core/test/util/ranges/union.test.ts b/core/test/util/ranges/union.test.ts new file mode 100644 index 000000000..9d06a97b4 --- /dev/null +++ b/core/test/util/ranges/union.test.ts @@ -0,0 +1,92 @@ +import { union } from "../../../util/ranges"; + +// This file is generated by Continue +interface Position { + line: number; + character: number; +} + +interface Range { + start: Position; + end: Position; +} + +describe("union", () => { + let rangeA: Range; + let rangeB: Range; + + beforeEach(() => { + rangeA = { + start: { line: 1, character: 0 }, + end: { line: 3, character: 5 }, + }; + + rangeB = { + start: { line: 2, character: 3 }, + end: { line: 4, character: 2 }, + }; + }); + + test("should return the union of two overlapping ranges", () => { + const result = union(rangeA, rangeB); + expect(result).toEqual({ + start: { line: 1, character: 0 }, + end: { line: 4, character: 2 }, + }); + }); + + test("should return the union when ranges are identical", () => { + const result = union(rangeA, rangeA); + expect(result).toEqual(rangeA); + }); + + test("should return the union when ranges do not overlap but are adjacent", () => { + rangeB = { + start: { line: 3, character: 5 }, + end: { line: 4, character: 2 }, + }; + const result = union(rangeA, rangeB); + expect(result).toEqual({ + start: { line: 1, character: 0 }, + end: { line: 4, character: 2 }, + }); + }); + + test("should return the union when one range is completely within the other", () => { + rangeB = { + start: { line: 2, character: 1 }, + end: { line: 2, character: 4 }, + }; + const result = union(rangeA, rangeB); + expect(result).toEqual(rangeA); + }); + + test("should return the union when ranges do not overlap and are not adjacent", () => { + rangeB = { + start: { line: 4, character: 3 }, + end: { line: 5, character: 1 }, + }; + const result = union(rangeA, rangeB); + expect(result).toEqual({ + start: { line: 1, character: 0 }, + end: { line: 5, character: 1 }, + }); + }); + + // TODO + test.skip("should handle edge case where start and end lines are the same", () => { + rangeA = { + start: { line: 1, character: 0 }, + end: { line: 1, character: 5 }, + }; + rangeB = { + start: { line: 1, character: 3 }, + end: { line: 1, character: 7 }, + }; + const result = union(rangeA, rangeB); + expect(result).toEqual({ + start: { line: 1, character: 0 }, + end: { line: 1, character: 7 }, + }); + }); +}); diff --git a/core/util/fetchFavicon.ts b/core/util/fetchFavicon.ts new file mode 100644 index 000000000..8b1c8616a --- /dev/null +++ b/core/util/fetchFavicon.ts @@ -0,0 +1,65 @@ +import { JSDOM } from "jsdom"; + +export async function findFaviconPath(url: URL): Promise { + const baseUrl = `${url.protocol}//${url.hostname}`; + + try { + const response = await fetch(baseUrl); + if (!response.ok) { + throw new Error(`HTTP error! status: ${response.status}`); + } + + const html = await response.text(); + const dom = new JSDOM(html); + const document = dom.window.document; + + // Look for favicon in tags + const linkTags = document.querySelectorAll('link[rel*="icon"]'); + + for (const link of linkTags) { + const href = link.getAttribute("href"); + if (href) { + return new URL(href, baseUrl).toString(); + } + } + } catch (error) { + console.debug(`Failed to fetch favicon for ${baseUrl}: ${error}`); + } + + console.debug(`Failed to find favicon for ${baseUrl}`); + return undefined; +} + +export async function getFaviconBase64( + faviconUrl: string, +): Promise { + try { + const response = await fetch(faviconUrl); + + if (!response.ok) { + throw new Error(`HTTP error! status: ${response.status}`); + } + + const arrayBuffer = await response.arrayBuffer(); + const base64 = btoa( + new Uint8Array(arrayBuffer).reduce( + (data, byte) => data + String.fromCharCode(byte), + "", + ), + ); + const mimeType = response.headers.get("content-type") || "image/x-icon"; + + return `data:${mimeType};base64,${base64}`; + } catch (error) { + console.debug(`Failed to fetch favicon from ${faviconUrl}: ${error}`); + return undefined; + } +} + +export async function fetchFavicon(url: URL): Promise { + const faviconPath = await findFaviconPath(url); + if (faviconPath) { + return getFaviconBase64(faviconPath); + } + return undefined; +} diff --git a/core/util/generateRepoMap.ts b/core/util/generateRepoMap.ts new file mode 100644 index 000000000..785a62c41 --- /dev/null +++ b/core/util/generateRepoMap.ts @@ -0,0 +1,213 @@ +import fs from "node:fs"; +import path from "node:path"; +import { IDE, ILLM } from ".."; +import { CodeSnippetsCodebaseIndex } from "../indexing/CodeSnippetsIndex"; +import { walkDirAsync } from "../indexing/walkDir"; +import { pruneLinesFromTop } from "../llm/countTokens"; +import { getRepoMapFilePath } from "./paths"; + +export interface RepoMapOptions { + includeSignatures?: boolean; + dirs?: string[]; +} + +class RepoMapGenerator { + private llm: ILLM; + private ide: IDE; + private options: RepoMapOptions; + private maxRepoMapTokens: number; + + private repoMapPath: string = getRepoMapFilePath(); + private writeStream: fs.WriteStream = fs.createWriteStream(this.repoMapPath); + private contentTokens: number = 0; + private repoMapDirs: string[] = []; + private allPathsInDirs: Set = new Set(); + private pathsInDirsWithSnippets: Set = new Set(); + + private BATCH_SIZE = 100; + private REPO_MAX_CONTEXT_LENGTH_RATIO = 0.5; + private PREAMBLE = + "Below is a repository map. \n" + + "For each file in the codebase, " + + "this map contains the name of the file, and the signature for any " + + "classes, methods, or functions in the file.\n\n"; + + constructor(llm: ILLM, ide: IDE, options: RepoMapOptions) { + this.llm = llm; + this.ide = ide; + this.options = options; + this.maxRepoMapTokens = + llm.contextLength * this.REPO_MAX_CONTEXT_LENGTH_RATIO; + } + + async generate(): Promise { + this.repoMapDirs = this.options.dirs ?? (await this.ide.getWorkspaceDirs()); + this.allPathsInDirs = await this.getAllPathsInDirs(); + + await this.initializeWriteStream(); + await this.processPathsAndSignatures(); + + this.writeStream.end(); + this.logRepoMapGeneration(); + + return fs.readFileSync(this.repoMapPath, "utf8"); + } + + private async initializeWriteStream(): Promise { + await this.writeToStream(this.PREAMBLE); + this.contentTokens += this.llm.countTokens(this.PREAMBLE); + } + + private async getAllPathsInDirs(): Promise> { + const paths = new Set(); + + for (const dir of this.repoMapDirs) { + for await (const filepath of walkDirAsync(dir, this.ide)) { + paths.add(filepath.replace(dir, "").slice(1)); + } + } + + return paths; + } + + private async processPathsAndSignatures(): Promise { + let offset = 0; + while (true) { + const { groupedByPath, hasMore } = + await CodeSnippetsCodebaseIndex.getPathsAndSignatures( + this.repoMapDirs, + offset, + this.BATCH_SIZE, + ); + await this.processBatch(groupedByPath); + if (!hasMore || this.contentTokens >= this.maxRepoMapTokens) { + break; + } + offset += this.BATCH_SIZE; + } + await this.writeRemainingPaths(); + } + + private async processBatch( + groupedByPath: Record, + ): Promise { + for (const [absolutePath, signatures] of Object.entries(groupedByPath)) { + const content = await this.processFile(absolutePath, signatures); + + if (content) { + await this.writeToStream(content); + } + } + } + + private async processFile( + absolutePath: string, + signatures: string[], + ): Promise { + const workspaceDir = + this.repoMapDirs.find((dir) => absolutePath.startsWith(dir)) || ""; + const relativePath = path.relative(workspaceDir, absolutePath); + + let fileContent: string; + + try { + fileContent = await fs.promises.readFile(absolutePath, "utf8"); + } catch (err) { + console.error( + "Failed to read file:\n" + + ` Path: ${absolutePath}\n` + + ` Error: ${err instanceof Error ? err.message : String(err)}`, + ); + + return; + } + + const filteredSignatures = signatures.filter( + (signature) => signature.trim() !== fileContent.trim(), + ); + + if (filteredSignatures.length > 0) { + this.pathsInDirsWithSnippets.add(relativePath); + } + + return this.generateContentForPath(relativePath, filteredSignatures); + } + + private generateContentForPath( + relativePath: string, + signatures: string[], + ): string { + if (this.options.includeSignatures === false) { + return `${relativePath}\n`; + } + + let content = `${relativePath}:\n`; + + for (const signature of signatures.slice(0, -1)) { + content += `${this.indentMultilineString(signature)}\n\t...\n`; + } + + content += `${this.indentMultilineString( + signatures[signatures.length - 1], + )}\n\n`; + + return content; + } + + private async writeToStream(content: string): Promise { + const tokens = this.llm.countTokens(content); + + if (this.contentTokens + tokens > this.maxRepoMapTokens) { + content = pruneLinesFromTop( + content, + this.maxRepoMapTokens - this.contentTokens, + this.llm.model, + ); + } + + this.contentTokens += this.llm.countTokens(content); + + await new Promise((resolve) => this.writeStream.write(content, resolve)); + } + + private async writeRemainingPaths(): Promise { + const pathsWithoutSnippets = new Set( + [...this.allPathsInDirs].filter( + (x) => !this.pathsInDirsWithSnippets.has(x), + ), + ); + + if (pathsWithoutSnippets.size > 0) { + await this.writeToStream(Array.from(pathsWithoutSnippets).join("\n")); + } + } + + private logRepoMapGeneration(): void { + console.debug( + `Generated repo map for ${this.repoMapDirs.join(", ")} at ${ + this.repoMapPath + }`, + ); + if (this.contentTokens >= this.maxRepoMapTokens) { + console.debug( + "Full repo map was unable to be generated due to context window limitations", + ); + } + } + + private indentMultilineString(str: string) { + return str + .split("\n") + .map((line: any) => "\t" + line) + .join("\n"); + } +} + +export default async function generateRepoMap( + llm: ILLM, + ide: IDE, + options: RepoMapOptions, +): Promise { + const generator = new RepoMapGenerator(llm, ide, options); + return generator.generate(); +} diff --git a/core/util/parameters.ts b/core/util/parameters.ts index b413a869e..88c7d38a6 100644 --- a/core/util/parameters.ts +++ b/core/util/parameters.ts @@ -20,6 +20,7 @@ export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = { recentLinePrefixMatchMinLength: 7, disableInFiles: undefined, useImports: true, + useRootPathContext: true, }; export const COUNT_COMPLETION_REJECTED_AFTER = 10_000; diff --git a/core/util/repoMap.ts b/core/util/repoMap.ts deleted file mode 100644 index 6c0a73e1f..000000000 --- a/core/util/repoMap.ts +++ /dev/null @@ -1,131 +0,0 @@ -import fs from "node:fs"; -import path from "node:path"; -import { IDE, ILLM } from ".."; -import { CodeSnippetsCodebaseIndex } from "../indexing/CodeSnippetsIndex"; -import { walkDirAsync } from "../indexing/walkDir"; -import { pruneLinesFromTop } from "../llm/countTokens"; -import { getRepoMapFilePath } from "./paths"; - -const repoMapPreamble = - "Below is a repository map. \n" + - "For each file in the codebase, " + - "this map contains the name of the file, and the signature for any " + - "classes, methods, or functions in the file.\n\n"; - -// The max percent of the context window we will take -const REPO_MAX_CONTEXT_LENGTH_RATIO = 0.5; - -function indentMultilineString(str: string) { - return str - .split("\n") - .map((line: any) => "\t" + line) - .join("\n"); -} - -export interface RepoMapOptions { - signatures?: boolean; - dirs?: string[]; -} - -async function generateRepoMap(llm: ILLM, ide: IDE, options?: RepoMapOptions) { - const repoMapPath = getRepoMapFilePath(); - const dirs = options?.dirs ?? (await ide.getWorkspaceDirs()); - const maxRepoMapTokens = llm.contextLength * REPO_MAX_CONTEXT_LENGTH_RATIO; - - const pathsWithoutSnippets = new Set(); - for (const dir of dirs) { - for await (const filepath of walkDirAsync(dir, ide)) { - pathsWithoutSnippets.add(filepath.replace(dir, "").slice(1)); - } - } - - if (fs.existsSync(repoMapPath)) { - console.debug(`Overwriting existing repo map at ${repoMapPath}`); - } - - const writeStream = fs.createWriteStream(repoMapPath); - await new Promise((resolve) => writeStream.write(repoMapPreamble, resolve)); - - let curTokens = llm.countTokens(repoMapPreamble); - let offset = 0; - const batchSize = 100; - - while (true) { - const { groupedByPath, hasMore } = - await CodeSnippetsCodebaseIndex.getPathsAndSignatures( - dirs, - offset, - batchSize, - ); - - let content = ""; - - for (const [absolutePath, signatures] of Object.entries(groupedByPath)) { - const workspaceDir = - dirs.find((dir) => absolutePath.startsWith(dir)) || ""; - - const relativePath = path.relative(workspaceDir, absolutePath); - - pathsWithoutSnippets.delete(relativePath); - - if (options?.signatures !== false) { - content += `${relativePath}:\n`; - for (const signature of signatures.slice(0, -1)) { - content += `${indentMultilineString(signature)}\n\t...\n`; - } - if (signatures.length > 0) { - // Don't add the trailing ellipsis for the last entry - content += `${indentMultilineString( - signatures[signatures.length - 1], - )}\n\n`; - } - } else { - // No signatures mode - content += `${relativePath}\n`; - } - } - - const contentTokens = llm.countTokens(content); - - if (curTokens + contentTokens >= maxRepoMapTokens) { - // Fit what we can, then stop - const prunedContent = pruneLinesFromTop( - content, - maxRepoMapTokens - curTokens, - llm.model, - ); - await new Promise((resolve) => writeStream.write(prunedContent, resolve)); - break; - } else { - await new Promise((resolve) => writeStream.write(content, resolve)); - } - - curTokens += contentTokens; - - if (!hasMore) { - break; - } - - offset += batchSize; - } - - const content = Array.from(pathsWithoutSnippets).join("\n"); - if (content.length > 0) { - await new Promise((resolve) => writeStream.write(content, resolve)); - } - - writeStream.end(); - console.debug(`Generated repo map at ${repoMapPath}`); - - if (curTokens >= maxRepoMapTokens) { - console.debug( - "Full repo map was unable to be genereated due to context window limitations", - ); - } - - const repoMap = fs.readFileSync(repoMapPath, "utf8"); - - return repoMap; -} - -export default generateRepoMap; diff --git a/core/util/treeSitter.ts b/core/util/treeSitter.ts index 204e2e3df..08cfe64d1 100644 --- a/core/util/treeSitter.ts +++ b/core/util/treeSitter.ts @@ -45,6 +45,7 @@ export const supportedLanguages: { [key: string]: string } = { mjs: "javascript", cjs: "javascript", py: "python", + ipynb: "python", pyw: "python", pyi: "python", el: "elisp", @@ -128,6 +129,11 @@ export async function getLanguageForFile( export enum TSQueryType { CodeSnippets = "code-snippet-queries", Imports = "import-queries", + // Used in RootPathContextService.ts + FunctionDeclaration = "root-path-context-queries/function_declaration", + MethodDefinition = "root-path-context-queries/method_definition", + FunctionDefinition = "root-path-context-queries/function_definition", + MethodDeclaration = "root-path-context-queries/method_declaration", } export async function getQueryForFile( diff --git a/docs/docs/chat/context-selection.md b/docs/docs/chat/context-selection.md index 2e2e7aa3d..ebdb41185 100644 --- a/docs/docs/chat/context-selection.md +++ b/docs/docs/chat/context-selection.md @@ -19,27 +19,27 @@ You can include the currently open file as context by pressing `cmd/ctrl + opt + ## Specific file -You can include a specific file in your current workspace as context by typing [`@files`](../customize/context-providers.md#files) and selecting the file. +You can include a specific file in your current workspace as context by typing [`@Files`](../customize/context-providers.md#files) and selecting the file. ## Specific folder -You can include a folder in your current workspace as context by typing [`@directory`](../customize/context-providers.md#folders) and selecting the directory. It [works like `@codebase`](../customize/deep-dives/codebase.md) but only includes the files in the selected directory. +You can include a folder in your current workspace as context by typing [`@Folder`](../customize/context-providers.md#folders) and selecting the directory. It [works like `@Codebase`](../customize/deep-dives/codebase.md) but only includes the files in the selected folder. ## Entire codebase -You can include your entire codebase as context by typing [`@codebase`](../customize/context-providers.md#codebase-retrieval). You can learn about how @codebase works [here](../customize/deep-dives/codebase.md). +You can include your entire codebase as context by typing [`@Codebase`](../customize/context-providers.md#codebase-retrieval). You can learn about how @Codebase works [here](../customize/deep-dives/codebase.md). ## Documentation site -You can include a documentation site as context by typing [`@docs`](../customize/context-providers.md#documentation) and selecting the documentation site. You can learn about how @docs works [here](../customize/deep-dives/docs.md). +You can include a documentation site as context by typing [`@Docs`](../customize/context-providers.md#documentation) and selecting the documentation site. You can learn about how @Docs works [here](../customize/deep-dives/docs.md). ## Terminal contents -You can include the contents of the terminal in your IDE as context by typing [`@terminal`](../customize/context-providers.md#terminal). +You can include the contents of the terminal in your IDE as context by typing [`@Terminal`](../customize/context-providers.md#terminal). ## Git diff -You can include all of the changes you've made to your current branch by typing [`@diff`](../customize/context-providers.md#git-diff). +You can include all of the changes you've made to your current branch by typing [`@Git Diff`](../customize/context-providers.md#git-diff). ## Other context diff --git a/docs/docs/chat/how-it-works.md b/docs/docs/chat/how-it-works.md index 7d0d382a5..b5e8aaece 100644 --- a/docs/docs/chat/how-it-works.md +++ b/docs/docs/chat/how-it-works.md @@ -11,4 +11,4 @@ The model response is then streamed directly back to the sidebar. Each code sect If you would like to view the exact prompt that is sent to the model during Chat, you can [view this in the prompt logs](troubleshooting.md#llm-prompt-logs). -You can learn more about how `@codebase` works [here](../customize/deep-dives/codebase.md) and `@docs` [here](../customize/deep-dives/docs.md). +You can learn more about how `@Codebase` works [here](../customize/deep-dives/codebase.md) and `@Docs` [here](../customize/deep-dives/docs.md). diff --git a/docs/docs/chat/how-to-customize.md b/docs/docs/chat/how-to-customize.md index a91720213..943d5e7ac 100644 --- a/docs/docs/chat/how-to-customize.md +++ b/docs/docs/chat/how-to-customize.md @@ -7,7 +7,7 @@ sidebar_position: 5 There are a number of different ways to customize Chat -- You can configure [`@codebase`](../customize/deep-dives/codebase.md) +- You can configure [`@Codebase`](../customize/deep-dives/codebase.md) - You can create your own [custom code RAG](../customize/tutorials/custom-code-rag.md) -- You can configure [`@docs`](../customize/deep-dives/docs.md) +- You can configure [`@Docs`](../customize/deep-dives/docs.md) - You can [build your own context provider](../customize/tutorials/build-your-own-context-provider.md) diff --git a/docs/docs/chat/how-to-use-it.md b/docs/docs/chat/how-to-use-it.md index 37e8384ab..509702b4f 100644 --- a/docs/docs/chat/how-to-use-it.md +++ b/docs/docs/chat/how-to-use-it.md @@ -10,7 +10,7 @@ sidebar_position: 1 ## How to use it -Chat makes it easy to ask for help from an LLM without needing to leave the IDE. You send it a task, including any relevant information, and it replies with the text / code most likely to complete the task. If it does not give you want you want, then you can send follow up messages to clarify and adjust its approach until the task is completed. +Chat makes it easy to ask for help from an LLM without needing to leave the IDE. You send it a task, including any relevant information, and it replies with the text / code most likely to complete the task. If it does not give you what you want, then you can send follow up messages to clarify and adjust its approach until the task is completed. Chat is best used to understand and iterate on code or as a replacement for search engine queries. @@ -28,7 +28,7 @@ If there is information from the codebase, documentation, IDE, or other tools th ## Apply generated code to your file -When the LLM replies with code, you can hover over the top right of the code block and select “Apply to current file” to update the existing code in the editor to this new version. +When the LLM replies with edits to a file, you can click the “Apply” button. This will update the existing code in the editor to reflect the suggested changes. ## Start a fresh session for a new task @@ -36,4 +36,4 @@ Once you complete a task and want to start a new one, press `cmd/ctrl + L` (VS C ## Switch between different models -If you have configured multiple models, you can switch between models using the dropdown or by pressing `cmd/ctrl + ’` \ No newline at end of file +If you have configured multiple models, you can switch between models using the dropdown or by pressing `cmd/ctrl + ’` diff --git a/docs/docs/customize/context-providers.md b/docs/docs/customize/context-providers.md index 23979bf94..2b3224543 100644 --- a/docs/docs/customize/context-providers.md +++ b/docs/docs/customize/context-providers.md @@ -6,164 +6,259 @@ keywords: [context, "@", provider, LLM] Context Providers allow you to type '@' and see a dropdown of content that can all be fed to the LLM as context. Every context provider is a plugin, which means if you want to reference some source of information that you don't see here, you can request (or build!) a new context provider. -As an example, say you are working on solving a new GitHub Issue. You type '@issue' and select the one you are working on. Continue can now see the issue title and contents. You also know that the issue is related to the files 'readme.md' and 'helloNested.py', so you type '@readme' and '@hello' to find and select them. Now these 3 "Context Items" are displayed inline with the rest of your input. +As an example, say you are working on solving a new GitHub Issue. You type '@Isse' and select the one you are working on. Continue can now see the issue title and contents. You also know that the issue is related to the files 'readme.md' and 'helloNested.py', so you type '@readme' and '@hello' to find and select them. Now these 3 "Context Items" are displayed inline with the rest of your input. ![Context Items](/img/context-provider-example.png) ## Built-in Context Providers -To use any of the built-in context providers, open `~/.continue/config.json` and add it to the `contextProviders` list. +To use any of the built-in context providers, open `config.json` and add it to the `contextProviders` list. -### Files +### `@File` -Type '@file' to reference any file in your current workspace. +Reference any file in your current workspace. -```json -{ "name": "file" } -``` - -### Code - -Type '@code' to reference specific functions or classes from throughout your project. - -```json -{ "name": "code" } -``` - -### Git Diff - -Type '@diff' to reference all of the changes you've made to your current branch. This is useful if you want to summarize what you've done or ask for a general review of your work before committing. - -```json -{ "name": "diff" } -``` - -### Terminal - -Type '@terminal' to reference the contents of your IDE's terminal. - -```json -{ "name": "terminal" } -``` - -### Documentation - -Type `@docs` to index and retrieve snippets from any documentation site. - -```json -{ "name": "docs" } -``` - -To learn more, visit `[@docs](customize/deep-dives/docs.md)`. - -### Open Files - -Type '@open' to reference the contents of all of your open files. Set `onlyPinned` to `true` to only reference pinned files. - -```json -{ "name": "open", "params": { "onlyPinned": true } } -``` - -### Codebase Retrieval - -Type '@codebase' to automatically retrieve the most relevant snippets from your codebase. Read more about indexing and retrieval [here](customize/deep-dives/codebase.md). - -```json -{ "name": "codebase" } -``` - -### Folders - -Type '@folder' to use the same retrieval mechanism as '@codebase', but only on a single folder. - -```json -{ "name": "folder" } -``` - -### Exact Search - -Type '@search' to reference the results of codebase search, just like the results you would get from VS Code search. This context provider is powered by [ripgrep](https://github.com/BurntSushi/ripgrep). - -```json -{ "name": "search" } -``` - -### URL - -Type '@url' and input a URL, then Continue will convert it to a markdown document to pass to the model. - -```json -{ "name": "url" } -``` - -### File Tree - -Type '@tree' to reference the structure of your current workspace. The LLM will be able to see the nested directory structure of your project. - -```json -{ "name": "tree" } -``` - -### Google - -Type '@google' to reference the results of a Google search. For example, type "@google python tutorial" if you want to search and discuss ways of learning Python. - -```json +```json title="config.json" { - "name": "google", - "params": { "serperApiKey": "" } + "contextProviders": [ + { + "name": "file" + } + ] } ``` +### `@Code` + +Reference specific functions or classes from throughout your project. + +```json title="config.json" +{ + "contextProviders": [ + { + "name": "code" + } + ] +} +``` + +### `@Git Diff` + +Reference all of the changes you've made to your current branch. This is useful if you want to summarize what you've done or ask for a general review of your work before committing. + +```json title="config.json" +{ + "contextProviders": [ + { + "name": "diff" + } + ] +} +``` + +### `@Terminal` + +Reference the contents of your IDE's terminal. + +```json title="config.json" +{ + "contextProviders": [ + { + "name": "terminal" + } + ] +} +``` + +### `@Docs` + +Reference the contents from any documentation site. + +```json title="config.json" +{ + "contextProviders": [ + { + "name": "docs" + } + ] +} +``` + +Note that this will only enable the `@Docs` context provider. + +To use it, you need to add a documentation site to your `config.json`. See the [docs](../customize/deep-dives/docs.md) page for more information. + +### `@Open` + +Reference the contents of all of your open files. Set `onlyPinned` to `true` to only reference pinned files. + +```json title="config.json" +{ + "contextProviders": [ + { + "name": "open", + "params": { + "onlyPinned": true + } + } + ] +} +``` + +### `@Codebase` + +Reference the most relevant snippets from your codebase. + +```json title="config.json" +{ + "contextProviders": [ + { + "name": "codebase" + } + ] +} +``` + +Read more about indexing and retrieval [here](../customize/deep-dives/codebase.md). + +### `@Folder` + +Uses the same retrieval mechanism as `@Codebase`, but only on a single folder. + +```json title="config.json" +{ + "contextProviders": [ + { + "name": "folder" + } + ] +} +``` + +### `@Search` + +Reference the results of codebase search, just like the results you would get from VS Code search. + +```json title="config.json" +{ + "contextProviders": [ + { + "name": "search" + } + ] +} +``` + +This context provider is powered by [ripgrep](https://github.com/BurntSushi/ripgrep). + +### `@Url` + +Reference the markdown converted contents of a given URL. + +```json title="config.json" +{ + "contextProviders": [ + { + "name": "url" + } + ] +} +``` + +### `@Tree` + +Reference the structure of your current workspace. + +```json title="config.json" +{ + "contextProviders": [ + { + "name": "tree" + } + ] +} +``` + +### `@Google` + +Reference the results of a Google search. + +```json title="config.json" +{ + "contextProviders": [ + { + "name": "google", + "params": { + "serperApiKey": "" + } + } + ] +} +``` + +For example, type "@Google python tutorial" if you want to search and discuss ways of learning Python. + Note: You can get an API key for free at [serper.dev](https://serper.dev). -### GitHub Issues +### `@Isse` -Type '@issue' to reference the conversation in a GitHub issue. Make sure to include your own [GitHub personal access token](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens#creating-a-fine-grained-personal-access-token) to avoid being rate-limited: +Reference the conversation in a GitHub issue. -```json +```json title="config.json" { - "name": "issue", - "params": { - "repos": [ - { - "owner": "continuedev", - "repo": "continue" + "contextProviders": [ + { + "name": "issue", + "params": { + "repos": [ + { + "owner": "continuedev", + "repo": "continue" + } + ], + "githubToken": "ghp_xxx" } - ], - "githubToken": "ghp_xxx" - } + } + ] } ``` -### GitLab Merge Request +Make sure to include your own [GitHub personal access token](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens#creating-a-fine-grained-personal-access-token) to avoid being rate-limited. -Type `@gitlab-mr` to reference an open MR for this branch on GitLab. +### `@Gitlab Merge Request` -#### Configuration +Reference an open MR for this branch on GitLab. -You will need to create a [personal access token](https://docs.gitlab.com/ee/user/profile/personal_access_tokens.html) with the `read_api` scope. then add the following to your configuration: - -```json +```json title="config.json" { - "name": "gitlab-mr", - "params": { - "token": "..." - } + "contextProviders": [ + { + "name": "gitlab-mr", + "params": { + "token": "..." + } + } + ] } ``` +You will need to create a [personal access token](https://docs.gitlab.com/ee/user/profile/personal_access_tokens.html) with the `read_api` scope. + #### Using Self-Hosted GitLab You can specify the domain to communicate with by setting the `domain` parameter in your configurtion. By default this is set to `gitlab.com`. -```json +```json title="config.json" { - "name": "gitlab-mr", - "params": { - "token": "...", - "domain": "gitlab.example.com" - } + "contextProviders": [ + { + "name": "gitlab-mr", + "params": { + "token": "...", + "domain": "gitlab.example.com" + } + } + ] } ``` @@ -171,31 +266,43 @@ You can specify the domain to communicate with by setting the `domain` parameter If you select some code to be edited, you can have the context provider filter out comments for other files. To enable this feature, set `filterComments` to `true`. -### Jira Issues +### `@Jira` -Type '@jira' to reference the conversation in a Jira issue. Make sure to include your own [Atlassian API Token](https://id.atlassian.com/manage-profile/security/api-tokens), or use your `email` and `token`, with token set to your password for basic authentication. If you use your own Atlassian API Token, don't configure your email. +Reference the conversation in a Jira issue. -```json +```json title="config.json" { - "name": "jira", - "params": { - "domain": "company.atlassian.net", - "token ": "ATATT..." - } + "contextProviders": [ + { + "name": "jira", + "params": { + "domain": "company.atlassian.net", + "token ": "ATATT..." + } + } + ] } ``` +Make sure to include your own [Atlassian API Token](https://id.atlassian.com/manage-profile/security/api-tokens), or use your `email` and `token`, with token set to your password for basic authentication. If you use your own Atlassian API Token, don't configure your email. + #### Jira Datacenter Support This context provider supports both Jira API version 2 and 3. It will use version 3 by default since that's what the cloud version uses, but if you have the datacenter version of Jira, you'll need to set the API Version to 2 using the `apiVersion` property. -```json - "params": { - "apiVersion": "2", - ... - } +```json title="config.json" +{ + "contextProviders": [ + { + "name": "jira", + "params": { + "apiVersion": "2" + } + } + ] +} ``` #### Issue Query @@ -208,117 +315,175 @@ assignee = currentUser() AND resolution = Unresolved order by updated DESC You can override this query by setting the `issueQuery` parameter. - +### `@Postgres` - - -### PostgreSQL - -Type `@postgres` to reference the schema of a table, and some sample rows. A dropdown will appear, allowing you to select a specific table, or all tables. - The only required settings are those for creating the database connection: `host`, `port`, `user`, `password`, and `database`. By default, the `schema` filter is set to `public`, and the `sampleRows` is set to 3. You may unset the schema if you want to include tables from all schemas. [Here is a short demo.](https://github.com/continuedev/continue/pull/859) -```json +### `@Database` + +Reference table schemas from Sqlite, Postgres, and MySQL databases. + +```json title="config.json" { - "name": "postgres", - "params": { - "host": "localhost", - "port": 5436, - "user": "myuser", - "password": "catsarecool", - "database": "animals", - "schema": "public", - "sampleRows": 3 - } -} -``` - -### Database Tables - -Type `@database` to reference table schemas you can use the drop-down or start typeing table names based off of your configuration. Configuration supports multiple databases, allowing you to specify various connection details for PostgreSQL, MySQL, SQLite. Each connection should include a unique name, the connection_type (e.g., postgres, sqlite), and the necessary connection parameters specific to each database type. - -```json -{ - "name": "database", - "params": { - "connections": [ - { - "name": "examplePostgres", - "connection_type": "postgres", - "connection": { - "user": "username", - "host": "localhost", - "database": "exampleDB", - "password": "yourPassword", - "port": 5432 - } - }, - { - "name": "exampleSqlite", - "connection_type": "sqlite", - "connection": { - "filename": "/path/to/your/sqlite/database.db" - } + "contextProviders": [ + { + "name": "database", + "params": { + "connections": [ + { + "name": "examplePostgres", + "connection_type": "postgres", + "connection": { + "user": "username", + "host": "localhost", + "database": "exampleDB", + "password": "yourPassword", + "port": 5432 + } + }, + { + "name": "exampleSqlite", + "connection_type": "sqlite", + "connection": { + "filename": "/path/to/your/sqlite/database.db" + } + } + ] } - ] - } + } + ] } ``` -### Debugger: Local Variables +Each connection should include a unique name, the `connection_type`, and the necessary connection parameters specific to each database type. -Type `@locals` to reference the contents of the local variables with top n level (defaulting to 3) of call stack for that thread. A dropdown will appear, allowing you to select a specific thread to see the local variables in that thread. +Available connection types: -```json +- `postgres` +- `mysql` +- `sqlite` + +### `@Locals` + +Reference the contents of the local variables in the debugger. + +```json title="config.json" { - "name": "locals", - "params": { - "stackDepth": 3 - } + "contextProviders": [ + { + "name": "locals", + "params": { + "stackDepth": 3 + } + } + ] } ``` -### Repository map +Uses the top _n_ levels (defaulting to 3) of the call stack for that thread. -Provides an overview of all files and the call signatures of top-level classes, functions, and methods. This helps the model better understand how a particular piece of code relates to the rest of the codebase. +### `@Repository Map` + +Reference the outline of your codebase. + +```json title="config.json" +{ + "contextProviders": [ + { + "name": "repo-map" + } + ] +} +``` + +Provides a list of files and the call signatures of top-level classes, functions, and methods in those files. This helps the model better understand how a particular piece of code relates to the rest of the codebase. + +In the submenu that appears, you can select either `Entire codebase`, or specify a subfolder to generate the repostiory map from. This context provider is inpsired by [Aider's repository map](https://aider.chat/2023/10/22/repomap.html). -```json +### `@Operating System` + +Reference the architecture and platform of your current operating system. + +```json title="config.json" { - "name": "repo-map" + "contextProviders": [ + { + "name": "os" + } + ] } ``` -### Operating System +### `@HTTP` -Type `@os` to reference the architecture and platform of your current operating system. +The HttpContextProvider makes a POST request to the url passed in the configuration. The server must return 200 OK with a ContextItem object or an array of ContextItems. -```json -{ "name": "os" } +```json title="config.json" +{ + "contextProviders": [ + { + "name": "http", + "params": { + "url": "https://api.example.com/v1/users", + } + } + ] +} +``` + +The receiving URL should expect to receive the following parameters: +```json title="POST parameters" +{ + query: string, + fullInput: string +} +``` + +The response 200 OK should be a JSON object with the following structure: +```json title="Response" +[ + { + "name": "", + "description": "", + "content": "" + } +] + +// OR +{ + "name": "", + "description": "", + "content": "" +} ``` ### Requesting Context Providers -Not seeing what you want? Create an issue [here](https://github.com/continuedev/continue/issues/new?assignees=TyDunn&labels=enhancement&projects=&template=feature-request-%F0%9F%92%AA.md&title=) to request a new ContextProvider. +Not seeing what you want? Create an issue [here](https://github.com/continuedev/continue/issues/new?assignees=TyDunn&labels=enhancement&projects=&template=feature-request-%F0%9F%92%AA.md&title=) to request a new Context Provider. diff --git a/docs/docs/customize/deep-dives/autocomplete.md b/docs/docs/customize/deep-dives/autocomplete.md index 3fd00ef02..49c2de949 100644 --- a/docs/docs/customize/deep-dives/autocomplete.md +++ b/docs/docs/customize/deep-dives/autocomplete.md @@ -32,7 +32,7 @@ Once it has been downloaded, you should begin to see completions in VS Code. All of the configuration options available for chat models are available to use for tab-autocomplete. For example, if you wanted to use a remote Ollama instance you would edit your `config.json` like this (note that it is not inside the models array): -```json title=~/.continue/config.json +```json title="config.json" { "tabAutocompleteModel": { "title": "Tab Autocomplete Model", @@ -73,7 +73,7 @@ This object allows you to customize the behavior of tab-autocomplete. The availa ### Full example -```json title=~/.continue/config.json +```json title="config.json" { "tabAutocompleteModel": { "title": "Tab Autocomplete Model", @@ -119,7 +119,7 @@ To ensure that you receive multi-line completions, you can set `"multilineComple Yes, in VS Code, if you don't want to be shown suggestions automatically you can: -1. Set `"editor.inlineSuggest.enabled": false` in VS Code settings to disabe automatic suggestions +1. Set `"editor.inlineSuggest.enabled": false` in VS Code settings to disable automatic suggestions 2. Open "Keyboard Shortcuts" (cmd/ctrl+k, cmd/ctrl+s) and search for `editor.action.inlineSuggest.trigger` 3. Click the "+" icon to add a new keybinding 4. Press the key combination you want to use to trigger suggestions (e.g. `ctrl+space`) diff --git a/docs/docs/customize/deep-dives/codebase.md b/docs/docs/customize/deep-dives/codebase.md index 8d5fef254..0d70f9b53 100644 --- a/docs/docs/customize/deep-dives/codebase.md +++ b/docs/docs/customize/deep-dives/codebase.md @@ -3,11 +3,11 @@ description: Talk to your codebase keywords: [talk, embeddings, reranker, codebase, experimental] --- -# @codebase +# @Codebase Continue indexes your codebase so that it can later automatically pull in the most relevant context from throughout your workspace. This is done via a combination of embeddings-based retrieval and keyword search. By default, all embeddings are calculated locally with `all-MiniLM-L6-v2` and stored locally in `~/.continue/index`. -Currently, the codebase retrieval feature is available as the "codebase" and "folder" context providers. You can use them by typing `@codebase` or `@folder` in the input box, and then asking a question. The contents of the input box will be compared with the embeddings from the rest of the codebase (or folder) to determine relevant files. +Currently, the codebase retrieval feature is available as the "codebase" and "folder" context providers. You can use them by typing `@Codebase` or `@Folder` in the input box, and then asking a question. The contents of the input box will be compared with the embeddings from the rest of the codebase (or folder) to determine relevant files. Here are some common use cases where it can be useful: @@ -19,10 +19,10 @@ Here are some common use cases where it can be useful: - "Generate a new React component with a date picker, using the same patterns as existing components" - "Write a draft of a CLI application for this project using Python's argparse" - "Implement the `foo` method in the `bar` class, following the patterns seen in other subclasses of `baz`. -- Use `@folder` to ask questions about a specific folder, increasing the likelihood of relevant results +- Use `@Folder` to ask questions about a specific folder, increasing the likelihood of relevant results - "What is the main purpose of this folder?" - "How do we use VS Code's CodeLens API?" - - Or any of the above examples, but with `@folder` instead of `@codebase` + - Or any of the above examples, but with `@Folder` instead of `@Codebase` Here are use cases where it is not useful: @@ -70,3 +70,7 @@ Continue respects `.gitignore` files in order to determine which files should no If you want to see exactly what files Continue has indexed, the metadata is stored in `~/.continue/index/index.sqlite`. You can use a tool like [DB Browser for SQLite](https://sqlitebrowser.org/) to view the `tag_catalog` table within this file. If you need to force a refresh of the index, reload the VS Code window with `cmd/ctrl + shift + p` + "Reload Window". + +## Repository map + +Models in the Claude 3, Llama 3.1, Gemini 1.5, and GPT-4o families will automatically use a [repository map](../context-providers.md#repository-map) during codebsae retrieval, which allows the model to understand the structure of your codebase and use it to answer questions. Currently, the repository map only contains the filepaths in the codebase. diff --git a/docs/docs/customize/deep-dives/docs.md b/docs/docs/customize/deep-dives/docs.md index 7ae6b329b..bc8968528 100644 --- a/docs/docs/customize/deep-dives/docs.md +++ b/docs/docs/customize/deep-dives/docs.md @@ -4,31 +4,32 @@ keywords: [documentation, indexing, context provider, embeddings, docs] toc_max_heading_level: 5 --- -# @docs +# @Docs -The [`@docs` context provider](http://localhost:3000/customization/context-providers#documentation) allows you to interact with your documentation directly within Continue. This feature enables you to index any static site or GitHub markdown pages, making it easier to access and utilize your documentation while coding. +The [`@Docs` context provider](http://localhost:3000/customization/context-providers#documentation) allows you to interact with your documentation directly within Continue. This feature enables you to index any static site or GitHub markdown pages, making it easier to access and utilize your documentation while coding. -## Enabling the `@docs` context provider +## Enabling the `@Docs` context provider -To enable the `@docs` context provider, you need to add it to the list of context providers in your `config.json` file. +To enable the `@Docs` context provider, you need to add it to the list of context providers in your `config.json` file. ```json { - "contextProviders": [ - { "name": "docs" } - ... - ] + "contextProviders": [ + { + "name": "docs" + } + ] } ``` ## How It Works -The `@docs` context provider works by crawling specified documentation sites, generating embeddings, and storing them locally for you. This process allows for quick and efficient access to your documentation content. +The `@Docs` context provider works by crawling specified documentation sites, generating embeddings, and storing them locally for you. This process allows for quick and efficient access to your documentation content. 1. We crawl the specified documentation site 2. Generate embeddings for the content 3. Store the embeddings locally on your machine -4. Provide access to the indexed content through the `@docs` context provider +4. Provide access to the indexed content through the `@Docs` context provider ## Pre-indexed Documentation Sites @@ -36,11 +37,11 @@ We offer a selection of pre-indexed documentation sites for popular frameworks a ## Indexing Your Own Documentation -### Through the `@docs` Context Provider +### Through the `@Docs` Context Provider -To add a single documentation site, we recommend using the `@docs` context provider. +To add a single documentation site, we recommend using the `@Docs` context provider. -1. Type `@docs` in the chat panel, hit enter +1. Type `@Docs` in the chat panel, hit enter 2. Type "add" and select the "Add Docs" option 3. Enter the required information into the dialog @@ -50,7 +51,7 @@ Indexing will begin upon submission. To add multiple documentation sites, we recommend adding them in bulk to your `config.json` file. Indexing will kick off upon file save. -The configuration schema is as follows: +The [configuration schema for docs](https://github.com/continuedev/continue/blob/v0.9.212-vscode/extensions/vscode/config_schema.json#L1943-L1973) is as follows: ```json "docs": [ @@ -74,7 +75,7 @@ By default, we use a lighter weight tool to crawl documentation sites that canno If you want to crawl a site that is dynamically generated, or you get an error while attempting to crawl a site, you can enable the experimental `useChromiumForDocsCrawling` feature in your `config.json`. This will download and install Chromium to `~/.continue/.utils`. -```json title=config.json +```json title="config.json" "experimental": { "useChromiumForDocsCrawling": true } diff --git a/docs/docs/customize/model-providers/top-level/anthropic.md b/docs/docs/customize/model-providers/top-level/anthropic.md index ebc156413..c4bb24a4c 100644 --- a/docs/docs/customize/model-providers/top-level/anthropic.md +++ b/docs/docs/customize/model-providers/top-level/anthropic.md @@ -48,14 +48,17 @@ Anthropic currently does not offer any reranking models. Anthropic supports [prompt caching with Claude](https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching). -Currently, we only allow caching of the system message. To enable this feature, update your your model configuration with `"cacheSystemMessage": true`: +To enable caching of the system message and the turn-by-turn conversation, update your your model configuration as following: ```json { "models": [ { // Enable prompt caching - "cacheSystemMessage": true, + "cacheBehavior": { + "cacheSystemMessage": true, + "cacheConversation": true + }, "title": "Anthropic", "provider": "anthropic", "model": "claude-3-5-sonnet-20240620", diff --git a/docs/docs/customize/model-types/autocomplete.md b/docs/docs/customize/model-types/autocomplete.md index 8e98c9186..8ecac28e6 100644 --- a/docs/docs/customize/model-types/autocomplete.md +++ b/docs/docs/customize/model-types/autocomplete.md @@ -7,10 +7,10 @@ sidebar_position: 1 An "autocomplete model" is an LLM that is trained on a special format called fill-in-the-middle (FIM). This format is designed to be given the prefix and suffix of a code file and predict what goes between. This task is very specific, which on one hand means that the models can be smaller (even a 3B parameter model can perform well). On the other hand, this means that Chat models, though larger, will perform poorly. -In Continue, these models are used to display inline [Autocomplete](../../chat/how-to-use-it.md) suggestions as you type. +In Continue, these models are used to display inline [Autocomplete](../../autocomplete/how-to-use-it.md) suggestions as you type. ## Recommended Autocomplete models -If you have the ability to use any model, we recommend [Codestral](../model-providers/top-level/mistral.md) from Mistral. +If you have the ability to use any model, we recommend `Codestral` with [Mistral](../model-providers/top-level/mistral.md#autocomplete-model). -If you want to run a model locally, we recommend [Starcoder2-3B] with [Ollama]../model-providers/top-level/ollama.md). +If you want to run a model locally, we recommend `Starcoder2-3B` with [Ollama](../model-providers/top-level/ollama.md#autocomplete-model). diff --git a/docs/docs/customize/model-types/embeddings.md b/docs/docs/customize/model-types/embeddings.md index 2960dcbfd..c32468967 100644 --- a/docs/docs/customize/model-types/embeddings.md +++ b/docs/docs/customize/model-types/embeddings.md @@ -7,7 +7,7 @@ sidebar_position: 3 An "embeddings model" is trained to convert a piece of text into a vector, which can later be rapidly compared to other vectors to determine similarity between the pieces of text. Embeddings models are typically much smaller than LLMs, and will be extremely fast and cheap in comparison. -In Continue, embeddings are generated during indexing and then used by [@codebase](../deep-dives/codebase.md) to perform similarity search over your codebase. +In Continue, embeddings are generated during indexing and then used by [@Codebase](../deep-dives/codebase.md) to perform similarity search over your codebase. ## Recommended embedding models diff --git a/docs/docs/customize/model-types/reranking.md b/docs/docs/customize/model-types/reranking.md index af6c99932..5f3fd77a3 100644 --- a/docs/docs/customize/model-types/reranking.md +++ b/docs/docs/customize/model-types/reranking.md @@ -7,7 +7,7 @@ sidebar_position: 4 A "reranking model" is trained to take two pieces of text (often a user question and a document) and return a relevancy score between 0 and 1, estimating how useful the document will be in answering the question. Rerankers are typically much smaller than LLMs, and will be extremely fast and cheap in comparison. -In Continue, reranking is used by [@codebase](../deep-dives/codebase.md) in order to select the most relevant code snippets after vector search. +In Continue, reranking is used by [@Codebase](../deep-dives/codebase.md) in order to select the most relevant code snippets after vector search. ## Recommended reranking models diff --git a/docs/docs/customize/slash-commands.md b/docs/docs/customize/slash-commands.md index 6379b6db5..702d00c7c 100644 --- a/docs/docs/customize/slash-commands.md +++ b/docs/docs/customize/slash-commands.md @@ -10,108 +10,144 @@ Slash commands are shortcuts that can be activated by typing '/' and selecting f ## Built-in Slash Commands -To use any of the built-in slash commands, open `~/.continue/config.json` and add it to the `slashCommands` list. +To use any of the built-in slash commands, open `config.json` and add it to the `slashCommands` list. -### `/edit` +### `/Edit` -Select code with ctrl/cmd + L (VS Code) or ctrl/cmd + J (JetBrains), and then type "/edit", followed by instructions for the edit. Continue will stream the changes into a side-by-side diff editor. +Select code with `ctrl/cmd + L` (VS Code) or `ctrl/cmd + J` (JetBrains), and then type `/Edit`, followed by instructions for the edit. Continue will stream the changes into a side-by-side diff editor. -```json +```json title="config.json" { - "name": "edit", - "description": "Edit highlighted code" + "slashCommands": [ + { + "name": "edit", + "description": "Edit highlighted code" + } + ] } ``` -### `/comment` +### `/Comment` -Comment works just like /edit, except it will automatically prompt the LLM to comment the code. +Comment works just like `/Edit`, except it will automatically prompt the LLM to comment the code. -```json +```json title="config.json" { - "name": "comment", - "description": "Write comments for the highlighted code" + "slashCommands": [ + { + "name": "comment", + "description": "Write comments for the highlighted code" + } + ] } ``` -### `/share` +### `/Share` -Type "/share" to generate a shareable markdown transcript of your current chat history. +Generate a shareable markdown transcript of your current chat history. -```json +```json title="config.json" { - "name": "share", - "description": "Export the current chat session to markdown", - "params": { "outputDir": "~/.continue/session-transcripts" } + "slashCommands": [ + { + "name": "share", + "description": "Export the current chat session to markdown", + "params": { "outputDir": "~/.continue/session-transcripts" } + } + ] } ``` Use the `outputDir` parameter to specify where you want to the markdown file to be saved. -### `/cmd` +### `/Cmd` Generate a shell command from natural language and (only in VS Code) automatically paste it into the terminal. -```json +```json title="config.json" { - "name": "cmd", - "description": "Generate a shell command" + "slashCommands": [ + { + "name": "cmd", + "description": "Generate a shell command" + } + ] } ``` -### `/commit` +### `/Commit` Shows the LLM your current git diff and asks it to generate a commit message. -```json +```json title="config.json" { - "name": "commit", - "description": "Generate a commit message for the current changes" + "slashCommands": [ + { + "name": "commit", + "description": "Generate a commit message for the current changes" + } + ] } ``` -### `/http` +### `/Http` Write a custom slash command at your own HTTP endpoint. Set 'url' in the params object for the endpoint you have setup. The endpoint should return a sequence of string updates, which will be streamed to the Continue sidebar. See our basic [FastAPI example](https://github.com/continuedev/continue/blob/74002369a5e435735b83278fb965e004ae38a97d/core/context/providers/context_provider_server.py#L34-L45) for reference. -```json +```json title="config.json" { - "name": "http", - "description": "Does something custom", - "params": { "url": "" } + "slashCommands": [ + { + "name": "http", + "description": "Does something custom", + "params": { "url": "" } + } + ] } ``` -### `/issue` +### `/Issue` Describe the issue you'd like to generate, and Continue will turn into a well-formatted title and body, then give you a link to the draft so you can submit. Make sure to set the URL of the repository you want to generate issues for. -```json +```json title="config.json" { - "name": "issue", - "description": "Generate a link to a drafted GitHub issue", - "params": { "repositoryUrl": "https://github.com/continuedev/continue" } + "slashCommands": [ + { + "name": "issue", + "description": "Generate a link to a drafted GitHub issue", + "params": { "repositoryUrl": "https://github.com/continuedev/continue" } + } + ] } ``` -### `/so` +### `/So` The StackOverflow slash command will automatically pull results from StackOverflow to answer your question, quoting links along with its answer. -```json +```json title="config.json" { - "name": "so", - "description": "Reference StackOverflow to answer the question" + "slashCommands": [ + { + "name": "so", + "description": "Reference StackOverflow to answer the question" + } + ] } ``` -### `/onboard` +### `/Onboard` The Onboard slash command helps to familiarize yourself with a new project by analyzing the project structure, READMEs, and dependency files. It identifies key folders, explains their purpose, and highlights popular packages used. Additionally, it offers insights into the project's architecture. -```json +```json title="config.json" { - "name": "onboard", - "description": "Familiarize yourself with the codebase" + "slashCommands": [ + { + "name": "onboard", + "description": "Familiarize yourself with the codebase" + } + ] } ``` diff --git a/docs/docs/customize/tutorials/custom-code-rag.md b/docs/docs/customize/tutorials/custom-code-rag.md index 6793a8277..208180a58 100644 --- a/docs/docs/customize/tutorials/custom-code-rag.md +++ b/docs/docs/customize/tutorials/custom-code-rag.md @@ -1,6 +1,6 @@ # Custom code RAG -While Continue comes with [@codebase](../deep-dives/codebase.md) out of the box, you might wish to set up your own vector database and build a custom retrieval-augmented generation (RAG) system. This can allow you to access code that is not available locally, to index code a single time across all users, or to include custom logic. In this guide, we'll walk you through the steps it takes to build this. +While Continue comes with [@Codebase](../deep-dives/codebase.md) out of the box, you might wish to set up your own vector database and build a custom retrieval-augmented generation (RAG) system. This can allow you to access code that is not available locally, to index code a single time across all users, or to include custom logic. In this guide, we'll walk you through the steps it takes to build this. ## Step 1: Choose an embeddings model diff --git a/docs/docs/troubleshooting.md b/docs/docs/troubleshooting.md index 8852cf3f4..d3933f6f9 100644 --- a/docs/docs/troubleshooting.md +++ b/docs/docs/troubleshooting.md @@ -122,6 +122,10 @@ If you are having persistent errors with indexing, our recommendation is to rebu This can be accomplished using the following command: `Continue: Rebuild codebase index`. +### Android Studio - "Nothing to show" in Chat + +This can be fixed by selecting `Actions > Choose Boot runtime for the IDE` then selecting the latest version, and then restarting Android Studio. [See this thread](https://github.com/continuedev/continue/issues/2280#issuecomment-2365231567) for details. + ## Still having trouble? You can also join our Discord community [here](https://discord.gg/vapESyrFmJ) for additional support and discussions. Alternatively, you can create a GitHub issue [here](https://github.com/continuedev/continue/issues/new?assignees=&labels=bug&projects=&template=bug-report-%F0%9F%90%9B.md&title=), providing details of your problem, and we'll be able to help you out more quickly. diff --git a/docs/package.json b/docs/package.json index 644b1d7f4..423c60bde 100644 --- a/docs/package.json +++ b/docs/package.json @@ -5,7 +5,7 @@ "private": true, "scripts": { "docusaurus": "docusaurus", - "start": "nodemon --watch sidebars.js --watch docusaurus.config.js --exec 'docusaurus start'", + "start": "nodemon --watch sidebars.js --watch docusaurus.config.js --exec \"docusaurus start\"", "build": "docusaurus build", "build:netlify": "docusaurus build --out-dir build/docs", "swizzle": "docusaurus swizzle", diff --git a/docs/sidebars.js b/docs/sidebars.js index 196a6c832..755d7f720 100644 --- a/docs/sidebars.js +++ b/docs/sidebars.js @@ -8,10 +8,6 @@ const sidebars = { type: "category", label: "Getting started", collapsed: false, - link: { - type: "doc", - id: "getting-started/install", - }, items: [ { type: "autogenerated", @@ -22,10 +18,6 @@ const sidebars = { { type: "category", label: "Chat", - link: { - type: "doc", - id: "chat/how-to-use-it", - }, items: [ { type: "autogenerated", @@ -36,10 +28,6 @@ const sidebars = { { type: "category", label: "Autocomplete", - link: { - type: "doc", - id: "autocomplete/how-to-use-it", - }, items: [ { type: "autogenerated", @@ -50,10 +38,6 @@ const sidebars = { { type: "category", label: "Edit", - link: { - type: "doc", - id: "edit/how-to-use-it", - }, items: [ { type: "autogenerated", @@ -64,10 +48,6 @@ const sidebars = { { type: "category", label: "Actions", - link: { - type: "doc", - id: "actions/how-to-use-it", - }, items: [ { type: "autogenerated", diff --git a/docs/static/schemas/config.json b/docs/static/schemas/config.json index 911278ebb..3f340f6ce 100644 --- a/docs/static/schemas/config.json +++ b/docs/static/schemas/config.json @@ -609,9 +609,7 @@ "llama3.1-70b", "llama3.1-405b", "gpt-3.5-turbo", - "phind-codellama-34b", "gemini-pro", - "mistral-8x7b", "claude-3-5-sonnet-20240620", "claude-3-haiku-20240307", "AUTODETECT" @@ -701,8 +699,17 @@ }, "then": { "properties": { - "cacheSystemMessage": { - "type": "boolean" + "cacheBehavior": { + "title": "Caching Behavior", + "description": "Options for the prompt caching", + "properties": { + "cacheSystemMessage": { + "type": "boolean" + }, + "cacheConversation": { + "type": "boolean" + } + } }, "model": { "anyOf": [ @@ -798,8 +805,14 @@ }, "then": { "properties": { - "cacheSystemMessage": { - "type": "boolean" + "cacheBehavior": { + "title": "Caching Behavior", + "description": "Options for the prompt caching", + "properties": { + "cacheSystemMessage": { + "type": "boolean" + } + } }, "model": { "enum": [ @@ -1019,8 +1032,17 @@ }, "then": { "properties": { - "cacheSystemMessage": { - "type": "boolean" + "cacheBehavior": { + "title": "Caching Behavior", + "description": "Options for the prompt caching", + "properties": { + "cacheSystemMessage": { + "type": "boolean" + }, + "cacheConversation": { + "type": "boolean" + } + } }, "model": { "enum": ["deepseek-chat", "deepseek-coder"] @@ -1044,6 +1066,7 @@ "llama2-70b", "mistral-8x7b", "gemma", + "gemma2", "llama3-8b", "llama3-70b", "llama3.1-8b", @@ -1529,7 +1552,8 @@ "url", "database", "os", - "repo-map" + "repo-map", + "greptile" ], "markdownEnumDescriptions": [ "Reference the contents of the current changes as given by `git diff`", @@ -1553,7 +1577,8 @@ "Reference the contents of a page at a URL", "Reference table schemas", "Operating system and CPU Information", - "Map of files in the repository with important code highlights" + "Map of files in the repository with important code highlights", + "Query your greptile index of the current repo" ], "type": "string" }, @@ -1931,6 +1956,36 @@ }, "required": ["host", "port", "user", "password", "database"] } + }, + { + "if": { + "properties": { + "name": { + "enum": ["greptile"] + } + } + }, + "then": { + "properties": { + "params": { + "properties": { + "GithubToken": { + "title": "GithubToken", + "description": "Your github access token", + "default": "", + "type": "string" + }, + "GreptileToken": { + "title": "GreptileToken", + "description": "Your greptile access token", + "default": "", + "type": "string" + } + } + } + }, + "required": ["GreptileToken", "GithubToken"] + } } ], "required": ["name"] @@ -2114,6 +2169,13 @@ "minimum": 128, "exclusiveMaximum": 2147483647 }, + "maxBatchSize": { + "title": "Maximum Batch Size", + "description": "The maximum number of chunks that can be sent to the embeddings provider in a single request", + "type": "integer", + "minimum": 1, + "exclusiveMaximum": 2147483647 + }, "region": { "title": "Region", "description": "The region where the model is hosted", diff --git a/extensions/intellij/.run/Run Verifications.run.xml b/extensions/intellij/.run/Run Verifications.run.xml index 3a8d68859..35b018168 100644 --- a/extensions/intellij/.run/Run Verifications.run.xml +++ b/extensions/intellij/.run/Run Verifications.run.xml @@ -3,7 +3,7 @@