From 7ec29ba7e649f8682bbc82980687391f83b0fa2a Mon Sep 17 00:00:00 2001 From: zhangtao Date: Tue, 22 Oct 2024 21:38:39 +0800 Subject: [PATCH 01/96] fix code context description parsing to filename & range --- gui/src/components/mainInput/resolveInput.ts | 7 +++++-- gui/src/components/markdown/CodeBlockToolbar.tsx | 1 + gui/src/components/markdown/CodeSnippetPreview.tsx | 6 +++--- gui/src/components/markdown/PreWithToolbar.tsx | 1 + gui/src/components/markdown/StyledMarkdownPreview.tsx | 10 ++++++---- 5 files changed, 16 insertions(+), 9 deletions(-) diff --git a/gui/src/components/mainInput/resolveInput.ts b/gui/src/components/mainInput/resolveInput.ts index f57c03f4a..4b2d606d6 100644 --- a/gui/src/components/mainInput/resolveInput.ts +++ b/gui/src/components/mainInput/resolveInput.ts @@ -57,9 +57,12 @@ async function resolveEditorContent( } } else if (p.type === "codeBlock") { if (!p.attrs.item.editing) { + let meta = p.attrs.item.description.split(" "); + let relativePath = meta[0] || ""; + let extName = relativePath.split(".").slice(-1)[0]; const text = - "```" + - p.attrs.item.description + + "\n\n" + + "```" + extName + " " + p.attrs.item.description + "\n" + p.attrs.item.content + "\n```"; diff --git a/gui/src/components/markdown/CodeBlockToolbar.tsx b/gui/src/components/markdown/CodeBlockToolbar.tsx index aecaa1b84..2973fc535 100644 --- a/gui/src/components/markdown/CodeBlockToolbar.tsx +++ b/gui/src/components/markdown/CodeBlockToolbar.tsx @@ -86,6 +86,7 @@ interface CodeBlockToolBarProps { language: string | undefined; isNextCodeBlock: boolean; filepath?: string; + range?: string; } const terminalLanguages = ["bash", "sh"]; diff --git a/gui/src/components/markdown/CodeSnippetPreview.tsx b/gui/src/components/markdown/CodeSnippetPreview.tsx index 2a7b6d970..3c783c59a 100644 --- a/gui/src/components/markdown/CodeSnippetPreview.tsx +++ b/gui/src/components/markdown/CodeSnippetPreview.tsx @@ -95,7 +95,7 @@ function CodeSnippetPreview(props: CodeSnippetPreviewProps) { .split(")")[0] .split("-"); ideMessenger.ide.showLines( - props.item.description, + props.item.description.split(" ")[0], parseInt(lines[0]) - 1, parseInt(lines[1]) - 1, ); @@ -145,8 +145,8 @@ function CodeSnippetPreview(props: CodeSnippetPreviewProps) { > diff --git a/gui/src/components/markdown/PreWithToolbar.tsx b/gui/src/components/markdown/PreWithToolbar.tsx index ec9297d54..f626dfb90 100644 --- a/gui/src/components/markdown/PreWithToolbar.tsx +++ b/gui/src/components/markdown/PreWithToolbar.tsx @@ -36,6 +36,7 @@ function PreWithToolbar(props: { language: string | null; codeBlockIndex: number; filepath?: string | undefined; + range?: string; }) { const uiConfig = useUIConfig(); const toolbarBottom = uiConfig?.codeBlockToolbarPosition == "bottom"; diff --git a/gui/src/components/markdown/StyledMarkdownPreview.tsx b/gui/src/components/markdown/StyledMarkdownPreview.tsx index 1695b7d19..a744b371d 100644 --- a/gui/src/components/markdown/StyledMarkdownPreview.tsx +++ b/gui/src/components/markdown/StyledMarkdownPreview.tsx @@ -126,14 +126,15 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( visit(tree, "code", (node: any) => { if (!node.lang) { node.lang === "javascript"; - } else if (node.lang.includes(".")) { - node.lang = node.lang.split(".").slice(-1)[0]; } if (node.meta) { node.data = node.data || {}; node.data.hProperties = node.data.hProperties || {}; - node.data.hProperties.filepath = node.meta; + + let meta = node.meta.split(" "); + node.data.hProperties.filepath = meta[0]; + node.data.hProperties.range = meta[1]; } }); }; @@ -172,13 +173,14 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( ); }, pre: ({ node, ...preProps }) => { - const { className, filepath } = preProps?.children?.[0]?.props; + const { className, filepath, range } = preProps?.children?.[0]?.props; return props.showCodeBorder ? ( From f81ec058abad249ebae769f297468d7064ea0ee5 Mon Sep 17 00:00:00 2001 From: Wouter Tichelaar Date: Thu, 24 Oct 2024 09:52:09 +0200 Subject: [PATCH 02/96] Added support for MSSQL to the DatabaseContextProvider --- core/config/types.ts | 1 + docs/static/schemas/config.json | 62 +++++++++++++++++++- extensions/vscode/config_schema.json | 62 +++++++++++++++++++- extensions/vscode/continue_rc_schema.json | 71 ++++++++++++++++++++++- extensions/vscode/package.json | 2 +- 5 files changed, 194 insertions(+), 4 deletions(-) diff --git a/core/config/types.ts b/core/config/types.ts index 390bc5519..36b3bb4fb 100644 --- a/core/config/types.ts +++ b/core/config/types.ts @@ -542,6 +542,7 @@ declare global { | "folder" | "jira" | "postgres" + | "mssql" | "database" | "code" | "docs" diff --git a/docs/static/schemas/config.json b/docs/static/schemas/config.json index 6da984ead..68cd82bd9 100644 --- a/docs/static/schemas/config.json +++ b/docs/static/schemas/config.json @@ -1737,6 +1737,7 @@ "highlights", "outline", "postgres", + "mssql", "code", "currentFile", "url", @@ -1986,7 +1987,7 @@ "connection_type": { "type": "string", "description": "The type of database (e.g., 'postgres', 'mysql')", - "enum": ["postgres", "mysql", "sqlite"] + "enum": ["postgres", "mysql", "sqlite", "mssql"] }, "connection": { "type": "object", @@ -2179,6 +2180,65 @@ } } }, + { + "if": { + "properties": { + "name": { + "enum": ["mssql"] + } + } + }, + "then": { + "properties": { + "params": { + "properties": { + "server": { + "title": "Host", + "description": "Database host", + "default": "localhost", + "type": "string" + }, + "port": { + "title": "Port", + "description": "Database port", + "default": 5432, + "type": "integer" + }, + "user": { + "title": "User", + "description": "Database user", + "default": "postgres", + "type": "string" + }, + "password": { + "title": "Password", + "description": "Database password", + "type": "string" + }, + "database": { + "title": "Database", + "description": "Database name", + "default": "postgres", + "type": "string" + }, + "schema": { + "title": "Schema", + "description": "Database schema", + "default": "public", + "type": "string" + }, + "sampleRows": { + "title": "Sample Rows", + "description": "Number of rows to sample from the database", + "default": 3, + "type": "integer" + } + } + } + }, + "required": ["host", "port", "user", "password", "database"] + } + }, { "if": { "properties": { diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index 6da984ead..68cd82bd9 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -1737,6 +1737,7 @@ "highlights", "outline", "postgres", + "mssql", "code", "currentFile", "url", @@ -1986,7 +1987,7 @@ "connection_type": { "type": "string", "description": "The type of database (e.g., 'postgres', 'mysql')", - "enum": ["postgres", "mysql", "sqlite"] + "enum": ["postgres", "mysql", "sqlite", "mssql"] }, "connection": { "type": "object", @@ -2179,6 +2180,65 @@ } } }, + { + "if": { + "properties": { + "name": { + "enum": ["mssql"] + } + } + }, + "then": { + "properties": { + "params": { + "properties": { + "server": { + "title": "Host", + "description": "Database host", + "default": "localhost", + "type": "string" + }, + "port": { + "title": "Port", + "description": "Database port", + "default": 5432, + "type": "integer" + }, + "user": { + "title": "User", + "description": "Database user", + "default": "postgres", + "type": "string" + }, + "password": { + "title": "Password", + "description": "Database password", + "type": "string" + }, + "database": { + "title": "Database", + "description": "Database name", + "default": "postgres", + "type": "string" + }, + "schema": { + "title": "Schema", + "description": "Database schema", + "default": "public", + "type": "string" + }, + "sampleRows": { + "title": "Sample Rows", + "description": "Number of rows to sample from the database", + "default": 3, + "type": "integer" + } + } + } + }, + "required": ["host", "port", "user", "password", "database"] + } + }, { "if": { "properties": { diff --git a/extensions/vscode/continue_rc_schema.json b/extensions/vscode/continue_rc_schema.json index 86304fa6e..e7f291135 100644 --- a/extensions/vscode/continue_rc_schema.json +++ b/extensions/vscode/continue_rc_schema.json @@ -1939,6 +1939,7 @@ "highlights", "outline", "postgres", + "mssql", "code", "currentFile", "url", @@ -2234,7 +2235,8 @@ "enum": [ "postgres", "mysql", - "sqlite" + "sqlite", + "mssql" ] }, "connection": { @@ -2458,6 +2460,73 @@ } } }, + { + "if": { + "properties": { + "name": { + "enum": [ + "mssql" + ] + } + } + }, + "then": { + "properties": { + "params": { + "properties": { + "server": { + "title": "Host", + "description": "Database host", + "default": "localhost", + "type": "string" + }, + "port": { + "title": "Port", + "description": "Database port", + "default": 5432, + "type": "integer" + }, + "user": { + "title": "User", + "description": "Database user", + "default": "postgres", + "type": "string" + }, + "password": { + "title": "Password", + "description": "Database password", + "type": "string" + }, + "database": { + "title": "Database", + "description": "Database name", + "default": "postgres", + "type": "string" + }, + "schema": { + "title": "Schema", + "description": "Database schema", + "default": "public", + "type": "string" + }, + "sampleRows": { + "title": "Sample Rows", + "description": "Number of rows to sample from the database", + "default": 3, + "type": "integer" + } + } + } + }, + "required": [ + "host", + "port", + "user", + "password", + "database" + ] + } + }, { "if": { "properties": { diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 2d7a5af4f..54edefdef 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -563,7 +563,7 @@ "axios": "^1.2.5", "core": "file:../../core", "cors": "^2.8.5", - "dbinfoz": "^0.11.0", + "dbinfoz": "^0.14.0", "downshift": "^7.6.0", "esbuild": "^0.17.19", "express": "^4.18.2", From 3a8457e6fcc4a5dbe9cdbea94159f1d62143c06e Mon Sep 17 00:00:00 2001 From: Wouter Tichelaar Date: Thu, 24 Oct 2024 09:38:23 +0200 Subject: [PATCH 03/96] Update documentation --- docs/docs/customize/context-providers.md | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/docs/docs/customize/context-providers.md b/docs/docs/customize/context-providers.md index 41b569604..0e9b91dce 100644 --- a/docs/docs/customize/context-providers.md +++ b/docs/docs/customize/context-providers.md @@ -390,7 +390,7 @@ By default, the `schema` filter is set to `public`, and the `sampleRows` is set ### `@Database` -Reference table schemas from Sqlite, Postgres, and MySQL databases. +Reference table schemas from Sqlite, Postgres, MSSQL, and MySQL databases. ```json title="config.json" { @@ -409,6 +409,15 @@ Reference table schemas from Sqlite, Postgres, and MySQL databases. "password": "yourPassword", "port": 5432 } + }{ + "name": "exampleMssql", + "connection_type": "mssql", + "connection": { + "user": "username", + "server": "localhost", + "database": "exampleDB", + "password": "yourPassword" + } }, { "name": "exampleSqlite", From 2984499485d7f3edeea69b9f6c61ae46f98693c3 Mon Sep 17 00:00:00 2001 From: Wouter Tichelaar <9594229+DifferentialityDevelopment@users.noreply.github.com> Date: Thu, 24 Oct 2024 19:37:02 +0200 Subject: [PATCH 04/96] Update docs/static/schemas/config.json Co-authored-by: Patrick Erichsen --- docs/static/schemas/config.json | 1 - 1 file changed, 1 deletion(-) diff --git a/docs/static/schemas/config.json b/docs/static/schemas/config.json index 68cd82bd9..107cfbee5 100644 --- a/docs/static/schemas/config.json +++ b/docs/static/schemas/config.json @@ -1737,7 +1737,6 @@ "highlights", "outline", "postgres", - "mssql", "code", "currentFile", "url", From 963fe50f2d2809859f015fea35845864d806e55a Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 28 Oct 2024 12:34:33 -0700 Subject: [PATCH 05/96] handle delete in vscode and filechanges in kotlin p1 --- core/core.ts | 8 ++++---- core/protocol/core.ts | 2 +- .../listeners/VirtualFileListener.kt | 0 .../vscode/src/extension/VsCodeExtension.ts | 16 +++++++++++----- 4 files changed, 16 insertions(+), 10 deletions(-) create mode 100644 extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/listeners/VirtualFileListener.kt diff --git a/core/core.ts b/core/core.ts index 415540a74..83bf1fe62 100644 --- a/core/core.ts +++ b/core/core.ts @@ -77,7 +77,7 @@ export class Core { constructor( private readonly messenger: IMessenger, private readonly ide: IDE, - private readonly onWrite: (text: string) => Promise = async () => {}, + private readonly onWrite: (text: string) => Promise = async () => { }, ) { this.indexingState = { status: "loading", desc: "loading", progress: 0 }; @@ -165,7 +165,7 @@ export class Core { this.configHandler, ide, getLlm, - (e) => {}, + (e) => { }, (..._) => Promise.resolve([]), ); @@ -483,7 +483,7 @@ export class Core { on("tts/kill", async () => { void TTS.kill(); }); - + on("chatDescriber/describe", async (msg) => { const currentModel = await this.getSelectedModel(); return await ChatDescriber.describe(currentModel, {}, msg.data); @@ -674,7 +674,7 @@ export class Core { await codebaseIndexer.clearIndexes(); } - const dirs = data?.dir ? [data.dir] : await this.ide.getWorkspaceDirs(); + const dirs = data?.dirs ?? await this.ide.getWorkspaceDirs(); await this.refreshCodebaseIndex(dirs); }); on("index/setPaused", (msg) => { diff --git a/core/protocol/core.ts b/core/protocol/core.ts index e2d512950..196a14e24 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -143,7 +143,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { "tts/kill": [undefined, void]; "index/setPaused": [boolean, void]; "index/forceReIndex": [ - undefined | { dir?: string; shouldClearIndexes?: boolean }, + undefined | { dirs?: string[]; shouldClearIndexes?: boolean }, void, ]; "index/indexingProgressBarInitialized": [undefined, void]; diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/listeners/VirtualFileListener.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/listeners/VirtualFileListener.kt new file mode 100644 index 000000000..e69de29bb diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index 78541f8ea..8d89156cc 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -272,11 +272,18 @@ export class VsCodeExtension { this.core.invoke("index/forceReIndex", undefined); } else { // Reindex the file - const indexer = await this.core.codebaseIndexerPromise; - indexer.refreshFile(filepath); + this.core.invoke("index/forceReIndex", { + dirs: [filepath] + }) } }); + vscode.workspace.onDidDeleteFiles(async (event) => { + this.core.invoke("index/forceReIndex", { + dirs: event.files.map((file) => file.fsPath) + }) + }) + // When GitHub sign-in status changes, reload config vscode.authentication.onDidChangeSessions(async (e) => { if (e.provider.id === "github") { @@ -309,7 +316,7 @@ export class VsCodeExtension { currentBranch !== this.PREVIOUS_BRANCH_FOR_WORKSPACE_DIR[dir] ) { // Trigger refresh of index only in this directory - this.core.invoke("index/forceReIndex", { dir }); + this.core.invoke("index/forceReIndex", { dirs: [dir] }); } } @@ -322,8 +329,7 @@ export class VsCodeExtension { // Register a content provider for the readonly virtual documents const documentContentProvider = new (class - implements vscode.TextDocumentContentProvider - { + implements vscode.TextDocumentContentProvider { // emitter and its event onDidChangeEmitter = new vscode.EventEmitter(); onDidChange = this.onDidChangeEmitter.event; From 3444d9276a0b675124cee20723ac83bec0d63e7e Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 28 Oct 2024 12:42:17 -0700 Subject: [PATCH 06/96] handle file changes on jetbrains --- .../activities/ContinuePluginStartupActivity.kt | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt index 422fe7460..4b740ce4d 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt @@ -147,6 +147,19 @@ class ContinuePluginStartupActivity : StartupActivity, Disposable, DumbAware { } }) + // Handle file changes and deletions - reindex + connection.subscribe(VirtualFileManager.VFS_CHANGES, object : VirtualFileListener { + override fun fileDeleted(event: VirtualFileEvent) { + val data = mapOf("dirs" to listOf(event.filePath)) + continuePluginService.coreMessenger?.request("index/forceReIndex", data, null) { _ -> } + } + + override fun contentsChanged(event: VirtualFileEvent) { + val data = mapOf("dirs" to listOf(event.filePath)) + continuePluginService.coreMessenger?.request("index/forceReIndex", data, null) { _ -> } + } + }) + // Listen for clicking settings button to start the auth flow val authService = service() val initialSessionInfo = authService.loadControlPlaneSessionInfo() From 7da12ce145ad69fdac3e6a3d942b6aeca1526a5c Mon Sep 17 00:00:00 2001 From: Wouter Tichelaar <9594229+DifferentialityDevelopment@users.noreply.github.com> Date: Wed, 30 Oct 2024 07:51:49 +0200 Subject: [PATCH 07/96] Update context-providers.md --- docs/docs/customize/context-providers.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/docs/customize/context-providers.md b/docs/docs/customize/context-providers.md index 0e9b91dce..e582beb1b 100644 --- a/docs/docs/customize/context-providers.md +++ b/docs/docs/customize/context-providers.md @@ -409,7 +409,8 @@ Reference table schemas from Sqlite, Postgres, MSSQL, and MySQL databases. "password": "yourPassword", "port": 5432 } - }{ + }, + { "name": "exampleMssql", "connection_type": "mssql", "connection": { From b65dbf8825aa6e4ba6442b1bfc23b789c47cc17d Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 30 Oct 2024 00:59:48 -0700 Subject: [PATCH 08/96] move files around --- .../{cache.ts => AutocompleteLruCache.ts} | 0 core/autocomplete/NearbyDefinitionsService.ts | 45 - core/autocomplete/README.md | 164 +- .../shouldCompleteMultiline.test.ts | 0 .../shouldCompleteMultiline.ts | 4 +- core/autocomplete/completionProvider.ts | 144 +- .../AutocompleteLanguageInfo.ts} | 2 +- .../AutocompleteTemplate.ts} | 6 +- core/autocomplete/constants/stopWords.ts | 11 + core/autocomplete/constructPrompt.ts | 12 +- .../ImportDefinitionsService.ts | 0 .../NearbyDefinitionsService.ts | 4 +- .../RootPathContextService.ts | 4 +- .../{ranking.ts => context/ranking/index.ts} | 6 +- .../{ => context/ranking}/slidingWindow.ts | 5 +- core/autocomplete/{ => context}/retrieval.ts | 0 .../BracketMatchingService.ts | 0 core/autocomplete/{ => filtering}/filter.ts | 0 .../streamTransforms}/charStream.test.ts | 0 .../streamTransforms/charStream.ts | 0 .../streamTransforms}/lineStream.test.ts | 0 .../streamTransforms/lineStream.ts | 0 .../test/NEGATIVE_CASES_STARCODER.tsx | 51 + .../filtering/test/filter.test.ts | 30 + core/autocomplete/filtering/test/testCases.ts | 2013 +++++++++++++++++ core/autocomplete/filtering/test/util.ts | 77 + .../GeneratorReuseManager.ts} | 76 +- .../generation/ListenableGenerator.ts | 75 + .../index.ts} | 6 +- core/autocomplete/types.ts | 38 + core/autocomplete/{ => util}/ast.ts | 4 +- core/core.ts | 2 +- core/edit/lazy/deterministic.ts | 2 +- core/protocol/core.ts | 2 +- 34 files changed, 2386 insertions(+), 397 deletions(-) rename core/autocomplete/{cache.ts => AutocompleteLruCache.ts} (100%) delete mode 100644 core/autocomplete/NearbyDefinitionsService.ts rename core/autocomplete/{ => classification}/shouldCompleteMultiline.test.ts (100%) rename core/autocomplete/{ => classification}/shouldCompleteMultiline.ts (93%) rename core/autocomplete/{languages.ts => constants/AutocompleteLanguageInfo.ts} (98%) rename core/autocomplete/{templates.ts => constants/AutocompleteTemplate.ts} (97%) create mode 100644 core/autocomplete/constants/stopWords.ts rename core/autocomplete/{services => context}/ImportDefinitionsService.ts (100%) rename core/autocomplete/{services => context}/NearbyDefinitionsService.ts (89%) rename core/autocomplete/{services => context}/RootPathContextService.ts (97%) rename core/autocomplete/{ranking.ts => context/ranking/index.ts} (97%) rename core/autocomplete/{ => context/ranking}/slidingWindow.ts (94%) rename core/autocomplete/{ => context}/retrieval.ts (100%) rename core/autocomplete/{services => filtering}/BracketMatchingService.ts (100%) rename core/autocomplete/{ => filtering}/filter.ts (100%) rename core/autocomplete/{ => filtering/streamTransforms}/charStream.test.ts (100%) rename core/autocomplete/{ => filtering}/streamTransforms/charStream.ts (100%) rename core/autocomplete/{ => filtering/streamTransforms}/lineStream.test.ts (100%) rename core/autocomplete/{ => filtering}/streamTransforms/lineStream.ts (100%) create mode 100644 core/autocomplete/filtering/test/NEGATIVE_CASES_STARCODER.tsx create mode 100644 core/autocomplete/filtering/test/filter.test.ts create mode 100644 core/autocomplete/filtering/test/testCases.ts create mode 100644 core/autocomplete/filtering/test/util.ts rename core/autocomplete/{util.ts => generation/GeneratorReuseManager.ts} (52%) create mode 100644 core/autocomplete/generation/ListenableGenerator.ts rename core/autocomplete/{postprocessing.ts => postprocessing/index.ts} (93%) create mode 100644 core/autocomplete/types.ts rename core/autocomplete/{ => util}/ast.ts (94%) diff --git a/core/autocomplete/cache.ts b/core/autocomplete/AutocompleteLruCache.ts similarity index 100% rename from core/autocomplete/cache.ts rename to core/autocomplete/AutocompleteLruCache.ts diff --git a/core/autocomplete/NearbyDefinitionsService.ts b/core/autocomplete/NearbyDefinitionsService.ts deleted file mode 100644 index 53178cba7..000000000 --- a/core/autocomplete/NearbyDefinitionsService.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { IDE, Location } from "../index.js"; -import { LANGUAGES } from "./languages.js"; -import { getSymbolsForSnippet } from "./ranking.js"; - -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/README.md b/core/autocomplete/README.md index e19509bd8..8b860a3cc 100644 --- a/core/autocomplete/README.md +++ b/core/autocomplete/README.md @@ -1,163 +1,29 @@ -# Tab Autocomplete (beta) +# Autocomplete -Continue now provides support for tab autocomplete in [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue) and [JetBrains IDEs](https://plugins.jetbrains.com/plugin/22707-continue/edit). We will be greatly improving the experience over the next few releases, and it is always helpful to hear feedback. If you have any problems or suggestions, please let us know in our [Discord](https://discord.gg/vapESyrFmJ). +The autocomplete pipeline: -## Setting up with Ollama (default) +## 1. Triggering -We recommend setting up tab-autocomplete with a local Ollama instance. To do this, first download the latest version of Ollama from [here](https://ollama.ai). Then, run the following command to download our recommended model: +### Debouncing -```bash -ollama run starcoder:3b -``` +## 2. Context gathering -Once it has been downloaded, you should begin to see completions in VS Code. +## 3. Prompt construction -## Setting up with LM Studio +This is fairly trivial, we just use the correct template/endpoint for the model. Any templates are defined in [`templates.ts`](./templates.ts). -You can also set up tab-autocomplete with a local LM Studio instance by following these steps: +## 4. Caching -1. Download the latest version of LM Studio from [here](https://lmstudio.ai/) -2. Download a model (e.g. search for `second-state/StarCoder2-3B-GGUF` and choose one of the options there) -3. Go to the server section (button is on the left), select your model from the dropdown at the top, and click "Start Server" -4. Go to the "My Models" section (button is on the left), find your selected model, and copy the name the path (example: `second-state/StarCoder2-3B-GGUF/starcoder2-3b-Q8_0.gguf`); this will be used as the "model" attribute in Continue -5. Go to Continue and modify the configurations for a [custom model](#setting-up-a-custom-model) -6. Set the "provider" to `lmstudio` and the "model" to the path copied earlier +## 4. Generation -Example: +### Reusing previous requests -```json title="config.json" -{ - "tabAutocompleteModel": { - "title": "Starcoder2 3b", - "model": "second-state/StarCoder2-3B-GGUF/starcoder2-3b-Q8_0.gguf", - "provider": "lmstudio", - }, - ... -} -``` +## 4. Classification -## Setting up a custom model +Is it multi-line or single-line? -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: +## 4. Filtering -```json title="config.json" -{ - "tabAutocompleteModel": { - "title": "Tab Autocomplete Model", - "provider": "openai", - "model": "", - "apiBase": "" - }, - ... -} -``` +## 5. Postprocessing -As another example, say you want to use a different model, `deepseek-coder:6.7b-base`, with Ollama: - -```json title="config.json" -{ - "tabAutocompleteModel": { - "title": "Tab Autocomplete Model", - "provider": "ollama", - "model": "deepseek-coder:6.7b-base" - }, - ... -} -``` - -If you aren't yet familiar with the available options, you can learn more in our [overview](../setup/overview.md). - -### What model should I use? - -If you are running the model locally, we recommend `starcoder:3b`. - -If you find it to be too slow, you should try `deepseek-coder:1.3b-base`. - -If you have a bit more compute, or are running a model in the cloud, you can upgrade to `deepseek-coder:6.7b-base`. - -Regardless of what you are willing to spend, we do not recommend using GPT or Claude for autocomplete. Learn why [below](#i-want-better-completions-should-i-use-gpt-4). - -## Configuration Options - -The following can be configured in `config.json`: - -### `tabAutocompleteModel` - -This is just another object like the ones in the `"models"` array of `config.json`. You can choose and configure any model you would like, but we strongly suggest using a small model made for tab-autocomplete, such as `deepseek-1b`, `starcoder-1b`, or `starcoder-3b`. - -### `tabAutocompleteOptions` - -This object allows you to customize the behavior of tab-autocomplete. The available options are: - -- `useCopyBuffer`: Determines whether the copy buffer will be considered when constructing the prompt. (Boolean) -- `useFileSuffix`: Determines whether to use the file suffix in the prompt. (Boolean) -- `maxPromptTokens`: The maximum number of prompt tokens to use. A smaller number will yield faster completions, but less context. (Number) -- `debounceDelay`: The delay in milliseconds before triggering autocomplete after a keystroke. (Number) -- `maxSuffixPercentage`: The maximum percentage of the prompt that can be dedicated to the suffix. (Number) -- `prefixPercentage`: The percentage of the input that should be dedicated to the prefix. (Number) -- `template`: An optional template string to be used for autocomplete. It will be rendered with the Mustache templating language, and is passed the 'prefix' and 'suffix' variables. (String) -- `multilineCompletions`: Whether to enable multiline completions ("always", "never", or "auto"). Defaults to "auto". - -### Full example - -```json title="config.json" -{ - "tabAutocompleteModel": { - "title": "Tab Autocomplete Model", - "provider": "ollama", - "model": "starcoder:3b", - "apiBase": "https://" - }, - "tabAutocompleteOptions": { - "useCopyBuffer": false, - "maxPromptTokens": 400, - "prefixPercentage": 0.5 - } -} -``` - -## Troubleshooting - -### I want better completions, should I use GPT-4? - -Perhaps surprisingly, the answer is no. The models that we suggest for autocomplete are trained with a highly specific prompt format, which allows them to respond to requests for completing code (see examples of these prompts [here](https://github.com/continuedev/continue/blob/d2bc6359e8ebf647892ec953e418042dc7f8a685/core/autocomplete/templates.ts)). Some of the best commercial models like GPT-4 or Claude are not trained with this prompt format, which means that they won't generate useful completions. Luckily, a huge model is not required for great autocomplete. Most of the state-of-the-art autocomplete models are no more than 10b parameters, and increasing beyond this does not significantly improve performance. - -### I'm not seeing any completions - -Follow these steps to ensure that everything is set up correctly: - -1. Make sure you have the "Enable Tab Autocomplete" setting checked (in VS Code, you can toggle by clicking the "Continue" button in the status bar). -2. Make sure you have downloaded Ollama. -3. Run `ollama run starcoder:3b` to verify that the model is downloaded. -4. Make sure that any other completion providers are disabled (e.g. Copilot), as they may interfere. -5. Make sure that you aren't also using another Ollama model for chat. This will cause Ollama to constantly load and unload the models from memory, resulting in slow responses (or none at all) for both. -6. Check the output of the logs to find any potential errors (cmd/ctrl+shift+p -> "Toggle Developer Tools" -> "Console" tab in VS Code, ~/.continue/logs/core.log in JetBrains). -7. If you are still having issues, please let us know in our [Discord](https://discord.gg/vapESyrFmJ) and we'll help as soon as possible. - -### Completions are slow - -Depending on your hardware, you may want to try a smaller, faster model. If 3b isn't working for you we recommend trying `deepseek-coder:1.3b-base`. - -### Completions don't know about my code - -We are working on this! Right now Continue uses the Language Server Protocol to add definitions to the prompt, as well as using similarity search over recently edited files. We will be improving the accuracy of this system greatly over the next few weeks. - -### Completions contain formatting errors - -If you're seeing a common pattern of mistake that might be helpful to report, please share in Discord. We will do our best to fix it as soon as possible. - -## How to turn off autocomplete - -### VS Code - -Click the "Continue" button in the status panel at the bottom right of the screen. The checkmark will become a "cancel" symbol and you will no longer see completions. You can click again to turn it back on. - -Alternatively, open VS Code settings, search for "Continue" and uncheck the box for "Enable Tab Autocomplete". - -### JetBrains - -Open Settings -> Tools -> Continue and uncheck the box for "Enable Tab Autocomplete". - -### Feedback - -If you're turning off autocomplete, we'd love to hear how we can improve! Please let us know in our [Discord](https://discord.gg/vapESyrFmJ) or file an issue on GitHub. +## 6. Telemetry diff --git a/core/autocomplete/shouldCompleteMultiline.test.ts b/core/autocomplete/classification/shouldCompleteMultiline.test.ts similarity index 100% rename from core/autocomplete/shouldCompleteMultiline.test.ts rename to core/autocomplete/classification/shouldCompleteMultiline.test.ts diff --git a/core/autocomplete/shouldCompleteMultiline.ts b/core/autocomplete/classification/shouldCompleteMultiline.ts similarity index 93% rename from core/autocomplete/shouldCompleteMultiline.ts rename to core/autocomplete/classification/shouldCompleteMultiline.ts index ae114151d..9c8172f85 100644 --- a/core/autocomplete/shouldCompleteMultiline.ts +++ b/core/autocomplete/classification/shouldCompleteMultiline.ts @@ -1,5 +1,5 @@ -import { AstPath } from "./ast"; -import { AutocompleteLanguageInfo } from "./languages"; +import { AutocompleteLanguageInfo } from "../constants/AutocompleteLanguageInfo"; +import { AstPath } from "../util/ast"; const BLOCK_TYPES = ["body", "statement_block"]; diff --git a/core/autocomplete/completionProvider.ts b/core/autocomplete/completionProvider.ts index 216286fcc..8458e1281 100644 --- a/core/autocomplete/completionProvider.ts +++ b/core/autocomplete/completionProvider.ts @@ -2,18 +2,10 @@ import ignore from "ignore"; import OpenAI from "openai"; import path from "path"; import { v4 as uuidv4 } from "uuid"; -import { RangeInFileWithContents } from "../commands/util.js"; import { ConfigHandler } from "../config/ConfigHandler.js"; import { TRIAL_FIM_MODEL } from "../config/onboarding.js"; import { streamLines } from "../diff/util.js"; -import { - IDE, - ILLM, - ModelProvider, - Position, - Range, - TabAutocompleteOptions, -} from "../index.js"; +import { IDE, ILLM, ModelProvider, TabAutocompleteOptions } from "../index.js"; import { logDevData } from "../util/devdata.js"; import { getBasename, getLastNPathParts } from "../util/index.js"; import { @@ -23,17 +15,24 @@ import { import { Telemetry } from "../util/posthog.js"; import { getRangeInString } from "../util/ranges.js"; -import AutocompleteLruCache from "./cache.js"; +import { AutocompleteLanguageInfo } from "./constants/AutocompleteLanguageInfo.js"; +import { getTemplateForModel } from "./constants/AutocompleteTemplate.js"; import { constructAutocompletePrompt, languageForFilepath, } from "./constructPrompt.js"; -import { isOnlyWhitespace } 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 { AutocompleteSnippet } from "./context/ranking/index.js"; +import { RootPathContextService } from "./context/RootPathContextService.js"; +import { isOnlyWhitespace } from "./filtering/filter.js"; +import { GeneratorReuseManager } from "./generation/GeneratorReuseManager.js"; +import { postprocessCompletion } from "./postprocessing/index.js"; +// @prettier-ignore +import Handlebars from "handlebars"; +import { getConfigJsonPath } from "../util/paths.js"; +import AutocompleteLruCache from "./AutocompleteLruCache.js"; +import { ImportDefinitionsService } from "./context/ImportDefinitionsService.js"; +import { BracketMatchingService } from "./filtering/BracketMatchingService.js"; +import { stopAtStopTokens } from "./filtering/streamTransforms/charStream.js"; import { avoidPathLineAndEmptyComments, noTopLevelKeywordsMidline, @@ -42,68 +41,11 @@ import { stopAtRepeatingLines, stopAtSimilarLine, streamWithNewLines, -} 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; - filepath: string; - pos: Position; - recentlyEditedFiles: RangeInFileWithContents[]; - recentlyEditedRanges: RecentlyEditedRange[]; - clipboardText: string; - // Used for notebook files - manuallyPassFileContents?: string; - // Used for VS Code git commit input box - manuallyPassPrefix?: string; - selectedCompletionInfo?: { - text: string; - range: Range; - }; - injectDetails?: string; -} - -export interface AutocompleteOutcome extends TabAutocompleteOptions { - accepted?: boolean; - time: number; - prefix: string; - suffix: string; - prompt: string; - completion: string; - modelProvider: string; - modelName: string; - completionOptions: any; - cacheHit: boolean; - filepath: string; - gitRepo?: string; - completionId: string; - uniqueId: string; -} +} from "./filtering/streamTransforms/lineStream.js"; +import { AutocompleteInput, AutocompleteOutcome } from "./types.js"; const autocompleteCache = AutocompleteLruCache.get(); -const DOUBLE_NEWLINE = "\n\n"; -const WINDOWS_DOUBLE_NEWLINE = "\r\n\r\n"; -const SRC_DIRECTORY = "/src/"; -// Starcoder2 tends to output artifacts starting with the letter "t" -const STARCODER2_T_ARTIFACTS = ["t.", "\nt", ""]; -const PYTHON_ENCODING = "#- coding: utf-8"; -const CODE_BLOCK_END = "```"; - -const multilineStops: string[] = [DOUBLE_NEWLINE, WINDOWS_DOUBLE_NEWLINE]; -const commonStops = [SRC_DIRECTORY, PYTHON_ENCODING, CODE_BLOCK_END]; - // Errors that can be expected on occasion even during normal functioning should not be shown. // Not worth disrupting the user to tell them that a single autocomplete request didn't go through const ERRORS_TO_IGNORE = [ @@ -262,7 +204,8 @@ export class CompletionProvider { for (const workspaceDir of workspaceDirs) { const relativePath = path.relative(workspaceDir, filepath); const relativePathBase = relativePath.split(path.sep).at(0); - const isInWorkspace = !path.isAbsolute(relativePath) && relativePathBase !== ".."; + const isInWorkspace = + !path.isAbsolute(relativePath) && relativePathBase !== ".."; if (isInWorkspace) { filepath = path.relative(workspaceDir, filepath); break; @@ -489,10 +432,11 @@ export class CompletionProvider { if (input.injectDetails) { const lines = fullPrefix.split("\n"); - fullPrefix = `${lines.slice(0, -1).join("\n")}\n${lang.singleLineComment - } ${input.injectDetails - .split("\n") - .join(`\n${lang.singleLineComment} `)}\n${lines[lines.length - 1]}`; + fullPrefix = `${lines.slice(0, -1).join("\n")}\n${ + lang.singleLineComment + } ${input.injectDetails + .split("\n") + .join(`\n${lang.singleLineComment} `)}\n${lines[lines.length - 1]}`; } const fullSuffix = getRangeInString(fileContents, { @@ -513,17 +457,17 @@ export class CompletionProvider { let extrasSnippets = options.useOtherFiles ? ((await Promise.race([ - this.getDefinitionsFromLsp( - filepath, - fullPrefix + fullSuffix, - fullPrefix.length, - this.ide, - lang, - ), - new Promise((resolve) => { - setTimeout(() => resolve([]), 100); - }), - ])) as AutocompleteSnippet[]) + this.getDefinitionsFromLsp( + filepath, + fullPrefix + fullSuffix, + fullPrefix.length, + this.ide, + lang, + ), + new Promise((resolve) => { + setTimeout(() => resolve([]), 100); + }), + ])) as AutocompleteSnippet[]) : []; const workspaceDirs = await this.ide.getWorkspaceDirs(); @@ -562,8 +506,8 @@ export class CompletionProvider { completionOptions, compilePrefixSuffix = undefined, } = options.template - ? { template: options.template, completionOptions: {} } - : getTemplateForModel(llm.model); + ? { template: options.template, completionOptions: {} } + : getTemplateForModel(llm.model); let prompt: string; const filename = getBasename(filepath); @@ -660,14 +604,14 @@ export class CompletionProvider { () => llm.supportsFim() ? llm.streamFim(prefix, suffix, { - ...completionOptions, - stop, - }) + ...completionOptions, + stop, + }) : llm.streamComplete(prompt, { - ...completionOptions, - raw: true, - stop, - }), + ...completionOptions, + raw: true, + stop, + }), multiline, ); diff --git a/core/autocomplete/languages.ts b/core/autocomplete/constants/AutocompleteLanguageInfo.ts similarity index 98% rename from core/autocomplete/languages.ts rename to core/autocomplete/constants/AutocompleteLanguageInfo.ts index be414098a..3af6e2e15 100644 --- a/core/autocomplete/languages.ts +++ b/core/autocomplete/constants/AutocompleteLanguageInfo.ts @@ -1,4 +1,4 @@ -import { LineFilter } from "./streamTransforms/lineStream"; +import { LineFilter } from "../filtering/streamTransforms/lineStream"; export interface AutocompleteLanguageInfo { name: string; diff --git a/core/autocomplete/templates.ts b/core/autocomplete/constants/AutocompleteTemplate.ts similarity index 97% rename from core/autocomplete/templates.ts rename to core/autocomplete/constants/AutocompleteTemplate.ts index cda8b8a2d..034426f91 100644 --- a/core/autocomplete/templates.ts +++ b/core/autocomplete/constants/AutocompleteTemplate.ts @@ -1,8 +1,8 @@ // Fill in the middle prompts -import { CompletionOptions } from "../index.js"; -import { getLastNPathParts, shortestRelativePaths } from "../util/index.js"; -import { AutocompleteSnippet } from "./ranking.js"; +import { CompletionOptions } from "../../index.js"; +import { getLastNPathParts, shortestRelativePaths } from "../../util/index.js"; +import { AutocompleteSnippet } from "../context/ranking/index.js"; interface AutocompleteTemplate { compilePrefixSuffix?: ( diff --git a/core/autocomplete/constants/stopWords.ts b/core/autocomplete/constants/stopWords.ts new file mode 100644 index 000000000..94d29cf40 --- /dev/null +++ b/core/autocomplete/constants/stopWords.ts @@ -0,0 +1,11 @@ +const DOUBLE_NEWLINE = "\n\n"; +const WINDOWS_DOUBLE_NEWLINE = "\r\n\r\n"; +// TODO: Do we want to stop completions when reaching a `/src/` string? +const SRC_DIRECTORY = "/src/"; +// Starcoder2 tends to output artifacts starting with the letter "t" +const STARCODER2_T_ARTIFACTS = ["t.", "\nt", ""]; +const PYTHON_ENCODING = "#- coding: utf-8"; +const CODE_BLOCK_END = "```"; + +const multilineStops: string[] = [DOUBLE_NEWLINE, WINDOWS_DOUBLE_NEWLINE]; +const commonStops = [SRC_DIRECTORY, PYTHON_ENCODING, CODE_BLOCK_END]; diff --git a/core/autocomplete/constructPrompt.ts b/core/autocomplete/constructPrompt.ts index 17b78fa01..889db0d76 100644 --- a/core/autocomplete/constructPrompt.ts +++ b/core/autocomplete/constructPrompt.ts @@ -6,23 +6,23 @@ import { pruneLinesFromBottom, pruneLinesFromTop, } from "../llm/countTokens.js"; -import { AstPath, getAst, getTreePathAtCursor } from "./ast.js"; +import { shouldCompleteMultiline } from "./classification/shouldCompleteMultiline.js"; import { AutocompleteLanguageInfo, LANGUAGES, Typescript, -} from "./languages.js"; +} from "./constants/AutocompleteLanguageInfo.js"; +import { ImportDefinitionsService } from "./context/ImportDefinitionsService.js"; import { fillPromptWithSnippets, getSymbolsForSnippet, rankSnippets, removeRangeFromSnippets, type AutocompleteSnippet, -} from "./ranking.js"; +} from "./context/ranking/index.js"; +import { RootPathContextService } from "./context/RootPathContextService.js"; import { RecentlyEditedRange, findMatchingRange } from "./recentlyEdited.js"; -import { ImportDefinitionsService } from "./services/ImportDefinitionsService.js"; -import { RootPathContextService } from "./services/RootPathContextService.js"; -import { shouldCompleteMultiline } from "./shouldCompleteMultiline.js"; +import { AstPath, getAst, getTreePathAtCursor } from "./util/ast.js"; export function languageForFilepath( filepath: string, diff --git a/core/autocomplete/services/ImportDefinitionsService.ts b/core/autocomplete/context/ImportDefinitionsService.ts similarity index 100% rename from core/autocomplete/services/ImportDefinitionsService.ts rename to core/autocomplete/context/ImportDefinitionsService.ts diff --git a/core/autocomplete/services/NearbyDefinitionsService.ts b/core/autocomplete/context/NearbyDefinitionsService.ts similarity index 89% rename from core/autocomplete/services/NearbyDefinitionsService.ts rename to core/autocomplete/context/NearbyDefinitionsService.ts index 12d6f7947..6e4cece83 100644 --- a/core/autocomplete/services/NearbyDefinitionsService.ts +++ b/core/autocomplete/context/NearbyDefinitionsService.ts @@ -1,6 +1,6 @@ import { IDE, Location } from "../.."; -import { LANGUAGES } from "../languages"; -import { getSymbolsForSnippet } from "../ranking"; +import { LANGUAGES } from "../constants/AutocompleteLanguageInfo"; +import { getSymbolsForSnippet } from "./ranking"; interface FileInfo { filepath: string; diff --git a/core/autocomplete/services/RootPathContextService.ts b/core/autocomplete/context/RootPathContextService.ts similarity index 97% rename from core/autocomplete/services/RootPathContextService.ts rename to core/autocomplete/context/RootPathContextService.ts index 69426aab8..2b2986b75 100644 --- a/core/autocomplete/services/RootPathContextService.ts +++ b/core/autocomplete/context/RootPathContextService.ts @@ -3,9 +3,9 @@ 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 { AstPath } from "../util/ast"; import { ImportDefinitionsService } from "./ImportDefinitionsService"; +import { AutocompleteSnippet } from "./ranking"; export class RootPathContextService { private cache = new LRUCache({ diff --git a/core/autocomplete/ranking.ts b/core/autocomplete/context/ranking/index.ts similarity index 97% rename from core/autocomplete/ranking.ts rename to core/autocomplete/context/ranking/index.ts index 48e01d5ff..4809901cd 100644 --- a/core/autocomplete/ranking.ts +++ b/core/autocomplete/context/ranking/index.ts @@ -1,6 +1,6 @@ -import { RangeInFileWithContents } from "../commands/util.js"; -import { Range } from "../index.js"; -import { countTokens } from "../llm/countTokens.js"; +import { RangeInFileWithContents } from "../../../commands/util.js"; +import { Range } from "../../../index.js"; +import { countTokens } from "../../../llm/countTokens.js"; export type AutocompleteSnippet = RangeInFileWithContents & { score?: number; diff --git a/core/autocomplete/slidingWindow.ts b/core/autocomplete/context/ranking/slidingWindow.ts similarity index 94% rename from core/autocomplete/slidingWindow.ts rename to core/autocomplete/context/ranking/slidingWindow.ts index 72aa1a5ee..37d1a7d9e 100644 --- a/core/autocomplete/slidingWindow.ts +++ b/core/autocomplete/context/ranking/slidingWindow.ts @@ -1,5 +1,8 @@ import { RangeInFileWithContents } from "../commands/util.js"; -import { AutocompleteSnippet, jaccardSimilarity } from "./ranking.js"; +import { + AutocompleteSnippet, + jaccardSimilarity, +} from "./context/ranking/index.js"; function* slidingWindow( content: string, diff --git a/core/autocomplete/retrieval.ts b/core/autocomplete/context/retrieval.ts similarity index 100% rename from core/autocomplete/retrieval.ts rename to core/autocomplete/context/retrieval.ts diff --git a/core/autocomplete/services/BracketMatchingService.ts b/core/autocomplete/filtering/BracketMatchingService.ts similarity index 100% rename from core/autocomplete/services/BracketMatchingService.ts rename to core/autocomplete/filtering/BracketMatchingService.ts diff --git a/core/autocomplete/filter.ts b/core/autocomplete/filtering/filter.ts similarity index 100% rename from core/autocomplete/filter.ts rename to core/autocomplete/filtering/filter.ts diff --git a/core/autocomplete/charStream.test.ts b/core/autocomplete/filtering/streamTransforms/charStream.test.ts similarity index 100% rename from core/autocomplete/charStream.test.ts rename to core/autocomplete/filtering/streamTransforms/charStream.test.ts diff --git a/core/autocomplete/streamTransforms/charStream.ts b/core/autocomplete/filtering/streamTransforms/charStream.ts similarity index 100% rename from core/autocomplete/streamTransforms/charStream.ts rename to core/autocomplete/filtering/streamTransforms/charStream.ts diff --git a/core/autocomplete/lineStream.test.ts b/core/autocomplete/filtering/streamTransforms/lineStream.test.ts similarity index 100% rename from core/autocomplete/lineStream.test.ts rename to core/autocomplete/filtering/streamTransforms/lineStream.test.ts diff --git a/core/autocomplete/streamTransforms/lineStream.ts b/core/autocomplete/filtering/streamTransforms/lineStream.ts similarity index 100% rename from core/autocomplete/streamTransforms/lineStream.ts rename to core/autocomplete/filtering/streamTransforms/lineStream.ts diff --git a/core/autocomplete/filtering/test/NEGATIVE_CASES_STARCODER.tsx b/core/autocomplete/filtering/test/NEGATIVE_CASES_STARCODER.tsx new file mode 100644 index 000000000..269d25f0f --- /dev/null +++ b/core/autocomplete/filtering/test/NEGATIVE_CASES_STARCODER.tsx @@ -0,0 +1,51 @@ +##### Prompt ##### +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; + } +} +========================================================================== +========================================================================== +Completion: + + this.result /= number; + return this; + } +} + +module.exports = Calculator; \ No newline at end of file diff --git a/core/autocomplete/filtering/test/filter.test.ts b/core/autocomplete/filtering/test/filter.test.ts new file mode 100644 index 000000000..171b1cb44 --- /dev/null +++ b/core/autocomplete/filtering/test/filter.test.ts @@ -0,0 +1,30 @@ +import { + AutocompleteFileringTestInput, + testAutocompleteFiltering, +} from "./util"; +import { TEST_CASES } from "./testCases"; + +const filterTestCases = (tests: AutocompleteFileringTestInput[]) => { + if (tests.some((test) => test.options?.only)) { + return tests.filter((test) => test.options?.only); + } + + return tests; +}; + +describe("llms/Mock", () => { + describe("Autocomplete Filtering Tests", () => { + beforeEach(async () => { + await new Promise((resolve) => setTimeout(resolve, 50)); + }); + + describe("Should return unmodified LLM output", () => { + it.each(filterTestCases(TEST_CASES))("$description", async (testCase) => { + await testAutocompleteFiltering(testCase); + }); + }); + + // TODO: Add test cases where modifying LLM output is desirable + describe.skip("Should return modified LLM output", () => {}); + }); +}); diff --git a/core/autocomplete/filtering/test/testCases.ts b/core/autocomplete/filtering/test/testCases.ts new file mode 100644 index 000000000..c3c19dfea --- /dev/null +++ b/core/autocomplete/filtering/test/testCases.ts @@ -0,0 +1,2013 @@ +import { dedent } from "../../../util"; +import { AutocompleteFileringTestInput } from "./util"; + +export const TEST_CASES: AutocompleteFileringTestInput[] = [ + { + description: "should pass", + filename: "test.js", + input: "console.log('Hello <|fim|>!');", + llmOutput: "World", + expectedCompletion: "World", + }, + { + description: + "Should preserve closing brackets when the opening bracket is not a part of the completion.", + filename: "test.js", + input: dedent` + 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) { + <|fim|> + + getResult() { + return this.result; + } + + reset() { + this.result = 0; + return this; + } + } + `, + llmOutput: dedent`if (number === 0) { + throw new Error("Cannot divide by zero"); + } + this.result /= number; + return this; + }`, + expectedCompletion: dedent`if (number === 0) { + throw new Error("Cannot divide by zero"); + } + this.result /= number; + return this; + }`, + }, + { + description: "Should multiline-autocomplete CSS blocks", + input: `body { + font-family: Arial, sans-serif; + font-size: 16px; + color: #333333; +} + +h1 { + font-size: 24px; + font-weight: bold; + color: #000000; +} + +h4<|fim|> + +a { + text-decoration: none; + color: #007bff; +} + +.container { + width: 100%; + max-width: 1200px; + margin: 0 auto; + padding: 20px; +} + +.button { + display: inline-block; + padding: 10px 20px; + background-color: #007bff; + color: #ffffff;`, + llmOutput: ` { + font-size: 18px; + font-weight: bold; + color: #000000; +}`, + expectedCompletion: ` { + font-size: 18px; + font-weight: bold; + color: #000000; +}`, + filename: "test.css", + }, + { + description: "Should complete CSS rules inside a nested selector", + filename: "styles.css", + input: ` +.container { + display: flex; + justify-content: center; + align-items: center; + width: 100%; + height: 100vh; + + .inner { + <|fim|> + } +} +`, + llmOutput: `width: 50%; + height: 50%; + background-color: #f0f0f0;`, + expectedCompletion: `width: 50%; + height: 50%; + background-color: #f0f0f0;`, + }, + + { + description: + "Should complete a CSS rule when the property is partially typed", + filename: "styles.css", + input: ` +button { + border: 2px solid #000; + border-radius<|fim|> +}`, + llmOutput: `: 5px;`, + expectedCompletion: `: 5px;`, + }, + + { + description: "Should handle CSS autocomplete with a single bracket present", + filename: "styles.css", + input: ` +.card { + box-shadow: 0 4px 8px rgba(0,0,0,0.2); + transition: 0.3s; + padding: 16px; + border-bottom-left-radius: <|fim|>px; + border-bottom-right-radius: 8px; +} +`, + llmOutput: `8`, + expectedCompletion: `8`, + }, + + { + description: "Should autocomplete CSS pseudoclass", + filename: "pseudoClass.css", + input: ` +input:focus { + outline: none; + border: 2px solid <|fim|>; +} +`, + llmOutput: `#4CAF50;`, + expectedCompletion: `#4CAF50;`, + }, + + { + description: "Should handle CSS variable syntax", + filename: "variables.css", + input: ` +:root { + --primary-color: #3498db; + --padding: 10px; +} + +.section { + background-color: var(<|fim|>); + padding: var(--padding); +} +`, + llmOutput: `--primary-color`, + expectedCompletion: `--primary-color`, + }, + { + description: "Should complete CSS grid template columns", + filename: "grid.css", + input: ` +.grid-container { + display: grid; + grid-template-columns: repeat(<|fim|>); + grid-gap: 10px; +} +`, + llmOutput: `3, 1fr`, + expectedCompletion: `3, 1fr`, + }, + + { + description: "Should complete PHP function inside a class with comments", + input: `name = $name; + $this->email = $email; + } + + public function <|fim|> + + public function setEmail($email) { + $this->email = $email; + } +}`, + llmOutput: `getDetails() { + return "Name: " . $this->name . ", Email: " . $this->email; + }`, + expectedCompletion: `getDetails() { + return "Name: " . $this->name . ", Email: " . $this->email; + }`, + filename: "User.php", + }, + + { + description: "Should autocomplete PHP function with inline logic", + input: ` +} + +echo calculateArea(5, 3);`, + llmOutput: `return $length * $width;`, + expectedCompletion: `return $length * $width;`, + filename: "areaCalculator.php", + }, + + { + description: "Should handle PHP completion in the middle of an array", + input: `); + +echo "First color is: " . $colors[0];`, + llmOutput: `"Blue"`, + expectedCompletion: `"Blue"`, + filename: "colors.php", + }, + { + description: "Should autocomplete React return statements (jsx)", + input: `import React from "react"; + +export const Button = ({ + onClick, + children, +}: { + children: React.ReactNode; + onClick: () => void; +}) => { + return ( +<|fim|> + ); +};`, + llmOutput: ``, + expectedCompletion: ``, + filename: "Button.tsx", + }, + { + description: "Should autocomplete React state initialization", + input: `import React, { useState } from "react"; + +export const Counter = () => { + const [count, setCount] = useState(<|fim|>); + + return ( +
+

You clicked {count} times

+ +
+ ); +};`, + llmOutput: `0`, + expectedCompletion: `0`, + filename: "Counter.tsx", + }, + + { + description: "Should autocomplete React effect hook", + input: `import React, { useState, useEffect } from "react"; + +export const Timer = () => { + const [seconds, setSeconds] = useState(0); + + useEffect(() => { + const interval = setInterval(() => { + setSeconds(seconds + 1); + }, 1000); + + <|fim|>; + + return () => clearInterval(interval); + }, [seconds]); + + return ( +
+

{seconds} seconds have passed.

+
+ ); +};`, + llmOutput: `return () => clearInterval(interval);`, + expectedCompletion: `return () => clearInterval(interval);`, + filename: "Timer.tsx", + }, + + { + description: "Should autocomplete React component methods", + input: `import React from "react"; + +class Form extends React.Component { + constructor(props) { + super(props); + this.state = { name: '' }; + } + + handleChange = (event) => { + <|fim|> + } + + handleSubmit = (event) => { + event.preventDefault(); + alert('A name was submitted: ' + this.state.name); + } + + render() { + return ( +
+ + +
+ ); + } +}`, + llmOutput: `this.setState({ name: event.target.value });`, + expectedCompletion: `this.setState({ name: event.target.value });`, + filename: "Form.tsx", + }, + { + description: "Should autocomplete Python function definition", + filename: "test.py", + input: `def calculate_area(length, width): + area = length * width + return area + +def calculate_perimeter(length, width): + <|fim|> +`, + llmOutput: `perimeter = 2 * (length + width) + return perimeter`, + expectedCompletion: `perimeter = 2 * (length + width) + return perimeter`, + }, + { + description: "Should complete Python class method with self", + filename: "test.py", + input: `class BankAccount: + def __init__(self, owner, balance=0): + self.owner = owner + self.balance = balance + + def deposit(self, amount): + self.balance += amount + return self.balance + + def withdraw(self, amount): + <|fim|> +`, + llmOutput: `if amount > self.balance: + return "Insufficient funds" + self.balance -= amount + return self.balance`, + expectedCompletion: `if amount > self.balance: + return "Insufficient funds" + self.balance -= amount + return self.balance`, + }, + { + description: "Should autocomplete Python list comprehension", + filename: "test.py", + input: `squares = [x**2 for x in range(10)] +even_squares = [x for x in squares if x % 2 == 0] +print(even_squares) + +odd_squares = [<|fim|> +print(odd_squares) +`, + llmOutput: `x for x in squares if x % 2 != 0`, + expectedCompletion: `x for x in squares if x % 2 != 0`, + }, + { + description: "Should handle python multi-line string", + filename: "test.py", + input: `def create_greeting(name): + greeting = """Hello, """ + name + """! +Welcome to our community. We hope you have a great time here. +If you have any questions, feel free to reach out.""" + return greeting + +message = create_greeting("Alice") +print(message) + +multi_line_message = """<|fim|> +print(multi_line_message) +`, + llmOutput: `This is a multi-line message. +It continues across multiple lines, +which allows for easy reading and formatting. +""" +`, + expectedCompletion: `This is a multi-line message. +It continues across multiple lines, +which allows for easy reading and formatting. +""" +`, + }, + { + description: "Should autocomplete a simple Go function declaration", + filename: "simpleFunction.go", + input: `package main + +import ( + "fmt" +) + +func main() { + fmt.Println("Hello, World!") +} + +func calculateArea<|fim|>`, + llmOutput: `(length float64, width float64) float64 { + return length * width +}`, + expectedCompletion: `(length float64, width float64) float64 { + return length * width +}`, + }, + + { + description: + "Should handle autocomplete in the middle of a Go struct definition", + filename: "structDefinition.go", + input: `package main + +type Person struct { + FirstName string + LastName string + Age int + Address Address +} + +type Address struct { + Street string + City <|fim|> +} + +func main() {}`, + llmOutput: `string + State string + ZipCode string +}`, + expectedCompletion: `string + State string + ZipCode string +}`, + }, + + { + description: "Should autocomplete a missing Go function body bracket", + filename: "missingBracket.go", + input: `package main + +func add(a int, b int) int { + return a + b<|fim|> + +func multiply(a int, b int) int { + return a * b +} + +func main() { + result1 := add(2, 3) + result2 := multiply(4, 5) + println(result1, result2) +}`, + llmOutput: ` +}`, + expectedCompletion: ` +}`, + }, + { + description: + "Should autocomplete SQL query with subquery and alias in SELECT clause", + filename: "complex_query.sql", + input: `SELECT u.id, + u.name, + (SELECT COUNT(*) FROM orders o WHERE o.user_id = u.id) AS order_count + FROM users u + WHERE u.active = 1 + <|fim|>`, + llmOutput: ` AND EXISTS (SELECT 1 FROM transactions t WHERE t.user_id = u.id AND t.amount > 100)`, + expectedCompletion: ` AND EXISTS (SELECT 1 FROM transactions t WHERE t.user_id = u.id AND t.amount > 100)`, + }, + { + description: + "Should autocomplete SQL query with nested functions and missing bracket", + filename: "_nested_function.sql", + input: `SELECT name, ROUND(AVG(rating), 2) as avg_rating + FROM movies + WHERE release_year > 2000 AND director = 'Christopher Nolan' + GROUP BY name + HAVING avg_rating > <|fim|>`, + llmOutput: `8.5)`, + expectedCompletion: `8.5)`, + }, + { + description: + "Should autocomplete multi-line SQL query with CASE statements", + filename: "case_statement.sql", + input: `SELECT order_id, + order_date, + CASE + WHEN status = 'shipped' THEN 'Completed' + WHEN status = 'pending' THEN 'Pending Approval' + <|fim|> + ELSE 'Unknown' + END as order_status + FROM orders`, + llmOutput: `WHEN status = 'cancelled' THEN 'Cancelled'`, + expectedCompletion: `WHEN status = 'cancelled' THEN 'Cancelled'`, + }, + { + description: "Should autocomplete HTML paragraph content", + input: ` + + Document + + +

<|fim|>

+ +`, + llmOutput: `This is a paragraph with some sample text.`, + expectedCompletion: `This is a paragraph with some sample text.`, + filename: "test.html", + }, + { + description: "Should autocomplete HTML attributes within a tag", + input: `
+ > +
+

Title

+

Description text.

+
+
`, + llmOutput: `alt="Description of image"`, + expectedCompletion: `alt="Description of image"`, + filename: "test.html", + }, + { + description: "Should autocomplete HTML nested tags", + input: `
    +
  • Item 1
  • +
  • Item 2
  • +
  • Item 3
  • +
`, + llmOutput: `>Item 4`, + expectedCompletion: `>Item 4`, + filename: "test.html", + }, + + { + description: "Should complete a class method in Ruby", + input: ` +class Greeter + def initialize(name) + @name = name + end + + def greet + puts "Hello, <|fim|> + end +end + +g = Greeter.new("World") +g.greet +`, + llmOutput: "#{@name}!", + expectedCompletion: "#{@name}!", + filename: "greeter.rb", + }, + { + description: "Should complete Ruby if-else block", + input: ` +number = 10 + +if number > 5 + puts "Number is greater than 5" +<|fim|> +end +`, + llmOutput: `else + puts "Number is 5 or less"`, + expectedCompletion: `else + puts "Number is 5 or less"`, + filename: "conditional.rb", + }, + { + description: "Should complete Ruby array method", + input: ` +numbers = [1, 2, 3, 4, 5] +squared_numbers = numbers.<|fim|> +`, + llmOutput: `map { |n| n ** 2 }`, + expectedCompletion: `map { |n| n ** 2 }`, + filename: "array_methods.rb", + }, + { + description: "Should autocomplete a Java method within a class", + filename: "Calculator.java", + input: ` +public class Calculator { + private double result; + + public Calculator() { + this.result = 0.0; + } + + public void add(double number) { + result += number; +<|fim|>`, + llmOutput: ` + } + + public void subtract(double number) { + result -= number; + } +`, + expectedCompletion: ` + } + + public void subtract(double number) { + result -= number; + } +`, + }, + { + description: "Should autocomplete Java when inside a block", + filename: "Main.java", + input: ` +public class Main { + public static void main(String[] args) { + for (int i = 0; i < 10; i++) { + if (i % 2 == 0) { + System.out.println("Even: " + i); + } else { +<|fim|> + } + } + } +}`, + llmOutput: ` + System.out.println("Odd: " + i); +`, + expectedCompletion: ` + System.out.println("Odd: " + i); +`, + }, + { + description: "Should autocomplete Java within a string", + filename: "App.java", + input: ` +public class App { + public static void main(String[] args) { + String message = "Hello, <|fim|>"; + System.out.println(message); + } +}`, + llmOutput: `World`, + expectedCompletion: `World`, + }, + { + description: + "Should autocomplete a C++ class definition with a constructor", + filename: "test.cpp", + input: "class Vehicle { public: Vehicle(<|fim|>); };", + llmOutput: "int wheels, double weight", + expectedCompletion: "int wheels, double weight", + }, + { + description: "Should complete a C++ method declaration inside a class", + filename: "test.cpp", + input: + "class Calculator { public: int add(int a, int b); int subtract(int a, int b);<|fim|> };", + llmOutput: " int multiply(int a, int b);", + expectedCompletion: " int multiply(int a, int b);", + }, + + { + description: "Should autocomplete C++ for loop syntax", + filename: "test.cpp", + input: ` + int sum = 0; + for (int i = 0; i < 10; <|fim|>) { + sum += i; + } + `, + llmOutput: "i++", + expectedCompletion: "i++", + }, + { + description: "Should autocomplete a Markdown list with nested items", + filename: "test.md", + input: ` +- Item 1 +- Item 2 + - Subitem 1 + <|fim|> +- Item 3 +`, + llmOutput: ` - Subitem 2 + - Subitem 3 +`, + expectedCompletion: ` - Subitem 2 + - Subitem 3 +`, + }, + { + description: + "Should autocomplete a Markdown heading and preserve formatting", + filename: "test.md", + input: `# My Document + +## Introduction +This is a sample document for testing. + +## <|fim|> +### Conclusion +Thank you for reading. +`, + llmOutput: `Features +Here is a list of features: +- Feature 1 +- Feature 2 +`, + expectedCompletion: `Features +Here is a list of features: +- Feature 1 +- Feature 2 +`, + }, + { + description: "Should complete a Markdown code block", + filename: "test.md", + input: ` +Here is a sample JavaScript function: + +\`\`\`javascript +function sayHello() { + console.log("Hello, <|fim|> +} +\`\`\` +`, + llmOutput: `world!"); +`, + expectedCompletion: `world!"); +`, + }, + { + description: "Should autocomplete JSON object inside an array", + filename: "data.json", + input: `{ + "users": [ + { "id": 1, "name": "Alice" }, + { "id": 2, "name": "Bob" } + <|fim|> + ] +}`, + llmOutput: `, { "id": 3, "name": "Charlie" }`, + expectedCompletion: `, { "id": 3, "name": "Charlie" }`, + }, + { + description: "Should autocomplete nested JSON objects", + filename: "config.json", + input: `{ + "server": { + "host": "localhost", + "port": 8080, + "features": { + "enableLogging": true, + "maxConnections": 100 + <|fim|> + } +}`, + llmOutput: `, + "timeout": 5000 + }`, + expectedCompletion: `, + "timeout": 5000 + }`, + }, + { + description: "Should autocomplete JSON object with missing bracket", + filename: "settings.json", + input: `{ + "theme": "dark", + "language": "en"<|fim|> + `, + llmOutput: `, + "notifications": true + }`, + expectedCompletion: `, + "notifications": true + }`, + }, + { + description: "Should autocomplete within a CSV record", + filename: "test.csv", + input: `Name, Age, City +John Doe, 30, New York +Jane Smith<|fim|>`, + llmOutput: `, 25, Los Angeles`, + expectedCompletion: `, 25, Los Angeles`, + }, + { + description: + "Should complete CSV record when starting in the middle of a word", + filename: "test.csv", + input: `Product, Price, Quantity +Laptop, 1200, 5 +Smart<|fim|>`, + llmOutput: `phone, 800, 10`, + expectedCompletion: `phone, 800, 10`, + }, + { + description: "Should complete CSV structure adding closing brackets", + filename: "test.csv", + input: `ID, Name, JoiningDate +1, Alice, 2023-01-10 +2, B<|fim|>`, + llmOutput: `ob, 2023-02-10`, + expectedCompletion: `ob, 2023-02-10`, + }, + { + description: "Should complete YAML list item and preserve structure", + filename: "test.yaml", + input: ` + services: + - name: web + image: nginx + - name: app<|fim|> + volumes: + - volume1 + - volume2 + `, + llmOutput: ` + image: node + `, + expectedCompletion: ` + image: node + `, + }, + { + description: + "Should complete YAML key-value pair inside a nested structure", + filename: "test.yaml", + input: ` + version: '3' + services: + db: + image: postgres + environment: + POSTGRES_USER: user + POSTGRES_PASSWORD: pass + POSTGRES_DB: mydb<|fim|> + `, + llmOutput: ` + PGDATA: /var/lib/postgresql/data/pgdata + `, + expectedCompletion: ` + PGDATA: /var/lib/postgresql/data/pgdata + `, + }, + { + description: "Should complete YAML block within an existing block", + filename: "test.yaml", + input: ` + pipelines: + branches: + master: + - step: + name: Build and Test + script: + - npm install + - npm run test + - step: + name: Deploy<|fim|> + `, + llmOutput: ` + script: + - npm run deploy + `, + expectedCompletion: ` + script: + - npm run deploy + `, + }, + { + description: + "Should autocomplete a Rust function implementation inside a struct", + filename: "main.rs", + input: ` +struct Calculator { + result: f64, +} + +impl Calculator { + fn new() -> Self { + Calculator { result: 0.0 } + } + + fn add(&mut self, number: f64) { + self.result += number; + } + + fn subtract(&mut self, number: f64) { + self.result -= number; + } + + fn multiply(&mut self, number: f64) { + self.result *= number; + } + + fn divide(&mut self, number: f64) { + if number != 0.0 { + self.result /= number; + } else { + println!("Cannot divide by zero."); + } + } + + fn reset(&mut self) { + self.result = 0.0; + } + + fn get_result(&self) -> f64 { + self.result + } + + fn<|fim|> +} +`, + llmOutput: ` divide(&mut self, number: f64) { + if number != 0.0 { + self.result /= number; + } else { + println!("Cannot divide by zero."); + } +}`, + expectedCompletion: ` divide(&mut self, number: f64) { + if number != 0.0 { + self.result /= number; + } else { + println!("Cannot divide by zero."); + } +}`, + }, + { + description: "Should autocomplete Rust match arms", + filename: "main.rs", + input: ` +fn get_status_code_description(code: u16) -> &'static str { + match code { + 200 => "OK", + 404 => "Not Found", + 500 => "Internal Server Error", + <|fim|> + } +} +`, + llmOutput: `403 => "Forbidden", + 401 => "Unauthorized", + _ => "Unknown Status", +`, + expectedCompletion: `403 => "Forbidden", + 401 => "Unauthorized", + _ => "Unknown Status", +`, + }, + { + description: "Should autocomplete Rust struct definition", + filename: "main.rs", + input: ` +struct User { + id: u32, + username: String, + email: String, + is_active: bool, + <|fim|> +} + +impl User { + fn new(id: u32, username: String, email: String) -> Self { + User { + id, + username, + email, + is_active: true, + } + } +} +`, + llmOutput: `created_at: String, + updated_at: String,`, + expectedCompletion: `created_at: String, + updated_at: String,`, + }, + { + description: "Haskell: Nested pattern matching with let bindings", + filename: "NestedPattern.hs", + input: `module NestedPattern where + +data Tree a = Leaf a | Node (Tree a) (Tree a) + +sumTree :: Num a => Tree a -> a +sumTree (Leaf x) = x +sumTree (Node left right) = + let leftSum = <|fim|> + rightSum = sumTree right + in leftSum + rightSum`, + llmOutput: `sumTree left`, + expectedCompletion: `sumTree left`, + }, + { + description: "Haskell: Complex function with where clause and guards", + filename: "QuadraticSolver.hs", + input: `module QuadraticSolver where + +solveQuadratic :: (Ord a, Floating a) => a -> a -> a -> Maybe (a, a) +solveQuadratic a b c + | discriminant < 0 = Nothing + | otherwise = Just (x1, x2) + where + discriminant = b^2 - 4*a*c + sqrtD = sqrt discriminant + x1 = (-b + sqrtD) / (2*a) + <|fim|> = (-b - sqrtD) / (2*a)`, + llmOutput: `x2`, + expectedCompletion: `x2`, + }, + { + description: "Haskell: List comprehension with complex filter", + filename: "PrimeNumbers.hs", + input: `module PrimeNumbers where + +primesUpTo :: Int -> [Int] +primesUpTo n = [x | x <- [2..n], isPrime x] + where isPrime num = <|fim|> && all (\d -> num \`mod\` d /= 0) [2..(floor . sqrt $ fromIntegral num)]`, + llmOutput: `num > 1`, + expectedCompletion: `num > 1`, + }, + { + description: "Should autocomplete Dart class methods", + filename: "calculator.dart", + input: ` +class Calculator { + double result = 0.0; + + void add(double number) { + result += number; + } + + void multiply(double number) { + result *= number; + } + + <|fim|> + + double getResult() { + return result; + } +}`, + llmOutput: `void subtract(double number) { + result -= number; + }`, + expectedCompletion: `void subtract(double number) { + result -= number; + }`, + }, + { + description: "Should handle string interpolation in Dart", + filename: "greetings.dart", + input: ` +void main() { + var name = "World"; + print('Hello, <|fim|>!'); +}`, + llmOutput: `\${name}`, + expectedCompletion: `\${name}`, + }, + { + description: "Should autocomplete within a Dart function body", + filename: "counter.dart", + input: ` +class Counter { + int count = 0; + + void increment() { + count++; + } + + void decrement() { + <|fim|> + + void reset() { + count = 0; + } +}`, + llmOutput: `count--;`, + expectedCompletion: `count--;`, + }, + { + description: + "Should autocomplete Clojure function definition with missing closing parenthesis", + input: `(defn calculate-sum [a b] + (let [sum (+ a b)] + (println "The sum is" sum) + sum<|fim|>`, + llmOutput: `))`, + expectedCompletion: `))`, + filename: "test.clj", + }, + { + description: + "Should autocomplete missing part of a Clojure map within a function", + input: `(defn get-user [] + {:username "johndoe" + :email "johndoe@example.com" + :age 30 + <|fim|> + (println "User information loaded"))`, + llmOutput: `:location "Unknown"}`, + expectedCompletion: `:location "Unknown"}`, + filename: "test.clj", + }, + { + description: + "Should autocomplete inside a Clojure vector within a looping construct", + input: `(defn odd-numbers [] + (loop [nums [1 3 5<|fim|> 9 11]] + (when (seq nums) + (println (first nums)) + (recur (rest nums)))))`, + llmOutput: ` 7,`, + expectedCompletion: ` 7,`, + filename: "test.clj", + }, + { + description: "Should autocomplete R function definition", + filename: "calculate.R", + input: ` +calculate_mean <- function(numbers) { + total <- sum(numbers) + <|fim|> +}`, + llmOutput: `mean_value <- total / length(numbers) + return(mean_value)`, + expectedCompletion: `mean_value <- total / length(numbers) + return(mean_value)`, + }, + { + description: "Should complete R loop and print statement", + filename: "loopPrint.R", + input: ` +numbers <- c(1, 2, 3, 4, 5) +for (number in numbers) { + print(<|fim|>) +}`, + llmOutput: `number)`, + expectedCompletion: `number)`, + }, + { + description: "Should autocomplete R data frame creation", + filename: "dataFrame.R", + input: ` +data <- data.frame( + Name = c("Alice", "Bob", "Charlie"), + Age = c(25, 30, 35), + <|fim|> +)`, + llmOutput: `Height = c(165, 180, 175)`, + expectedCompletion: `Height = c(165, 180, 175)`, + }, + { + description: "Should autocomplete R if-else statement", + filename: "condition.R", + input: ` +grade <- 85 +if (grade >= 90) { + print("A") +} else if (grade >= 80) { + <|fim|> +} else { + print("C") +}`, + llmOutput: `print("B")`, + expectedCompletion: `print("B")`, + }, + { + description: "Should autocomplete R ggplot2 plot structure", + filename: "plot.R", + input: ` +library(ggplot2) + +ggplot(data=mtcars, aes(x=wt, y=mpg)) + + geom_point() + + <|fim|>`, + llmOutput: `geom_smooth(method='lm', se=FALSE)`, + expectedCompletion: `geom_smooth(method='lm', se=FALSE)`, + }, + { + description: "Should autocomplete Scala class with a method", + filename: "Person.scala", + input: `class Person(val name: String, val age: Int) { + def greet(): String = { + <|fim|> + } + }`, + llmOutput: `s"Hello, my name is $name and I am $age years old."`, + expectedCompletion: `s"Hello, my name is $name and I am $age years old."`, + }, + + { + description: "Should handle Scala case class with a missing field", + filename: "Person.scala", + input: `case class Address(city: String, postalCode: String) + case class Person(name: String, age: Int, address: Address) + + val alice = Person("Alice", 30, Address("Wonderland", <|fim|>))`, + llmOutput: `"12345")`, + expectedCompletion: `"12345")`, + }, + + { + description: "Should autocomplete Scala function with missing body bracket", + filename: "Math.scala", + input: `object MathUtils { + def add(a: Int, b: Int): Int = { + a + b<|fim|> + + def multiply(a: Int, b: Int): Int = { + a * b + } + } + + object Main extends App { + println(MathUtils.add(3, 5)) + println(MathUtils.multiply(4, 6)) + }`, + llmOutput: ` + }`, + expectedCompletion: ` + }`, + }, + { + description: "Should autocomplete C function definition", + filename: "math_utils.c", + input: `#include + +int add(int a, int b) { + return a + b; +} + +int multiply(int a, int b) { + return a * b; +} + +int subtract(int a, int b) { + <|fim|> +} + +int main() { + printf("Result: %d", add(2, 3)); + return 0; +}`, + llmOutput: `return a - b;`, + expectedCompletion: `return a - b;`, + }, + + { + description: "Should handle C struct with missing field initialization", + filename: "person.c", + input: `#include + +typedef struct { + char name[50]; + int age; + float height; +} Person; + +int main() { + Person alice = {"Alice", 30, <|fim|>}; + printf("Name: %s, Age: %d, Height: %.2f", alice.name, alice.age, alice.height); + return 0; +}`, + llmOutput: `5.5`, + expectedCompletion: `5.5`, + }, + + { + description: "Should autocomplete C function with missing body bracket", + filename: "area.c", + input: `#include + +double calculateCircleArea(double radius) { + const double pi = 3.14159; + return pi * radius * radius;<|fim|> + +double calculateRectangleArea(double length, double width) { + return length * width; +} + +int main() { + printf("Circle Area: %.2f", calculateCircleArea(5.0)); + printf("Rectangle Area: %.2f", calculateRectangleArea(4.0, 6.0)); + return 0; +}`, + llmOutput: ` +}`, + expectedCompletion: ` +}`, + }, + { + description: "Should autocomplete a simple Kotlin function declaration", + filename: "simpleFunction.kt", + input: ` +fun main() { + println("Hello, World!") +} + +fun calculateArea(length: Double, width: Double): Double <|fim|>`, + llmOutput: `{ + return length * width +}`, + expectedCompletion: `{ + return length * width +}`, + }, + { + description: "Should handle autocomplete inside a Kotlin data class", + filename: "dataClass.kt", + input: ` +data class User( + val id: Int, + val name: String, + val email: String, + <|fim|> +)`, + llmOutput: `val age: Int`, + expectedCompletion: `val age: Int`, + }, + { + description: + "Should complete Kotlin if-else structure with missing brackets", + filename: "controlStructure.kt", + input: ` +fun getMax(a: Int, b: Int): Int { + if (a > b<|fim|> + } else { + return b + } +}`, + llmOutput: `) { + return a`, + expectedCompletion: `) { + return a`, + }, + { + description: "Should autocomplete Solidity function definition", + filename: "SimpleStorage.sol", + input: ` +pragma solidity ^0.8.0; + +contract SimpleStorage { + uint private data; + + function set(uint x) public { + data = x; + } + + function get() public view returns (uint) { + <|fim|> + } +} + `, + llmOutput: `return data;`, + expectedCompletion: `return data;`, + }, + + { + description: "Should autocomplete Solidity event with parameters", + filename: "EventExample.sol", + input: ` +pragma solidity ^0.8.0; + +contract EventExample { + event DataStored(uint indexed id, string content); + + function storeData(uint id, string memory content) public { + emit DataStored(<|fim|>); + } +} + `, + llmOutput: `id, content`, + expectedCompletion: `id, content`, + }, + + { + description: "Should handle Solidity struct definition completion", + filename: "StructDefinition.sol", + input: ` +pragma solidity ^0.8.0; + +contract StructExample { + struct Person { + string name; + uint age; + address wallet; + } + + Person[] private people; + + function addPerson(string memory name, uint age, address wallet) public { + people.push(Person(name, age, wallet)); + } + + function getFirstPerson<|fim|> +} + `, + llmOutput: `() public view returns (string memory, uint, address) { + if (people.length > 0) { + Person storage person = people[0]; + return (person.name, person.age, person.wallet); + } + return ("", 0, address(0)); + }`, + expectedCompletion: `() public view returns (string memory, uint, address) { + if (people.length > 0) { + Person storage person = people[0]; + return (person.name, person.age, person.wallet); + } + return ("", 0, address(0)); + }`, + }, + { + description: "Should autocomplete TypeScript interface properties", + filename: "User.ts", + input: ` +interface User { + id: number; + name: string; + e<|fim|> +} +`, + llmOutput: `mail: string; + age: number; +}`, + expectedCompletion: `mail: string; + age: number; +}`, + }, + + { + description: + "Should autocomplete a TypeScript arrow function inside a variable assignment", + filename: "mathOperations.ts", + input: ` +const addNumbers = (a: number, b: number): number => { + return a + b; +}; + +const multiplyNumbers = (a: number, b: number): number => { + re<|fim|> +} + +console.log(multiplyNumbers(2, 3)); +`, + llmOutput: `turn a * b;`, + expectedCompletion: `turn a * b;`, + }, + + { + description: + "Should handle autocomplete inside a nested TypeScript class method", + filename: "Account.ts", + input: ` +class Account { + private balance: number = 0; + + deposit(amount: number) { + this.balance += amount; + return this.balance; + } + + withdraw(amount: number) { + if (amount > this.balance) { + throw new Error("Insufficient funds"); + } + this.balance -= amount; + return thi<|fim|> + } +} +`, + llmOutput: `s.balance;`, + expectedCompletion: `s.balance;`, + }, + + { + description: "Should autocomplete a TypeScript generic function", + filename: "GenericFunction.ts", + input: ` +function identity(arg: T): T { + return ar<|fim|> +} + +console.log(identity(5)); +`, + llmOutput: `g;`, + expectedCompletion: `g;`, + }, + + { + description: + "Should autocomplete a TypeScript promise within an asynchronous function", + filename: "asyncFunction.ts", + input: ` +async function fetchData(url: string): Promise { + const response = await fetch(url); + <|fim|> + return data; +} + +fetchData('https://api.example.com/data'); +`, + llmOutput: `const data = await response.json();`, + expectedCompletion: `const data = await response.json();`, + }, + + { + description: + "Should autocomplete a C# class with a constructor and property", + filename: "Person.cs", + input: `using System; + +public class Person +{ + public string Name { get; set; } + public int Age { get; set; } + + public Person(string name, int <|fim|> +}`, + llmOutput: `age) + { + Name = name; + Age = age; + }`, + expectedCompletion: `age) + { + Name = name; + Age = age; + }`, + }, + { + description: "Should autocomplete a C# interface method", + filename: "IGreetable.cs", + input: `public interface IGreetable +{ + void <|fim|> +}`, + llmOutput: `Greet();`, + expectedCompletion: `Greet();`, + }, + { + description: "Should autocomplete inside C# method with if condition", + filename: "Calculator.cs", + input: `using System; + +public class Calculator +{ + public int Add(int a, int b) + { + if(<|fim|>) + { + return a + b; + } + return 0; + } +}`, + llmOutput: `a > 0 && b > 0`, + expectedCompletion: `a > 0 && b > 0`, + }, + { + description: "Should complete a simple Julia function", + filename: "simpleFunction.jl", + input: `function calculate_area(length, width) + <|fim|> +end +`, + llmOutput: `return length * width`, + expectedCompletion: `return length * width`, + }, + { + description: "Should autocomplete Julia for loop", + filename: "loop.jl", + input: `numbers = [1, 2, 3, 4, 5] +squared_numbers = [] + +for num in numbers + <|fim|> +end + +println(squared_numbers) +`, + llmOutput: `push!(squared_numbers, num^2)`, + expectedCompletion: `push!(squared_numbers, num^2)`, + }, + { + description: "Should complete a Julia struct definition", + filename: "structDefinition.jl", + input: `struct Person + first_name::String + last_name::String + age::Int + address::Address +end + +struct Address + street::String + city::String + <|fim|> +end +`, + llmOutput: `state::String + zip_code::String`, + expectedCompletion: `state::String + zip_code::String`, + }, + { + description: "Should complete a Julia dictionary access", + filename: "dictionary.jl", + input: `grades = Dict("Alice" => 90, "Bob" => 85, "Eve" => 88) + +function get_grade(student_name) + return grades[<|fim|>] +end + +println(get_grade("Alice")) # Should print 90 +`, + llmOutput: `student_name`, + expectedCompletion: `student_name`, + }, + { + description: "Should complete a Julia module declaration", + filename: "moduleDeclaration.jl", + input: `module MathOperations + +export add, subtract + +function add(a, b) + return a + b +end + +function subtract(a, b) + return a - b +end + +<|fim|> +`, + llmOutput: `end`, + expectedCompletion: `end`, + }, + { + description: "Should complete F# let-binding with function definition", + filename: "mathModule.fs", + input: `module MathModule + +let calculateArea length width = + <|fim|>`, + llmOutput: `length * width`, + expectedCompletion: `length * width`, + }, + + { + description: "Should complete incomplete F# type definition", + filename: "personType.fs", + input: `type Person = { + FirstName: string + LastName: string + Age: int<|fim|> +} + +let john = { FirstName = "John"; LastName = "Doe"; Age = 30 }`, + llmOutput: ` + Address: string +}`, + expectedCompletion: ` + Address: string +}`, + }, + + { + description: "Should complete F# pattern matching expression", + filename: "patternMatching.fs", + input: `let describeNumber number = + match number with + | 0 -> "Zero" + | 1 -> "One" + | <|fim|>`, + llmOutput: `2 -> "Two" + | _ -> "Other"`, + expectedCompletion: `2 -> "Two" + | _ -> "Other"`, + }, + + { + description: "Should complete F# list comprehension expression", + filename: "listComprehension.fs", + input: `let squares = [ for x in 1..10 -> x * x ] +let evenSquares = [ for x in squares do if x % 2 = 0 then yield x ] +let oddSquares = [<|fim|>]`, + llmOutput: ` for x in squares do if x % 2 <> 0 then yield x ]`, + expectedCompletion: ` for x in squares do if x % 2 <> 0 then yield x ]`, + }, + + { + description: "Should complete an F# recursive function", + filename: "recursiveFunctions.fs", + input: `let rec factorial n = + if n <= 1 then 1 + else n <|fim|> factorial (n - 1)`, + llmOutput: ` * `, + expectedCompletion: ` * `, + }, + + { + description: "Should complete F# member method inside a class type", + filename: "bankAccount.fs", + input: `type BankAccount(owner: string, initialBalance: float) = + let mutable balance = initialBalance + + member this.Deposit amount = + balance <- balance + amount + this + <|fim|>`, + llmOutput: ` + member this.Withdraw amount = + if amount > balance then + failwith "Insufficient funds" + balance <- balance - amount + this`, + expectedCompletion: ` + member this.Withdraw amount = + if amount > balance then + failwith "Insufficient funds" + balance <- balance - amount + this`, + }, + + { + description: "Should complete F# async workflow function", + filename: "asyncWorkflow.fs", + input: `let fetchDataAsync url = + async { + use client = new System.Net.Http.HttpClient() + <|fim|> + }`, + llmOutput: `let! response = client.GetStringAsync(url) + return response`, + expectedCompletion: `let! response = client.GetStringAsync(url) + return response`, + }, + { + description: "Should autocomplete SCSS nested class starting inside a rule", + filename: "styles.scss", + input: `nav { + display: flex; + justify-content: space-between; + .logo { + font-size: 1.5rem; + color: #333; + + .brand<|fim|> + } + + ul { + list-style: none; + display: flex; + gap: 1rem; + } +}`, + llmOutput: `-name { + font-weight: bold; + text-transform: uppercase; +}`, + expectedCompletion: `-name { + font-weight: bold; + text-transform: uppercase; +}`, + }, + + { + description: "Should handle SCSS mixin within a class", + filename: "styles.scss", + input: `.card { + border: 1px solid #ccc; + padding: 10px; + + @include<|fim|> + + &:hover { + box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); + } +}`, + llmOutput: ` transition(all 0.3s ease);`, + expectedCompletion: ` transition(all 0.3s ease);`, + }, + + { + description: + "Should autocomplete SCSS variable in the middle of a statement", + filename: "styles.scss", + input: `$primary-color: #007bff; +$secondary-color: #6c757d; + +.button { + background-color: <|fim|> color; + padding: 10px 15px; + border: none; + color: #fff; + border-radius: 4px; +}`, + llmOutput: `$primary-`, + expectedCompletion: `$primary-`, + }, + { + description: "Should autocomplete Vue component method", + filename: "MyComponent.vue", + input: ` + + +`, + llmOutput: `() { + this.count = 0; + }`, + expectedCompletion: `() { + this.count = 0; + }`, + }, + { + description: "Should autocomplete Vue computed property", + filename: "UserComponent.vue", + input: ` + + +`, + llmOutput: `() { + return this.firstName + ' ' + this.lastName; + }`, + expectedCompletion: `() { + return this.firstName + ' ' + this.lastName; + }`, + }, + { + description: "Should autocomplete Vue method using props", + filename: "TodoItem.vue", + input: ` + + +`, + llmOutput: `this.completed`, + expectedCompletion: `this.completed`, + }, + { + description: "Should autocomplete Svelte reactive statement", + filename: "Counter.svelte", + input: ` + + + +`, + llmOutput: `doubledCount = count * 2`, + expectedCompletion: `doubledCount = count * 2`, + }, + + { + description: "Should autocomplete Svelte component inside HTML", + filename: "NestedComponent.svelte", + input: ` + + +
+

Hello Svelte

+ /> +
+`, + llmOutput: `name="World"`, + expectedCompletion: `name="World"`, + }, + + { + description: "Should handle autocomplete in Svelte each block", + filename: "List.svelte", + input: ` + + +
    + {#each items as item} +
  • {item}
  • + {/each<|fim|> +
+`, + llmOutput: `}`, + expectedCompletion: `}`, + }, +]; diff --git a/core/autocomplete/filtering/test/util.ts b/core/autocomplete/filtering/test/util.ts new file mode 100644 index 000000000..9dbf9b6aa --- /dev/null +++ b/core/autocomplete/filtering/test/util.ts @@ -0,0 +1,77 @@ +import fs from "node:fs"; +import path from "node:path"; +import Mock from "../../../llm/llms/Mock"; +import { testConfigHandler, testIde } from "../../../test/util/fixtures"; +import { + AutocompleteInput, + CompletionProvider, +} from "../../CompletionProvider"; + +const FIM_DELIMITER = "<|fim|>"; + +function parseFimExample(text: string): { prefix: string; suffix: string } { + const [prefix, suffix] = text.split(FIM_DELIMITER); + return { prefix, suffix }; +} + +export interface AutocompleteFileringTestInput { + description: string; + filename: string; + input: string; + llmOutput: string; + expectedCompletion: string | null; + options?: { + only?: boolean; + }; +} + +export async function testAutocompleteFiltering( + test: AutocompleteFileringTestInput, +) { + const { prefix, suffix } = parseFimExample(test.input); + + // Setup necessary objects + const llm = new Mock({ + model: "mock", + }); + llm.completion = test.llmOutput; + const ide = testIde; + const configHandler = testConfigHandler; + + // Create a real file + const [workspaceDir] = await ide.getWorkspaceDirs(); + const filepath = path.join(workspaceDir, test.filename); + fs.writeFileSync(filepath, test.input.replace(FIM_DELIMITER, "")); + + // Prepare completion input and provider + const completionProvider = new CompletionProvider( + configHandler, + ide, + async () => llm, + () => {}, + async () => [], + ); + + const line = prefix.split("\n").length - 1; + const character = prefix.split("\n")[line].length; + const autocompleteInput: AutocompleteInput = { + clipboardText: "", + completionId: "test-completion-id", + filepath, + pos: { + line, + character, + }, + recentlyEditedFiles: [], + recentlyEditedRanges: [], + }; + + // Generate a completion + const result = await completionProvider.provideInlineCompletionItems( + autocompleteInput, + undefined, + ); + + // Ensure that we return the text that is wanted to be displayed + expect(result?.completion).toEqual(test.expectedCompletion); +} diff --git a/core/autocomplete/util.ts b/core/autocomplete/generation/GeneratorReuseManager.ts similarity index 52% rename from core/autocomplete/util.ts rename to core/autocomplete/generation/GeneratorReuseManager.ts index d07658d17..7a67e686f 100644 --- a/core/autocomplete/util.ts +++ b/core/autocomplete/generation/GeneratorReuseManager.ts @@ -1,78 +1,4 @@ -export class ListenableGenerator { - private _source: AsyncGenerator; - private _buffer: T[] = []; - private _listeners: Set<(value: T) => void> = new Set(); - private _isEnded = false; - - constructor( - source: AsyncGenerator, - private readonly onError: (e: any) => void, - ) { - this._source = source; - this._start(); - } - - public cancel() { - this._isEnded = true; - } - - private async _start() { - try { - for await (const value of this._source) { - if (this._isEnded) { - break; - } - this._buffer.push(value); - for (const listener of this._listeners) { - listener(value); - } - } - } catch (e) { - this.onError(e); - } finally { - this._isEnded = true; - for (const listener of this._listeners) { - listener(null as any); - } - } - } - - listen(listener: (value: T) => void) { - this._listeners.add(listener); - for (const value of this._buffer) { - listener(value); - } - if (this._isEnded) { - listener(null as any); - } - } - - async *tee(): AsyncGenerator { - try { - let i = 0; - while (i < this._buffer.length) { - yield this._buffer[i++]; - } - while (!this._isEnded) { - let resolve: (value: any) => void; - const promise = new Promise((res) => { - resolve = res; - this._listeners.add(resolve!); - }); - await promise; - this._listeners.delete(resolve!); - - // Possible timing caused something to slip in between - // timers so we iterate over the buffer - while (i < this._buffer.length) { - yield this._buffer[i++]; - } - } - } finally { - // this._listeners.delete(resolve!); - } - } -} +import { ListenableGenerator } from "./ListenableGenerator"; export class GeneratorReuseManager { currentGenerator: ListenableGenerator | undefined; diff --git a/core/autocomplete/generation/ListenableGenerator.ts b/core/autocomplete/generation/ListenableGenerator.ts new file mode 100644 index 000000000..0cc9f664e --- /dev/null +++ b/core/autocomplete/generation/ListenableGenerator.ts @@ -0,0 +1,75 @@ +export class ListenableGenerator { + private _source: AsyncGenerator; + private _buffer: T[] = []; + private _listeners: Set<(value: T) => void> = new Set(); + private _isEnded = false; + + constructor( + source: AsyncGenerator, + private readonly onError: (e: any) => void, + ) { + this._source = source; + this._start(); + } + + public cancel() { + this._isEnded = true; + } + + private async _start() { + try { + for await (const value of this._source) { + if (this._isEnded) { + break; + } + this._buffer.push(value); + for (const listener of this._listeners) { + listener(value); + } + } + } catch (e) { + this.onError(e); + } finally { + this._isEnded = true; + for (const listener of this._listeners) { + listener(null as any); + } + } + } + + listen(listener: (value: T) => void) { + this._listeners.add(listener); + for (const value of this._buffer) { + listener(value); + } + if (this._isEnded) { + listener(null as any); + } + } + + async *tee(): AsyncGenerator { + try { + let i = 0; + while (i < this._buffer.length) { + yield this._buffer[i++]; + } + while (!this._isEnded) { + let resolve: (value: any) => void; + const promise = new Promise((res) => { + resolve = res; + this._listeners.add(resolve!); + }); + await promise; + this._listeners.delete(resolve!); + + // Possible timing caused something to slip in between + // timers so we iterate over the buffer + while (i < this._buffer.length) { + yield this._buffer[i++]; + } + } + } finally { + // this._listeners.delete(resolve!); + } + } +} diff --git a/core/autocomplete/postprocessing.ts b/core/autocomplete/postprocessing/index.ts similarity index 93% rename from core/autocomplete/postprocessing.ts rename to core/autocomplete/postprocessing/index.ts index cb3ada459..af0c698e0 100644 --- a/core/autocomplete/postprocessing.ts +++ b/core/autocomplete/postprocessing/index.ts @@ -1,6 +1,6 @@ -import type { ILLM } from "../index.js"; -import { longestCommonSubsequence } from "../util/lcs.js"; -import { lineIsRepeated } from "./streamTransforms/lineStream.js"; +import type { ILLM } from "../../index.js"; +import { longestCommonSubsequence } from "../../util/lcs.js"; +import { lineIsRepeated } from "../filtering/streamTransforms/lineStream.js"; function rewritesLineAbove(completion: string, prefix: string): boolean { const lineAbove = prefix diff --git a/core/autocomplete/types.ts b/core/autocomplete/types.ts new file mode 100644 index 000000000..745ea563b --- /dev/null +++ b/core/autocomplete/types.ts @@ -0,0 +1,38 @@ +import { Position, Range, TabAutocompleteOptions } from ".."; +import { RangeInFileWithContents } from "../commands/util"; +import { RecentlyEditedRange } from "./recentlyEdited"; + +export interface AutocompleteInput { + completionId: string; + filepath: string; + pos: Position; + recentlyEditedFiles: RangeInFileWithContents[]; + recentlyEditedRanges: RecentlyEditedRange[]; + clipboardText: string; + // Used for notebook files + manuallyPassFileContents?: string; + // Used for VS Code git commit input box + manuallyPassPrefix?: string; + selectedCompletionInfo?: { + text: string; + range: Range; + }; + injectDetails?: string; +} + +export interface AutocompleteOutcome extends TabAutocompleteOptions { + accepted?: boolean; + time: number; + prefix: string; + suffix: string; + prompt: string; + completion: string; + modelProvider: string; + modelName: string; + completionOptions: any; + cacheHit: boolean; + filepath: string; + gitRepo?: string; + completionId: string; + uniqueId: string; +} diff --git a/core/autocomplete/ast.ts b/core/autocomplete/util/ast.ts similarity index 94% rename from core/autocomplete/ast.ts rename to core/autocomplete/util/ast.ts index 139b22dbf..600b84126 100644 --- a/core/autocomplete/ast.ts +++ b/core/autocomplete/util/ast.ts @@ -1,6 +1,6 @@ import Parser from "web-tree-sitter"; -import { RangeInFileWithContents } from "../commands/util.js"; -import { getParserForFile } from "../util/treeSitter.js"; +import { RangeInFileWithContents } from "../../commands/util.js"; +import { getParserForFile } from "../../util/treeSitter.js"; export type AstPath = Parser.SyntaxNode[]; diff --git a/core/core.ts b/core/core.ts index 8ce7c7a5d..d7bd1846f 100644 --- a/core/core.ts +++ b/core/core.ts @@ -1,6 +1,6 @@ import { v4 as uuidv4 } from "uuid"; import type { ContextItemId, IDE, IndexingProgressUpdate } from "."; -import { CompletionProvider } from "./autocomplete/completionProvider"; +import { CompletionProvider } from "./autocomplete/CompletionProvider"; import { ConfigHandler } from "./config/ConfigHandler"; import { setupBestConfig, diff --git a/core/edit/lazy/deterministic.ts b/core/edit/lazy/deterministic.ts index e9cbdf921..bb938b050 100644 --- a/core/edit/lazy/deterministic.ts +++ b/core/edit/lazy/deterministic.ts @@ -2,7 +2,7 @@ import { distance } from "fastest-levenshtein"; import path from "path"; import Parser from "web-tree-sitter"; import { DiffLine } from "../.."; -import { LANGUAGES } from "../../autocomplete/languages"; +import { LANGUAGES } from "../../autocomplete/constants/AutocompleteLanguageInfo"; import { myersDiff } from "../../diff/myers"; import { getParserForFile } from "../../util/treeSitter"; import { findInAst } from "./findInAst"; diff --git a/core/protocol/core.ts b/core/protocol/core.ts index e2d512950..d82454184 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -15,7 +15,7 @@ import type { SessionInfo, SiteIndexingConfig, } from "../"; -import type { AutocompleteInput } from "../autocomplete/completionProvider"; +import type { AutocompleteInput } from "../autocomplete/CompletionProvider"; import { ProfileDescription } from "../config/ConfigHandler"; export type ProtocolGeneratorType = AsyncGenerator<{ From e6d431d1c5032bba1154824b92e52b001cbc83f3 Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 30 Oct 2024 01:00:07 -0700 Subject: [PATCH 09/96] autoformat --- core/autocomplete/context/ranking/slidingWindow.ts | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/core/autocomplete/context/ranking/slidingWindow.ts b/core/autocomplete/context/ranking/slidingWindow.ts index 37d1a7d9e..54ec763f2 100644 --- a/core/autocomplete/context/ranking/slidingWindow.ts +++ b/core/autocomplete/context/ranking/slidingWindow.ts @@ -1,8 +1,5 @@ -import { RangeInFileWithContents } from "../commands/util.js"; -import { - AutocompleteSnippet, - jaccardSimilarity, -} from "./context/ranking/index.js"; +import { RangeInFileWithContents } from "../../../commands/util.js"; +import { AutocompleteSnippet, jaccardSimilarity } from "./index.js"; function* slidingWindow( content: string, From 4e57b761398b555e601ec015a611ec232f272817 Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 30 Oct 2024 01:05:51 -0700 Subject: [PATCH 10/96] fix tsc errs --- core/autocomplete/completionProvider.ts | 6 +++++- core/autocomplete/context/retrieval.ts | 4 ++-- .../filtering/streamTransforms/charStream.test.ts | 2 +- .../filtering/streamTransforms/lineStream.test.ts | 2 +- .../filtering/streamTransforms/lineStream.ts | 4 ++-- core/autocomplete/filtering/test/util.ts | 6 ++---- core/commands/slash/edit.ts | 2 +- core/core.ts | 2 +- core/edit/lazy/replace.ts | 2 +- core/edit/lazy/streamLazyApply.ts | 4 ++-- core/edit/streamDiffLines.ts | 9 ++------- core/llm/llms/Mock.ts | 6 +++--- core/protocol/core.ts | 2 +- 13 files changed, 24 insertions(+), 27 deletions(-) diff --git a/core/autocomplete/completionProvider.ts b/core/autocomplete/completionProvider.ts index 8458e1281..bc910161a 100644 --- a/core/autocomplete/completionProvider.ts +++ b/core/autocomplete/completionProvider.ts @@ -32,7 +32,11 @@ import { getConfigJsonPath } from "../util/paths.js"; import AutocompleteLruCache from "./AutocompleteLruCache.js"; import { ImportDefinitionsService } from "./context/ImportDefinitionsService.js"; import { BracketMatchingService } from "./filtering/BracketMatchingService.js"; -import { stopAtStopTokens } from "./filtering/streamTransforms/charStream.js"; +import { + noFirstCharNewline, + onlyWhitespaceAfterEndOfLine, + stopAtStopTokens, +} from "./filtering/streamTransforms/charStream.js"; import { avoidPathLineAndEmptyComments, noTopLevelKeywordsMidline, diff --git a/core/autocomplete/context/retrieval.ts b/core/autocomplete/context/retrieval.ts index 422b377bd..45d6f2b64 100644 --- a/core/autocomplete/context/retrieval.ts +++ b/core/autocomplete/context/retrieval.ts @@ -1,5 +1,5 @@ -import { BranchAndDir, Chunk } from "../index.js"; -import { FullTextSearchCodebaseIndex } from "../indexing/FullTextSearchCodebaseIndex.js"; +import { BranchAndDir, Chunk } from "../.."; +import { FullTextSearchCodebaseIndex } from "../../indexing/FullTextSearchCodebaseIndex"; export async function fullTextRetrieve( prefix: string, diff --git a/core/autocomplete/filtering/streamTransforms/charStream.test.ts b/core/autocomplete/filtering/streamTransforms/charStream.test.ts index b5504ad63..7ab8923fc 100644 --- a/core/autocomplete/filtering/streamTransforms/charStream.test.ts +++ b/core/autocomplete/filtering/streamTransforms/charStream.test.ts @@ -1,4 +1,4 @@ -import { stopAtStopTokens } from "./streamTransforms/charStream"; +import { stopAtStopTokens } from "./charStream"; describe("stopAtStopTokens", () => { async function* createMockStream(chunks: string[]): AsyncGenerator { diff --git a/core/autocomplete/filtering/streamTransforms/lineStream.test.ts b/core/autocomplete/filtering/streamTransforms/lineStream.test.ts index ace94eaa4..df8cd1263 100644 --- a/core/autocomplete/filtering/streamTransforms/lineStream.test.ts +++ b/core/autocomplete/filtering/streamTransforms/lineStream.test.ts @@ -1,5 +1,5 @@ import { jest } from "@jest/globals"; -import * as lineStream from "./streamTransforms/lineStream"; +import * as lineStream from "./lineStream"; describe("lineStream", () => { let mockFullStop: jest.Mock; diff --git a/core/autocomplete/filtering/streamTransforms/lineStream.ts b/core/autocomplete/filtering/streamTransforms/lineStream.ts index 5990bbf3c..918acaf26 100644 --- a/core/autocomplete/filtering/streamTransforms/lineStream.ts +++ b/core/autocomplete/filtering/streamTransforms/lineStream.ts @@ -1,6 +1,6 @@ import { distance } from "fastest-levenshtein"; -import { DiffLine } from "../.."; -import { LineStream } from "../../diff/util"; +import { DiffLine } from "../../.."; +import { LineStream } from "../../../diff/util"; export type LineFilter = (args: { lines: LineStream; diff --git a/core/autocomplete/filtering/test/util.ts b/core/autocomplete/filtering/test/util.ts index 9dbf9b6aa..37890e1e8 100644 --- a/core/autocomplete/filtering/test/util.ts +++ b/core/autocomplete/filtering/test/util.ts @@ -2,10 +2,8 @@ import fs from "node:fs"; import path from "node:path"; import Mock from "../../../llm/llms/Mock"; import { testConfigHandler, testIde } from "../../../test/util/fixtures"; -import { - AutocompleteInput, - CompletionProvider, -} from "../../CompletionProvider"; +import { CompletionProvider } from "../../completionProvider"; +import { AutocompleteInput } from "../../types"; const FIM_DELIMITER = "<|fim|>"; diff --git a/core/commands/slash/edit.ts b/core/commands/slash/edit.ts index aafafa67e..fc71838df 100644 --- a/core/commands/slash/edit.ts +++ b/core/commands/slash/edit.ts @@ -6,7 +6,7 @@ import { fixCodeLlamaFirstLineIndentation, stopAtLines, streamWithNewLines, -} from "../../autocomplete/streamTransforms/lineStream"; +} from "../../autocomplete/filtering/streamTransforms/lineStream"; import { streamLines } from "../../diff/util"; import { stripImages } from "../../llm/images"; import { diff --git a/core/core.ts b/core/core.ts index d7bd1846f..8ce7c7a5d 100644 --- a/core/core.ts +++ b/core/core.ts @@ -1,6 +1,6 @@ import { v4 as uuidv4 } from "uuid"; import type { ContextItemId, IDE, IndexingProgressUpdate } from "."; -import { CompletionProvider } from "./autocomplete/CompletionProvider"; +import { CompletionProvider } from "./autocomplete/completionProvider"; import { ConfigHandler } from "./config/ConfigHandler"; import { setupBestConfig, diff --git a/core/edit/lazy/replace.ts b/core/edit/lazy/replace.ts index b4b6164cc..e6c3183f0 100644 --- a/core/edit/lazy/replace.ts +++ b/core/edit/lazy/replace.ts @@ -2,7 +2,7 @@ import { ILLM } from "../.."; import { filterLeadingNewline, stopAtLines, -} from "../../autocomplete/streamTransforms/lineStream"; +} from "../../autocomplete/filtering/streamTransforms/lineStream"; import { streamLines } from "../../diff/util"; import { dedent } from "../../util"; diff --git a/core/edit/lazy/streamLazyApply.ts b/core/edit/lazy/streamLazyApply.ts index dece697ca..f101c6981 100644 --- a/core/edit/lazy/streamLazyApply.ts +++ b/core/edit/lazy/streamLazyApply.ts @@ -2,7 +2,7 @@ import { filterLeadingAndTrailingNewLineInsertion, filterLeadingNewline, stopAtLines, -} from "../../autocomplete/streamTransforms/lineStream"; +} from "../../autocomplete/filtering/streamTransforms/lineStream.js"; import { streamDiff } from "../../diff/streamDiff.js"; import { LineStream, streamLines } from "../../diff/util.js"; import { DiffLine, ILLM } from "../../index.js"; @@ -43,7 +43,7 @@ export async function* streamLazyApply( let lazyCompletionLines = streamLines(lazyCompletion, true); // Process line output // lazyCompletionLines = filterEnglishLinesAtStart(lazyCompletionLines); - lazyCompletionLines = stopAtLines(lazyCompletionLines, () => { }, ["```"]); + lazyCompletionLines = stopAtLines(lazyCompletionLines, () => {}, ["```"]); lazyCompletionLines = filterLeadingNewline(lazyCompletionLines); // Fill in unchanged code diff --git a/core/edit/streamDiffLines.ts b/core/edit/streamDiffLines.ts index dbab5841c..f49f3f911 100644 --- a/core/edit/streamDiffLines.ts +++ b/core/edit/streamDiffLines.ts @@ -5,15 +5,10 @@ import { filterLeadingAndTrailingNewLineInsertion, skipLines, stopAtLines, -} from "../autocomplete/streamTransforms/lineStream.js"; +} from "../autocomplete/filtering/streamTransforms/lineStream.js"; import { streamDiff } from "../diff/streamDiff.js"; import { streamLines } from "../diff/util.js"; -import { - ChatMessage, - DiffLine, - ILLM, - LLMFullCompletionOptions, -} from "../index.js"; +import { ChatMessage, DiffLine, ILLM } from "../index.js"; import { gptEditPrompt } from "../llm/templates/edit.js"; import { Telemetry } from "../util/posthog.js"; diff --git a/core/llm/llms/Mock.ts b/core/llm/llms/Mock.ts index d5e2ef59c..d151ba3b2 100644 --- a/core/llm/llms/Mock.ts +++ b/core/llm/llms/Mock.ts @@ -2,14 +2,14 @@ import { ChatMessage, CompletionOptions, ModelProvider } from "../../index.js"; import { BaseLLM } from "../index.js"; class Mock extends BaseLLM { - static Completion = "Test Completion"; + completion = "Test Completion"; static providerName: ModelProvider = "mock"; protected async *_streamComplete( prompt: string, options: CompletionOptions, ): AsyncGenerator { - yield Mock.Completion; + yield this.completion; } protected async *_streamChat( @@ -18,7 +18,7 @@ class Mock extends BaseLLM { ): AsyncGenerator { yield { role: "assistant", - content: Mock.Completion, + content: this.completion, }; } } diff --git a/core/protocol/core.ts b/core/protocol/core.ts index d82454184..090ee2c5a 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -15,7 +15,7 @@ import type { SessionInfo, SiteIndexingConfig, } from "../"; -import type { AutocompleteInput } from "../autocomplete/CompletionProvider"; +import { AutocompleteInput } from "../autocomplete/types"; import { ProfileDescription } from "../config/ConfigHandler"; export type ProtocolGeneratorType = AsyncGenerator<{ From 911256bad10cab2824f5d3b491b09b30948b12d6 Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 30 Oct 2024 19:52:07 -0700 Subject: [PATCH 11/96] refactor debouncing --- core/autocomplete/AutocompleteDebouncer.ts | 32 ++++++ core/autocomplete/completionProvider.ts | 105 ++++++------------ core/autocomplete/context/retrieval.ts | 23 ---- core/autocomplete/filtering/filter.ts | 4 - core/autocomplete/postprocessing/index.ts | 6 +- .../AutocompleteTemplate.ts | 0 core/autocomplete/templating/index.ts | 19 ++++ 7 files changed, 89 insertions(+), 100 deletions(-) create mode 100644 core/autocomplete/AutocompleteDebouncer.ts delete mode 100644 core/autocomplete/context/retrieval.ts delete mode 100644 core/autocomplete/filtering/filter.ts rename core/autocomplete/{constants => templating}/AutocompleteTemplate.ts (100%) create mode 100644 core/autocomplete/templating/index.ts diff --git a/core/autocomplete/AutocompleteDebouncer.ts b/core/autocomplete/AutocompleteDebouncer.ts new file mode 100644 index 000000000..f8bcc474f --- /dev/null +++ b/core/autocomplete/AutocompleteDebouncer.ts @@ -0,0 +1,32 @@ +import { v4 as uuidv4 } from "uuid"; +export class AutocompleteDebouncer { + private debounceTimeout: NodeJS.Timeout | undefined = undefined; + private debouncing = false; + private lastUUID: string | undefined = undefined; + + async delayAndShouldDebounce(debounceDelay: number): Promise { + // Debounce + const uuid = uuidv4(); + this.lastUUID = uuid; + + // Debounce + if (this.debouncing) { + this.debounceTimeout?.refresh(); + const lastUUID = await new Promise((resolve) => + setTimeout(() => { + resolve(this.lastUUID); + }, debounceDelay), + ); + if (uuid !== lastUUID) { + return true; + } + } else { + this.debouncing = true; + this.debounceTimeout = setTimeout(async () => { + this.debouncing = false; + }, debounceDelay); + } + + return false; + } +} diff --git a/core/autocomplete/completionProvider.ts b/core/autocomplete/completionProvider.ts index 012b525ca..4f47579a4 100644 --- a/core/autocomplete/completionProvider.ts +++ b/core/autocomplete/completionProvider.ts @@ -1,7 +1,6 @@ import ignore from "ignore"; import OpenAI from "openai"; import path from "path"; -import { v4 as uuidv4 } from "uuid"; import { ConfigHandler } from "../config/ConfigHandler.js"; import { TRIAL_FIM_MODEL } from "../config/onboarding.js"; import { streamLines } from "../diff/util.js"; @@ -16,19 +15,19 @@ import { Telemetry } from "../util/posthog.js"; import { getRangeInString } from "../util/ranges.js"; import { AutocompleteLanguageInfo } from "./constants/AutocompleteLanguageInfo.js"; -import { getTemplateForModel } from "./constants/AutocompleteTemplate.js"; import { constructAutocompletePrompt, languageForFilepath, } from "./constructPrompt.js"; import { AutocompleteSnippet } from "./context/ranking/index.js"; import { RootPathContextService } from "./context/RootPathContextService.js"; -import { isOnlyWhitespace } from "./filtering/filter.js"; import { GeneratorReuseManager } from "./generation/GeneratorReuseManager.js"; import { postprocessCompletion } from "./postprocessing/index.js"; +import { getTemplateForModel } from "./templating/AutocompleteTemplate.js"; // @prettier-ignore import Handlebars from "handlebars"; import { getConfigJsonPath } from "../util/paths.js"; +import { AutocompleteDebouncer } from "./AutocompleteDebouncer.js"; import AutocompleteLruCache from "./AutocompleteLruCache.js"; import { ImportDefinitionsService } from "./context/ImportDefinitionsService.js"; import { BracketMatchingService } from "./filtering/BracketMatchingService.js"; @@ -41,6 +40,7 @@ import { stopAtSimilarLine, streamWithNewLines, } from "./filtering/streamTransforms/lineStream.js"; +import { formatExternalSnippet } from "./templating/index.js"; import { AutocompleteInput, AutocompleteOutcome } from "./types.js"; const autocompleteCache = AutocompleteLruCache.get(); @@ -60,23 +60,6 @@ const LOCAL_PROVIDERS: ModelProvider[] = [ "text-gen-webui", ]; -function formatExternalSnippet( - filepath: string, - snippet: string, - language: AutocompleteLanguageInfo, -) { - const comment = language.singleLineComment; - const lines = [ - `${comment} Path: ${getBasename(filepath)}`, - ...snippet - .trim() - .split("\n") - .map((line) => `${comment} ${line}`), - comment, - ]; - return lines.join("\n"); -} - export type GetLspDefinitionsFunction = ( filepath: string, contents: string, @@ -86,9 +69,14 @@ export type GetLspDefinitionsFunction = ( ) => Promise; export class CompletionProvider { - private static debounceTimeout: NodeJS.Timeout | undefined = undefined; - private static debouncing = false; - private static lastUUID: string | undefined = undefined; + private importDefinitionsService: ImportDefinitionsService; + private rootPathContextService: RootPathContextService; + private generatorReuseManager: GeneratorReuseManager; + private autocompleteCache = AutocompleteLruCache.get(); + public errorsShown: Set = new Set(); + private bracketMatchingService = new BracketMatchingService(); + private debouncer = new AutocompleteDebouncer(); + // private nearbyDefinitionsService = new NearbyDefinitionsService(); constructor( private readonly configHandler: ConfigHandler, @@ -107,14 +95,6 @@ export class CompletionProvider { ); } - private importDefinitionsService: ImportDefinitionsService; - private rootPathContextService: RootPathContextService; - private generatorReuseManager: GeneratorReuseManager; - private autocompleteCache = AutocompleteLruCache.get(); - public errorsShown: Set = new Set(); - private bracketMatchingService = new BracketMatchingService(); - // private nearbyDefinitionsService = new NearbyDefinitionsService(); - private onError(e: any) { console.warn("Error generating autocompletion: ", e); if ( @@ -150,19 +130,7 @@ export class CompletionProvider { if (this._outcomes.has(completionId)) { const outcome = this._outcomes.get(completionId)!; - outcome.accepted = true; - logDevData("autocomplete", outcome); - void Telemetry.capture( - "autocomplete", - { - accepted: outcome.accepted, - modelName: outcome.modelName, - modelProvider: outcome.modelProvider, - time: outcome.time, - cacheHit: outcome.cacheHit, - }, - true, - ); + this.logAcceptedCompletion(completionId, outcome); this._outcomes.delete(completionId); this.bracketMatchingService.handleAcceptedCompletion( @@ -172,6 +140,25 @@ export class CompletionProvider { } } + private logAcceptedCompletion( + completionId: string, + outcome: AutocompleteOutcome, + ) { + outcome.accepted = true; + logDevData("autocomplete", outcome); + void Telemetry.capture( + "autocomplete", + { + accepted: outcome.accepted, + modelName: outcome.modelName, + modelProvider: outcome.modelProvider, + time: outcome.time, + cacheHit: outcome.cacheHit, + }, + true, + ); + } + public cancelRejectionTimeout(completionId: string) { if (this._logRejectionTimeouts.has(completionId)) { clearTimeout(this._logRejectionTimeouts.get(completionId)!); @@ -188,10 +175,6 @@ export class CompletionProvider { token: AbortSignal | undefined, ): Promise { try { - // Debounce - const uuid = uuidv4(); - CompletionProvider.lastUUID = uuid; - const config = await this.configHandler.loadConfig(); const options = { ...DEFAULT_AUTOCOMPLETE_OPTS, @@ -244,21 +227,8 @@ export class CompletionProvider { } // Debounce - if (CompletionProvider.debouncing) { - CompletionProvider.debounceTimeout?.refresh(); - const lastUUID = await new Promise((resolve) => - setTimeout(() => { - resolve(CompletionProvider.lastUUID); - }, options.debounceDelay), - ); - if (uuid !== lastUUID) { - return undefined; - } - } else { - CompletionProvider.debouncing = true; - CompletionProvider.debounceTimeout = setTimeout(async () => { - CompletionProvider.debouncing = false; - }, options.debounceDelay); + if (await this.debouncer.delayAndShouldDebounce(options.debounceDelay)) { + return undefined; } // Get completion @@ -292,15 +262,6 @@ export class CompletionProvider { return undefined; } - /** - * This check is most likely not needed because we do trim the LLM output - * elsewhere in the code. That said, I'm not yet confident enough to - * remove this. - */ - if (options.transform && isOnlyWhitespace(outcome.completion)) { - return undefined; - } - // Do some stuff later so as not to block return. Latency matters const completionToCache = outcome.completion; setTimeout(async () => { diff --git a/core/autocomplete/context/retrieval.ts b/core/autocomplete/context/retrieval.ts deleted file mode 100644 index 45d6f2b64..000000000 --- a/core/autocomplete/context/retrieval.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { BranchAndDir, Chunk } from "../.."; -import { FullTextSearchCodebaseIndex } from "../../indexing/FullTextSearchCodebaseIndex"; - -export async function fullTextRetrieve( - prefix: string, - suffix: string, - indexTag: BranchAndDir, -): Promise { - const index = new FullTextSearchCodebaseIndex(); - const searchStrings = prefix.split("\n").slice(-3); - const results: Chunk[] = []; - searchStrings.forEach(async (searchString) => { - const chunks = await index.retrieve( - [indexTag], - searchString, - 3, - undefined, - undefined, - ); - results.push(...chunks); - }); - return results; -} diff --git a/core/autocomplete/filtering/filter.ts b/core/autocomplete/filtering/filter.ts deleted file mode 100644 index 5b2b66df0..000000000 --- a/core/autocomplete/filtering/filter.ts +++ /dev/null @@ -1,4 +0,0 @@ -export function isOnlyWhitespace(completion: string): boolean { - const whitespaceRegex = /^[\s]+$/; - return whitespaceRegex.test(completion); -} diff --git a/core/autocomplete/postprocessing/index.ts b/core/autocomplete/postprocessing/index.ts index af0c698e0..001642573 100644 --- a/core/autocomplete/postprocessing/index.ts +++ b/core/autocomplete/postprocessing/index.ts @@ -42,6 +42,10 @@ function isExtremeRepetition(completion: string): boolean { } return false; } +export function isOnlyWhitespace(completion: string): boolean { + const whitespaceRegex = /^[\s]+$/; + return whitespaceRegex.test(completion); +} export function postprocessCompletion({ completion, @@ -55,7 +59,7 @@ export function postprocessCompletion({ suffix: string; }): string | undefined { // Don't return empty - if (completion.trim().length <= 0) { + if (isOnlyWhitespace(completion)) { return undefined; } diff --git a/core/autocomplete/constants/AutocompleteTemplate.ts b/core/autocomplete/templating/AutocompleteTemplate.ts similarity index 100% rename from core/autocomplete/constants/AutocompleteTemplate.ts rename to core/autocomplete/templating/AutocompleteTemplate.ts diff --git a/core/autocomplete/templating/index.ts b/core/autocomplete/templating/index.ts new file mode 100644 index 000000000..725c99753 --- /dev/null +++ b/core/autocomplete/templating/index.ts @@ -0,0 +1,19 @@ +import { getBasename } from "../../util"; +import { AutocompleteLanguageInfo } from "../constants/AutocompleteLanguageInfo"; + +export function formatExternalSnippet( + filepath: string, + snippet: string, + language: AutocompleteLanguageInfo, +) { + const comment = language.singleLineComment; + const lines = [ + `${comment} Path: ${getBasename(filepath)}`, + ...snippet + .trim() + .split("\n") + .map((line) => `${comment} ${line}`), + comment, + ]; + return lines.join("\n"); +} From 54b27748e3a81a19632a0530853da31c1e1c7a88 Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 30 Oct 2024 21:00:42 -0700 Subject: [PATCH 12/96] move multiline classification --- .../classification/shouldCompleteMultiline.ts | 55 ++++++ core/autocomplete/completionProvider.ts | 184 +++++++----------- 2 files changed, 127 insertions(+), 112 deletions(-) diff --git a/core/autocomplete/classification/shouldCompleteMultiline.ts b/core/autocomplete/classification/shouldCompleteMultiline.ts index 9ae0d55fa..8bc5e5de4 100644 --- a/core/autocomplete/classification/shouldCompleteMultiline.ts +++ b/core/autocomplete/classification/shouldCompleteMultiline.ts @@ -1,4 +1,6 @@ +import { TabAutocompleteOptions } from "@continuedev/config-types"; import { AutocompleteLanguageInfo } from "../constants/AutocompleteLanguageInfo"; +import { AutocompleteInput } from "../types"; import { AstPath } from "../util/ast"; const BLOCK_TYPES = ["body", "statement_block"]; @@ -31,3 +33,56 @@ export async function shouldCompleteMultiline( return true; } + +function shouldCompleteMultilineBasedOnLanguage( + language: AutocompleteLanguageInfo, + prefix: string, + suffix: string, +) { + let langMultilineDecision = language.useMultiline?.({ prefix, suffix }); + return langMultilineDecision; +} + +function shouldCompleteMultilineBasedOnSelectedCompletion( + selectedCompletionInfo: AutocompleteInput["selectedCompletionInfo"], + multilineCompletions: TabAutocompleteOptions["multilineCompletions"], + completeMultiline: boolean, +) { + return ( + !selectedCompletionInfo && // Only ever single-line if using intellisense selected value + multilineCompletions !== "never" && + (multilineCompletions === "always" || completeMultiline) + ); +} + +export function decideMultilineEarly({ + language, + prefix, + suffix, + selectedCompletionInfo, + multilineCompletions, + completeMultiline, +}: { + language: AutocompleteLanguageInfo; + prefix: string; + suffix: string; + selectedCompletionInfo: AutocompleteInput["selectedCompletionInfo"]; + multilineCompletions: TabAutocompleteOptions["multilineCompletions"]; + completeMultiline: boolean; +}) { + if (shouldCompleteMultilineBasedOnLanguage(language, prefix, suffix)) { + return true; + } + + if ( + shouldCompleteMultilineBasedOnSelectedCompletion( + selectedCompletionInfo, + multilineCompletions, + completeMultiline, + ) + ) { + return true; + } + + return false; +} diff --git a/core/autocomplete/completionProvider.ts b/core/autocomplete/completionProvider.ts index 4f47579a4..8c01dcb53 100644 --- a/core/autocomplete/completionProvider.ts +++ b/core/autocomplete/completionProvider.ts @@ -4,7 +4,7 @@ import path from "path"; import { ConfigHandler } from "../config/ConfigHandler.js"; import { TRIAL_FIM_MODEL } from "../config/onboarding.js"; import { streamLines } from "../diff/util.js"; -import { IDE, ILLM, ModelProvider, TabAutocompleteOptions } from "../index.js"; +import { IDE, ILLM, TabAutocompleteOptions } from "../index.js"; import { logDevData } from "../util/devdata.js"; import { getBasename, getLastNPathParts } from "../util/index.js"; import { @@ -29,6 +29,7 @@ import Handlebars from "handlebars"; import { getConfigJsonPath } from "../util/paths.js"; import { AutocompleteDebouncer } from "./AutocompleteDebouncer.js"; import AutocompleteLruCache from "./AutocompleteLruCache.js"; +import { decideMultilineEarly } from "./classification/shouldCompleteMultiline.js"; import { ImportDefinitionsService } from "./context/ImportDefinitionsService.js"; import { BracketMatchingService } from "./filtering/BracketMatchingService.js"; import { stopAtStopTokens } from "./filtering/streamTransforms/charStream.js"; @@ -52,14 +53,6 @@ const ERRORS_TO_IGNORE = [ "unexpected server status", ]; -const LOCAL_PROVIDERS: ModelProvider[] = [ - "ollama", - "lmstudio", - "llama.cpp", - "llamafile", - "text-gen-webui", -]; - export type GetLspDefinitionsFunction = ( filepath: string, contents: string, @@ -130,7 +123,7 @@ export class CompletionProvider { if (this._outcomes.has(completionId)) { const outcome = this._outcomes.get(completionId)!; - this.logAcceptedCompletion(completionId, outcome); + this.logAutocompleteOutcome(outcome); this._outcomes.delete(completionId); this.bracketMatchingService.handleAcceptedCompletion( @@ -140,20 +133,26 @@ export class CompletionProvider { } } - private logAcceptedCompletion( - completionId: string, - outcome: AutocompleteOutcome, - ) { + private logAutocompleteOutcome(outcome: AutocompleteOutcome) { outcome.accepted = true; logDevData("autocomplete", outcome); + const { prompt, completion, prefix, suffix, ...restOfOutcome } = outcome; void Telemetry.capture( "autocomplete", { - accepted: outcome.accepted, - modelName: outcome.modelName, - modelProvider: outcome.modelProvider, - time: outcome.time, - cacheHit: outcome.cacheHit, + accepted: restOfOutcome.accepted, + cacheHit: restOfOutcome.cacheHit, + completionId: restOfOutcome.completionId, + completionOptions: restOfOutcome.completionOptions, + debounceDelay: restOfOutcome.debounceDelay, + fileExtension: restOfOutcome.filepath.split(".")?.slice(-1)[0], + maxPromptTokens: restOfOutcome.maxPromptTokens, + modelName: restOfOutcome.modelName, + modelProvider: restOfOutcome.modelProvider, + multilineCompletions: restOfOutcome.multilineCompletions, + time: restOfOutcome.time, + useRecentlyEdited: restOfOutcome.useRecentlyEdited, + useRootPathContext: restOfOutcome.useRootPathContext, }, true, ); @@ -170,16 +169,58 @@ export class CompletionProvider { } } + private async _getAutocompleteOptions() { + const config = await this.configHandler.loadConfig(); + const options = { + ...DEFAULT_AUTOCOMPLETE_OPTS, + ...config.tabAutocompleteOptions, + }; + return options; + } + + private async _isDisabledForFile( + currentFilepath: string, + disableInFiles: string[] | undefined, + ) { + if (disableInFiles) { + // Relative path needed for `ignore` + const workspaceDirs = await this.ide.getWorkspaceDirs(); + let filepath = currentFilepath; + for (const workspaceDir of workspaceDirs) { + const relativePath = path.relative(workspaceDir, filepath); + const relativePathBase = relativePath.split(path.sep).at(0); + const isInWorkspace = + !path.isAbsolute(relativePath) && relativePathBase !== ".."; + if (isInWorkspace) { + filepath = path.relative(workspaceDir, filepath); + break; + } + } + + // Worst case we can check filetype glob patterns + if (filepath === currentFilepath) { + filepath = getBasename(filepath); + } + + // @ts-ignore + const pattern = ignore.default().add(options.disableInFiles); + if (pattern.ignores(filepath)) { + return true; + } + } + } + public async provideInlineCompletionItems( input: AutocompleteInput, token: AbortSignal | undefined, ): Promise { try { - const config = await this.configHandler.loadConfig(); - const options = { - ...DEFAULT_AUTOCOMPLETE_OPTS, - ...config.tabAutocompleteOptions, - }; + const options = await this._getAutocompleteOptions(); + + // Allow disabling autocomplete from config.json + if (options.disable) { + return undefined; + } // Check whether we're in the continue config.json file if (input.filepath === getConfigJsonPath()) { @@ -187,31 +228,10 @@ export class CompletionProvider { } // Check whether autocomplete is disabled for this file - if (options.disableInFiles) { - // Relative path needed for `ignore` - const workspaceDirs = await this.ide.getWorkspaceDirs(); - let filepath = input.filepath; - for (const workspaceDir of workspaceDirs) { - const relativePath = path.relative(workspaceDir, filepath); - const relativePathBase = relativePath.split(path.sep).at(0); - const isInWorkspace = - !path.isAbsolute(relativePath) && relativePathBase !== ".."; - if (isInWorkspace) { - filepath = path.relative(workspaceDir, filepath); - break; - } - } - - // Worst case we can check filetype glob patterns - if (filepath === input.filepath) { - filepath = getBasename(filepath); - } - - // @ts-ignore - const pattern = ignore.default().add(options.disableInFiles); - if (pattern.ignores(filepath)) { - return undefined; - } + if ( + await this._isDisabledForFile(input.filepath, options.disableInFiles) + ) { + return undefined; } // Create abort signal if not given @@ -221,11 +241,6 @@ export class CompletionProvider { this._abortControllers.set(input.completionId, controller); } - // Allow disabling autocomplete from config.json - if (options.disable) { - return undefined; - } - // Debounce if (await this.debouncer.delayAndShouldDebounce(options.debounceDelay)) { return undefined; @@ -233,7 +248,6 @@ export class CompletionProvider { // Get completion const llm = await this.getLlm(); - if (!llm) { return undefined; } @@ -244,18 +258,11 @@ export class CompletionProvider { return undefined; } - // Set temperature (but don't overrride) + // Set temperature (but don't override) if (llm.completionOptions.temperature === undefined) { llm.completionOptions.temperature = 0.01; } - if ( - !config.tabAutocompleteOptions?.maxPromptTokens && - LOCAL_PROVIDERS.includes(llm.providerName) - ) { - options.maxPromptTokens = 500; - } - const outcome = await this.getTabCompletion(token, options, llm, input); if (!outcome?.completion) { @@ -285,27 +292,7 @@ export class CompletionProvider { const logRejectionTimeout = setTimeout(() => { // Wait 10 seconds, then assume it wasn't accepted outcome.accepted = false; - logDevData("autocomplete", outcome); - const { prompt, completion, prefix, suffix, ...restOfOutcome } = outcome; - void Telemetry.capture( - "autocomplete", - { - accepted: restOfOutcome.accepted, - cacheHit: restOfOutcome.cacheHit, - completionId: restOfOutcome.completionId, - completionOptions: restOfOutcome.completionOptions, - debounceDelay: restOfOutcome.debounceDelay, - fileExtension: restOfOutcome.filepath.split(".")?.slice(-1)[0], - maxPromptTokens: restOfOutcome.maxPromptTokens, - modelName: restOfOutcome.modelName, - modelProvider: restOfOutcome.modelProvider, - multilineCompletions: restOfOutcome.multilineCompletions, - time: restOfOutcome.time, - useRecentlyEdited: restOfOutcome.useRecentlyEdited, - useRootPathContext: restOfOutcome.useRootPathContext, - }, - true, - ); + this.logAutocompleteOutcome(outcome); this._logRejectionTimeouts.delete(completionId); }, COUNT_COMPLETION_REJECTED_AFTER); this._outcomes.set(completionId, outcome); @@ -340,33 +327,6 @@ export class CompletionProvider { }; } - private isMultiline({ - language, - prefix, - suffix, - selectedCompletionInfo, - multilineCompletions, - completeMultiline, - }: { - language: AutocompleteLanguageInfo; - prefix: string; - suffix: string; - selectedCompletionInfo: AutocompleteInput["selectedCompletionInfo"]; - multilineCompletions: TabAutocompleteOptions["multilineCompletions"]; - completeMultiline: boolean; - }) { - let langMultilineDecision = language.useMultiline?.({ prefix, suffix }); - if (langMultilineDecision) { - return langMultilineDecision; - } else { - return ( - !selectedCompletionInfo && // Only ever single-line if using intellisense selected value - multilineCompletions !== "never" && - (multilineCompletions === "always" || completeMultiline) - ); - } - } - async getTabCompletion( token: AbortSignal, options: TabAutocompleteOptions, @@ -579,7 +539,7 @@ export class CompletionProvider { const multiline = !options.transform || - this.isMultiline({ + decideMultilineEarly({ multilineCompletions: options.multilineCompletions, language: lang, selectedCompletionInfo: input.selectedCompletionInfo, From 04003da444618af2d3ce049eee75deabf697fe0e Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 30 Oct 2024 21:10:29 -0700 Subject: [PATCH 13/96] refactor getLlm --- core/autocomplete/completionProvider.ts | 83 +++++++++++++++---------- 1 file changed, 49 insertions(+), 34 deletions(-) diff --git a/core/autocomplete/completionProvider.ts b/core/autocomplete/completionProvider.ts index 8c01dcb53..bc554c626 100644 --- a/core/autocomplete/completionProvider.ts +++ b/core/autocomplete/completionProvider.ts @@ -74,7 +74,7 @@ export class CompletionProvider { constructor( private readonly configHandler: ConfigHandler, private readonly ide: IDE, - private readonly getLlm: () => Promise, + private readonly _injectedGetLlm: () => Promise, private readonly _onError: (e: any) => void, private readonly getDefinitionsFromLsp: GetLspDefinitionsFunction, ) { @@ -88,6 +88,27 @@ export class CompletionProvider { ); } + private async _getLlm(): Promise { + const llm = await this._injectedGetLlm(); + + if (!llm) { + return undefined; + } + + // Ignore empty API keys for Mistral since we currently write + // a template provider without one during onboarding + if (llm.providerName === "mistral" && llm.apiKey === "") { + return undefined; + } + + // Set temperature (but don't override) + if (llm.completionOptions.temperature === undefined) { + llm.completionOptions.temperature = 0.01; + } + + return llm; + } + private onError(e: any) { console.warn("Error generating autocompletion: ", e); if ( @@ -210,6 +231,28 @@ export class CompletionProvider { } } + private async _shouldSkipCompletionForAnyReason( + input: AutocompleteInput, + options: TabAutocompleteOptions, + ): Promise { + // Allow disabling autocomplete from config.json + if (options.disable) { + return true; + } + + // Check whether we're in the continue config.json file + if (input.filepath === getConfigJsonPath()) { + return true; + } + + // Check whether autocomplete is disabled for this file + if (await this._isDisabledForFile(input.filepath, options.disableInFiles)) { + return true; + } + + return false; + } + public async provideInlineCompletionItems( input: AutocompleteInput, token: AbortSignal | undefined, @@ -217,20 +260,14 @@ export class CompletionProvider { try { const options = await this._getAutocompleteOptions(); - // Allow disabling autocomplete from config.json - if (options.disable) { + // Debounce + if (await this.debouncer.delayAndShouldDebounce(options.debounceDelay)) { return undefined; } - // Check whether we're in the continue config.json file - if (input.filepath === getConfigJsonPath()) { - return undefined; - } - - // Check whether autocomplete is disabled for this file - if ( - await this._isDisabledForFile(input.filepath, options.disableInFiles) - ) { + // Get completion + const llm = await this._getLlm(); + if (!llm) { return undefined; } @@ -241,28 +278,6 @@ export class CompletionProvider { this._abortControllers.set(input.completionId, controller); } - // Debounce - if (await this.debouncer.delayAndShouldDebounce(options.debounceDelay)) { - return undefined; - } - - // Get completion - const llm = await this.getLlm(); - if (!llm) { - return undefined; - } - - // Ignore empty API keys for Mistral since we currently write - // a template provider without one during onboarding - if (llm.providerName === "mistral" && llm.apiKey === "") { - return undefined; - } - - // Set temperature (but don't override) - if (llm.completionOptions.temperature === undefined) { - llm.completionOptions.temperature = 0.01; - } - const outcome = await this.getTabCompletion(token, options, llm, input); if (!outcome?.completion) { From 8aa825940f0fc78777f7f1f1cbdf2cdc32046218 Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 30 Oct 2024 21:26:28 -0700 Subject: [PATCH 14/96] prefiltering --- core/autocomplete/completionProvider.ts | 101 +++++------------------- core/autocomplete/prefiltering/index.ts | 92 +++++++++++++++++++++ 2 files changed, 110 insertions(+), 83 deletions(-) create mode 100644 core/autocomplete/prefiltering/index.ts diff --git a/core/autocomplete/completionProvider.ts b/core/autocomplete/completionProvider.ts index bc554c626..a590045f5 100644 --- a/core/autocomplete/completionProvider.ts +++ b/core/autocomplete/completionProvider.ts @@ -1,8 +1,4 @@ -import ignore from "ignore"; -import OpenAI from "openai"; -import path from "path"; import { ConfigHandler } from "../config/ConfigHandler.js"; -import { TRIAL_FIM_MODEL } from "../config/onboarding.js"; import { streamLines } from "../diff/util.js"; import { IDE, ILLM, TabAutocompleteOptions } from "../index.js"; import { logDevData } from "../util/devdata.js"; @@ -26,7 +22,8 @@ import { postprocessCompletion } from "./postprocessing/index.js"; import { getTemplateForModel } from "./templating/AutocompleteTemplate.js"; // @prettier-ignore import Handlebars from "handlebars"; -import { getConfigJsonPath } from "../util/paths.js"; +import { TRIAL_FIM_MODEL } from "../config/onboarding.js"; +import OpenAI from "../llm/llms/OpenAI.js"; import { AutocompleteDebouncer } from "./AutocompleteDebouncer.js"; import AutocompleteLruCache from "./AutocompleteLruCache.js"; import { decideMultilineEarly } from "./classification/shouldCompleteMultiline.js"; @@ -41,6 +38,7 @@ import { stopAtSimilarLine, streamWithNewLines, } from "./filtering/streamTransforms/lineStream.js"; +import { shouldPrefilter } from "./prefiltering/index.js"; import { formatExternalSnippet } from "./templating/index.js"; import { AutocompleteInput, AutocompleteOutcome } from "./types.js"; @@ -88,7 +86,7 @@ export class CompletionProvider { ); } - private async _getLlm(): Promise { + private async _prepareLlm(): Promise { const llm = await this._injectedGetLlm(); if (!llm) { @@ -106,6 +104,15 @@ export class CompletionProvider { llm.completionOptions.temperature = 0.01; } + if (llm instanceof OpenAI) { + llm.useLegacyCompletionsEndpoint = true; + } else if ( + llm.providerName === "free-trial" && + llm.model !== TRIAL_FIM_MODEL + ) { + llm.model = TRIAL_FIM_MODEL; + } + return llm; } @@ -199,60 +206,6 @@ export class CompletionProvider { return options; } - private async _isDisabledForFile( - currentFilepath: string, - disableInFiles: string[] | undefined, - ) { - if (disableInFiles) { - // Relative path needed for `ignore` - const workspaceDirs = await this.ide.getWorkspaceDirs(); - let filepath = currentFilepath; - for (const workspaceDir of workspaceDirs) { - const relativePath = path.relative(workspaceDir, filepath); - const relativePathBase = relativePath.split(path.sep).at(0); - const isInWorkspace = - !path.isAbsolute(relativePath) && relativePathBase !== ".."; - if (isInWorkspace) { - filepath = path.relative(workspaceDir, filepath); - break; - } - } - - // Worst case we can check filetype glob patterns - if (filepath === currentFilepath) { - filepath = getBasename(filepath); - } - - // @ts-ignore - const pattern = ignore.default().add(options.disableInFiles); - if (pattern.ignores(filepath)) { - return true; - } - } - } - - private async _shouldSkipCompletionForAnyReason( - input: AutocompleteInput, - options: TabAutocompleteOptions, - ): Promise { - // Allow disabling autocomplete from config.json - if (options.disable) { - return true; - } - - // Check whether we're in the continue config.json file - if (input.filepath === getConfigJsonPath()) { - return true; - } - - // Check whether autocomplete is disabled for this file - if (await this._isDisabledForFile(input.filepath, options.disableInFiles)) { - return true; - } - - return false; - } - public async provideInlineCompletionItems( input: AutocompleteInput, token: AbortSignal | undefined, @@ -260,13 +213,17 @@ export class CompletionProvider { try { const options = await this._getAutocompleteOptions(); + if (await shouldPrefilter(input, options, this.ide)) { + return undefined; + } + // Debounce if (await this.debouncer.delayAndShouldDebounce(options.debounceDelay)) { return undefined; } // Get completion - const llm = await this._getLlm(); + const llm = await this._prepareLlm(); if (!llm) { return undefined; } @@ -366,28 +323,6 @@ export class CompletionProvider { // Filter const lang = languageForFilepath(filepath); - if (options.transform) { - const line = fileLines[pos.line] ?? ""; - for (const endOfLine of lang.endOfLine) { - if (line.endsWith(endOfLine) && pos.character >= line.length) { - return undefined; - } - } - } - - // Model - if (!llm) { - return; - } - if (llm instanceof OpenAI) { - llm.useLegacyCompletionsEndpoint = true; - } else if ( - llm.providerName === "free-trial" && - llm.model !== TRIAL_FIM_MODEL - ) { - llm.model = TRIAL_FIM_MODEL; - } - // Prompt let fullPrefix = getRangeInString(fileContents, { diff --git a/core/autocomplete/prefiltering/index.ts b/core/autocomplete/prefiltering/index.ts new file mode 100644 index 000000000..1d8d089c9 --- /dev/null +++ b/core/autocomplete/prefiltering/index.ts @@ -0,0 +1,92 @@ +import path from "node:path"; +import { IDE, Position, TabAutocompleteOptions } from "../.."; +import { getBasename } from "../../util"; +import { getConfigJsonPath } from "../../util/paths"; +import { languageForFilepath } from "../constructPrompt"; +import { AutocompleteInput } from "../types"; + +async function isDisabledForFile( + currentFilepath: string, + disableInFiles: string[] | undefined, + ide: IDE, +) { + if (disableInFiles) { + // Relative path needed for `ignore` + const workspaceDirs = await ide.getWorkspaceDirs(); + let filepath = currentFilepath; + for (const workspaceDir of workspaceDirs) { + const relativePath = path.relative(workspaceDir, filepath); + const relativePathBase = relativePath.split(path.sep).at(0); + const isInWorkspace = + !path.isAbsolute(relativePath) && relativePathBase !== ".."; + if (isInWorkspace) { + filepath = path.relative(workspaceDir, filepath); + break; + } + } + + // Worst case we can check filetype glob patterns + if (filepath === currentFilepath) { + filepath = getBasename(filepath); + } + + // @ts-ignore + const pattern = ignore.default().add(options.disableInFiles); + if (pattern.ignores(filepath)) { + return true; + } + } +} + +async function shouldLanguageSpecificPrefilter( + manuallyPassFileContents: string | undefined, + filepath: string, + pos: Position, + ide: IDE, +) { + const lang = languageForFilepath(filepath); + const fileContents = + manuallyPassFileContents ?? (await ide.readFile(filepath)); + const fileLines = fileContents.split("\n"); + const line = fileLines[pos.line] ?? ""; + for (const endOfLine of lang.endOfLine) { + if (line.endsWith(endOfLine) && pos.character >= line.length) { + return true; + } + } +} + +export async function shouldPrefilter( + input: AutocompleteInput, + options: TabAutocompleteOptions, + ide: IDE, +): Promise { + // Allow disabling autocomplete from config.json + if (options.disable) { + return true; + } + + // Check whether we're in the continue config.json file + if (input.filepath === getConfigJsonPath()) { + return true; + } + + // Check whether autocomplete is disabled for this file + if (await isDisabledForFile(input.filepath, options.disableInFiles, ide)) { + return true; + } + + if ( + options.transform && + (await shouldLanguageSpecificPrefilter( + input.manuallyPassFileContents, + input.filepath, + input.pos, + ide, + )) + ) { + return true; + } + + return false; +} From 66da91b0a400166132db1d18917b3c53486e43cf Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 30 Oct 2024 21:55:53 -0700 Subject: [PATCH 15/96] more refactoring --- core/autocomplete/completionProvider.ts | 82 ++++-------------- .../StreamTransformPipeline.ts | 84 +++++++++++++++++++ 2 files changed, 100 insertions(+), 66 deletions(-) create mode 100644 core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts diff --git a/core/autocomplete/completionProvider.ts b/core/autocomplete/completionProvider.ts index a590045f5..77a5ac920 100644 --- a/core/autocomplete/completionProvider.ts +++ b/core/autocomplete/completionProvider.ts @@ -1,5 +1,4 @@ import { ConfigHandler } from "../config/ConfigHandler.js"; -import { streamLines } from "../diff/util.js"; import { IDE, ILLM, TabAutocompleteOptions } from "../index.js"; import { logDevData } from "../util/devdata.js"; import { getBasename, getLastNPathParts } from "../util/index.js"; @@ -29,15 +28,7 @@ import AutocompleteLruCache from "./AutocompleteLruCache.js"; import { decideMultilineEarly } from "./classification/shouldCompleteMultiline.js"; import { ImportDefinitionsService } from "./context/ImportDefinitionsService.js"; import { BracketMatchingService } from "./filtering/BracketMatchingService.js"; -import { stopAtStopTokens } from "./filtering/streamTransforms/charStream.js"; -import { - avoidPathLineAndEmptyComments, - skipPrefixes, - stopAtLines, - stopAtRepeatingLines, - stopAtSimilarLine, - streamWithNewLines, -} from "./filtering/streamTransforms/lineStream.js"; +import { StreamTransformPipeline } from "./filtering/streamTransforms/StreamTransformPipeline.js"; import { shouldPrefilter } from "./prefiltering/index.js"; import { formatExternalSnippet } from "./templating/index.js"; import { AutocompleteInput, AutocompleteOutcome } from "./types.js"; @@ -67,6 +58,7 @@ export class CompletionProvider { public errorsShown: Set = new Set(); private bracketMatchingService = new BracketMatchingService(); private debouncer = new AutocompleteDebouncer(); + private streamTransformPipeline = new StreamTransformPipeline(); // private nearbyDefinitionsService = new NearbyDefinitionsService(); constructor( @@ -344,17 +336,6 @@ export class CompletionProvider { end: { line: fileLines.length - 1, character: Number.MAX_SAFE_INTEGER }, }); - // First non-whitespace line below the cursor - let lineBelowCursor = ""; - let i = 1; - while ( - lineBelowCursor.trim() === "" && - pos.line + i <= fileLines.length - 1 - ) { - lineBelowCursor = fileLines[Math.min(pos.line + i, fileLines.length - 1)]; - i++; - } - let extrasSnippets = options.useOtherFiles ? ((await Promise.race([ this.getDefinitionsFromLsp( @@ -476,7 +457,7 @@ export class CompletionProvider { cacheHit = true; completion = cachedCompletion; } else { - const stop = [ + const stopTokens = [ ...(completionOptions?.stop || []), // ...multilineStops, ...commonStops, @@ -505,12 +486,12 @@ export class CompletionProvider { llm.supportsFim() ? llm.streamFim(prefix, suffix, { ...completionOptions, - stop, + stop: stopTokens, }) : llm.streamComplete(prompt, { ...completionOptions, raw: true, - stop, + stop: stopTokens, }), multiline, ); @@ -530,53 +511,22 @@ export class CompletionProvider { yield update; } }; - let charGenerator = generatorWithCancellation(); - if (options.transform) { - // charGenerator = noFirstCharNewline(charGenerator); - // charGenerator = onlyWhitespaceAfterEndOfLine( - // charGenerator, - // lang.endOfLine, - // fullStop, - // ); - charGenerator = stopAtStopTokens(charGenerator, stop); - charGenerator = - this.bracketMatchingService.stopOnUnmatchedClosingBracket( - charGenerator, + const initialGenerator = generatorWithCancellation(); + const finalGenerator = options.transform + ? this.streamTransformPipeline.transform( + initialGenerator, prefix, suffix, filepath, multiline, - ); - } - - let lineGenerator = streamLines(charGenerator); - if (options.transform) { - lineGenerator = stopAtLines(lineGenerator, fullStop); - lineGenerator = stopAtRepeatingLines(lineGenerator, fullStop); - lineGenerator = avoidPathLineAndEmptyComments( - lineGenerator, - lang.singleLineComment, - ); - lineGenerator = skipPrefixes(lineGenerator); - - // lineGenerator = noTopLevelKeywordsMidline( - // lineGenerator, - // lang.topLevelKeywords, - // fullStop, - // ); - for (const lineFilter of lang.lineFilters ?? []) { - lineGenerator = lineFilter({ lines: lineGenerator, fullStop }); - } - - lineGenerator = stopAtSimilarLine( - lineGenerator, - lineBelowCursor, - fullStop, - ); - } - - const finalGenerator = streamWithNewLines(lineGenerator); + pos, + fileLines, + stopTokens, + lang, + fullStop, + ) + : initialGenerator; try { for await (const update of finalGenerator) { diff --git a/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts b/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts new file mode 100644 index 000000000..edc4f8c40 --- /dev/null +++ b/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts @@ -0,0 +1,84 @@ +import { Position } from "../../.."; +import { streamLines } from "../../../diff/util"; +import { AutocompleteLanguageInfo } from "../../constants/AutocompleteLanguageInfo"; +import { BracketMatchingService } from "../BracketMatchingService"; +import { stopAtStopTokens } from "./charStream"; +import { + avoidPathLineAndEmptyComments, + skipPrefixes, + stopAtLines, + stopAtRepeatingLines, + stopAtSimilarLine, + streamWithNewLines, +} from "./lineStream"; + +export class StreamTransformPipeline { + private bracketMatchingService = new BracketMatchingService(); + + async *transform( + generator: AsyncGenerator, + prefix: string, + suffix: string, + filepath: string, + multiline: boolean, + pos: Position, + fileLines: string[], + stopTokens: string[], + lang: AutocompleteLanguageInfo, + fullStop: () => void, + ): AsyncGenerator { + let charGenerator = generator; + + // charGenerator = noFirstCharNewline(charGenerator); + // charGenerator = onlyWhitespaceAfterEndOfLine( + // charGenerator, + // lang.endOfLine, + // fullStop, + // ); + charGenerator = stopAtStopTokens(generator, stopTokens); + charGenerator = this.bracketMatchingService.stopOnUnmatchedClosingBracket( + charGenerator, + prefix, + suffix, + filepath, + multiline, + ); + + let lineGenerator = streamLines(charGenerator); + + // First non-whitespace line below the cursor + let lineBelowCursor = ""; + let i = 1; + while ( + lineBelowCursor.trim() === "" && + pos.line + i <= fileLines.length - 1 + ) { + lineBelowCursor = fileLines[Math.min(pos.line + i, fileLines.length - 1)]; + i++; + } + + lineGenerator = stopAtLines(lineGenerator, fullStop); + lineGenerator = stopAtRepeatingLines(lineGenerator, fullStop); + lineGenerator = avoidPathLineAndEmptyComments( + lineGenerator, + lang.singleLineComment, + ); + lineGenerator = skipPrefixes(lineGenerator); + + // lineGenerator = noTopLevelKeywordsMidline( + // lineGenerator, + // lang.topLevelKeywords, + // fullStop, + // ); + for (const lineFilter of lang.lineFilters ?? []) { + lineGenerator = lineFilter({ lines: lineGenerator, fullStop }); + } + + lineGenerator = stopAtSimilarLine(lineGenerator, lineBelowCursor, fullStop); + + const finalGenerator = streamWithNewLines(lineGenerator); + for await (const update of finalGenerator) { + yield update; + } + } +} From c1df46c0c03020ab544ac6b88ae15218e0cb8e1a Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 30 Oct 2024 22:14:07 -0700 Subject: [PATCH 16/96] refactor more --- core/autocomplete/completionProvider.ts | 111 ++++-------------------- core/autocomplete/templating/index.ts | 107 ++++++++++++++++++++++- 2 files changed, 122 insertions(+), 96 deletions(-) diff --git a/core/autocomplete/completionProvider.ts b/core/autocomplete/completionProvider.ts index 77a5ac920..45bf98cd0 100644 --- a/core/autocomplete/completionProvider.ts +++ b/core/autocomplete/completionProvider.ts @@ -1,7 +1,6 @@ import { ConfigHandler } from "../config/ConfigHandler.js"; import { IDE, ILLM, TabAutocompleteOptions } from "../index.js"; import { logDevData } from "../util/devdata.js"; -import { getBasename, getLastNPathParts } from "../util/index.js"; import { COUNT_COMPLETION_REJECTED_AFTER, DEFAULT_AUTOCOMPLETE_OPTS, @@ -18,19 +17,16 @@ import { AutocompleteSnippet } from "./context/ranking/index.js"; import { RootPathContextService } from "./context/RootPathContextService.js"; import { GeneratorReuseManager } from "./generation/GeneratorReuseManager.js"; import { postprocessCompletion } from "./postprocessing/index.js"; -import { getTemplateForModel } from "./templating/AutocompleteTemplate.js"; // @prettier-ignore -import Handlebars from "handlebars"; import { TRIAL_FIM_MODEL } from "../config/onboarding.js"; import OpenAI from "../llm/llms/OpenAI.js"; import { AutocompleteDebouncer } from "./AutocompleteDebouncer.js"; import AutocompleteLruCache from "./AutocompleteLruCache.js"; -import { decideMultilineEarly } from "./classification/shouldCompleteMultiline.js"; import { ImportDefinitionsService } from "./context/ImportDefinitionsService.js"; import { BracketMatchingService } from "./filtering/BracketMatchingService.js"; import { StreamTransformPipeline } from "./filtering/streamTransforms/StreamTransformPipeline.js"; import { shouldPrefilter } from "./prefiltering/index.js"; -import { formatExternalSnippet } from "./templating/index.js"; +import { renderPrompt } from "./templating/index.js"; import { AutocompleteInput, AutocompleteOutcome } from "./types.js"; const autocompleteCache = AutocompleteLruCache.get(); @@ -381,68 +377,19 @@ export class CompletionProvider { suffix = ""; } - // Template prompt - const { - template, - completionOptions, - compilePrefixSuffix = undefined, - } = options.template - ? { template: options.template, completionOptions: {} } - : getTemplateForModel(llm.model); - - let prompt: string; - const filename = getBasename(filepath); - const reponame = getBasename(workspaceDirs[0] ?? "myproject"); - - // Some models have prompts that need two passes. This lets us pass the compiled prefix/suffix - // into either the 2nd template to generate a raw string, or to pass prefix, suffix to a FIM endpoint - if (compilePrefixSuffix) { - [prefix, suffix] = compilePrefixSuffix( - prefix, - suffix, - filepath, - reponame, - snippets, - ); - } - - if (typeof template === "string") { - const compiledTemplate = Handlebars.compile(template); - - // Format snippets as comments and prepend to prefix - const formattedSnippets = snippets - .map((snippet) => - formatExternalSnippet(snippet.filepath, snippet.contents, lang), - ) - .join("\n"); - if (formattedSnippets.length > 0) { - prefix = `${formattedSnippets}\n\n${prefix}`; - } else if (prefix.trim().length === 0 && suffix.trim().length === 0) { - // If it's an empty file, include the file name as a comment - prefix = `${lang.singleLineComment} ${getLastNPathParts( - filepath, - 2, - )}\n${prefix}`; - } - - prompt = compiledTemplate({ - prefix, - suffix, - filename, - reponame, - language: lang.name, - }); - } else { - // Let the template function format snippets - prompt = template( - prefix, - suffix, - filepath, - reponame, - lang.name, - snippets, - ); - } + const [prompt, completionOptions, multiline] = renderPrompt( + options, + prefix, + suffix, + filepath, + lang, + snippets, + llm.model, + workspaceDirs, + options.template, + input.selectedCompletionInfo, + completeMultiline, + ); // Completion let completion = ""; @@ -457,41 +404,15 @@ export class CompletionProvider { cacheHit = true; completion = cachedCompletion; } else { - const stopTokens = [ - ...(completionOptions?.stop || []), - // ...multilineStops, - ...commonStops, - ...(llm.model.toLowerCase().includes("starcoder2") - ? STARCODER2_T_ARTIFACTS - : []), - ...(lang.stopWords ?? []), - // ...lang.topLevelKeywords.map((word) => `\n${word}`), - ]; - - const multiline = - !options.transform || - decideMultilineEarly({ - multilineCompletions: options.multilineCompletions, - language: lang, - selectedCompletionInfo: input.selectedCompletionInfo, - prefix, - suffix, - completeMultiline, - }); - // Try to reuse pending requests if what the user typed matches start of completion const generator = this.generatorReuseManager.getGenerator( prefix, () => llm.supportsFim() - ? llm.streamFim(prefix, suffix, { - ...completionOptions, - stop: stopTokens, - }) + ? llm.streamFim(prefix, suffix, completionOptions) : llm.streamComplete(prompt, { ...completionOptions, raw: true, - stop: stopTokens, }), multiline, ); @@ -522,7 +443,7 @@ export class CompletionProvider { multiline, pos, fileLines, - stopTokens, + completionOptions?.stop || [], lang, fullStop, ) diff --git a/core/autocomplete/templating/index.ts b/core/autocomplete/templating/index.ts index 725c99753..e0890ca8b 100644 --- a/core/autocomplete/templating/index.ts +++ b/core/autocomplete/templating/index.ts @@ -1,5 +1,10 @@ -import { getBasename } from "../../util"; +import { CompletionOptions, TabAutocompleteOptions } from "../.."; +import { getBasename, getLastNPathParts } from "../../util"; +import { decideMultilineEarly } from "../classification/shouldCompleteMultiline"; import { AutocompleteLanguageInfo } from "../constants/AutocompleteLanguageInfo"; +import { AutocompleteSnippet } from "../context/ranking"; +import { AutocompleteInput } from "../types"; +import { getTemplateForModel } from "./AutocompleteTemplate"; export function formatExternalSnippet( filepath: string, @@ -17,3 +22,103 @@ export function formatExternalSnippet( ]; return lines.join("\n"); } + +export function renderPrompt( + options: TabAutocompleteOptions, + prefix: string, + suffix: string, + filepath: string, + lang: AutocompleteLanguageInfo, + snippets: AutocompleteSnippet[], + model: string, + workspaceDirs: string[], + userDefinedTemplate: string | undefined, + selectedCompletionInfo: AutocompleteInput["selectedCompletionInfo"], + completeMultiline: boolean, +): [string, Partial | undefined, boolean] { + // Template prompt + let { + template, + completionOptions, + compilePrefixSuffix = undefined, + } = userDefinedTemplate + ? { template: userDefinedTemplate, completionOptions: {} } + : getTemplateForModel(model); + + let prompt: string; + const filename = getBasename(filepath); + const reponame = getBasename(workspaceDirs[0] ?? "myproject"); + + // Some models have prompts that need two passes. This lets us pass the compiled prefix/suffix + // into either the 2nd template to generate a raw string, or to pass prefix, suffix to a FIM endpoint + if (compilePrefixSuffix) { + [prefix, suffix] = compilePrefixSuffix( + prefix, + suffix, + filepath, + reponame, + snippets, + ); + } + + if (typeof template === "string") { + const compiledTemplate = Handlebars.compile(template); + + // Format snippets as comments and prepend to prefix + const formattedSnippets = snippets + .map((snippet) => + formatExternalSnippet(snippet.filepath, snippet.contents, lang), + ) + .join("\n"); + if (formattedSnippets.length > 0) { + prefix = `${formattedSnippets}\n\n${prefix}`; + } else if (prefix.trim().length === 0 && suffix.trim().length === 0) { + // If it's an empty file, include the file name as a comment + prefix = `${lang.singleLineComment} ${getLastNPathParts( + filepath, + 2, + )}\n${prefix}`; + } + + prompt = compiledTemplate({ + prefix, + suffix, + filename, + reponame, + language: lang.name, + }); + } else { + // Let the template function format snippets + prompt = template(prefix, suffix, filepath, reponame, lang.name, snippets); + } + + // Stop tokens + const stopTokens = [ + ...(completionOptions?.stop || []), + // ...multilineStops, + ...commonStops, + ...(model.toLowerCase().includes("starcoder2") + ? STARCODER2_T_ARTIFACTS + : []), + ...(lang.stopWords ?? []), + // ...lang.topLevelKeywords.map((word) => `\n${word}`), + ]; + + const multiline = + !options.transform || + decideMultilineEarly({ + multilineCompletions: options.multilineCompletions, + language: lang, + selectedCompletionInfo: selectedCompletionInfo, + prefix, + suffix, + completeMultiline, + }); + + completionOptions = { + ...completionOptions, + stop: stopTokens, + }; + + return [prompt, completionOptions, multiline]; +} From 4348067e83cacf43d8829083a46a25fbed1ac0e1 Mon Sep 17 00:00:00 2001 From: Pranjal Rana <129268721+PRANJALRANA11@users.noreply.github.com> Date: Thu, 31 Oct 2024 20:51:30 +0530 Subject: [PATCH 17/96] add check for ignore for recently edited file --- core/core.ts | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/core/core.ts b/core/core.ts index 8ce7c7a5d..db965dec1 100644 --- a/core/core.ts +++ b/core/core.ts @@ -29,6 +29,7 @@ import type { IMessenger, Message } from "./util/messenger"; import { editConfigJson, setupInitialDotContinueDirectory } from "./util/paths"; import { Telemetry } from "./util/posthog"; import { TTS } from "./util/tts"; +import { walkDir } from "./indexing/walkDir"; export class Core { // implements IMessenger @@ -704,8 +705,12 @@ export class Core { return { url }; }); - on("didChangeActiveTextEditor", ({ data: { filepath } }) => { - recentlyEditedFilesCache.set(filepath, filepath); + on("didChangeActiveTextEditor", async ({ data: { filepath } }) => { + const dirs = await this.ide.getWorkspaceDirs(); + const paths = await walkDir(dirs[0], this.ide); + if (paths.includes(filepath)) { + recentlyEditedFilesCache.set(filepath, filepath); + } }); } From 34657c80e2c209195a3443033189670b1aab774c Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 31 Oct 2024 12:36:49 -0700 Subject: [PATCH 18/96] allow completion undefined --- core/autocomplete/completionProvider.ts | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/core/autocomplete/completionProvider.ts b/core/autocomplete/completionProvider.ts index 45bf98cd0..f11ce14e0 100644 --- a/core/autocomplete/completionProvider.ts +++ b/core/autocomplete/completionProvider.ts @@ -392,7 +392,7 @@ export class CompletionProvider { ); // Completion - let completion = ""; + let completion: string | undefined = ""; const cache = await autocompleteCache; const cachedCompletion = options.useCache @@ -473,13 +473,15 @@ export class CompletionProvider { }) : completion; - if (!processedCompletion) { - return undefined; - } completion = processedCompletion; } const time = Date.now() - startTime; + + if (!completion) { + return undefined; + } + return { time, completion, From a42d32d168d6bef11ef3384c260061065b6c1ead Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 31 Oct 2024 12:38:58 -0700 Subject: [PATCH 19/96] fix tsc errs --- core/autocomplete/test/util.ts | 3 ++- extensions/vscode/continue_rc_schema.json | 2 +- extensions/vscode/src/autocomplete/completionProvider.ts | 6 +++--- extensions/vscode/src/autocomplete/lsp.ts | 6 +++--- extensions/vscode/src/autocomplete/recentlyEdited.ts | 2 +- 5 files changed, 10 insertions(+), 9 deletions(-) diff --git a/core/autocomplete/test/util.ts b/core/autocomplete/test/util.ts index 60e7b3f93..4b008143f 100644 --- a/core/autocomplete/test/util.ts +++ b/core/autocomplete/test/util.ts @@ -2,7 +2,8 @@ import fs from "node:fs"; import path from "node:path"; import Mock from "../../llm/llms/Mock"; import { testConfigHandler, testIde } from "../../test/util/fixtures"; -import { AutocompleteInput, CompletionProvider } from "../completionProvider"; +import { CompletionProvider } from "../completionProvider"; +import { AutocompleteInput } from "../types"; const FIM_DELIMITER = "<|fim|>"; diff --git a/extensions/vscode/continue_rc_schema.json b/extensions/vscode/continue_rc_schema.json index 1c1610446..6c664ecb0 100644 --- a/extensions/vscode/continue_rc_schema.json +++ b/extensions/vscode/continue_rc_schema.json @@ -3155,7 +3155,7 @@ "transform": { "type": "boolean", "description": "Whether LLM output should be transformed to correct common model pitfalls." - }, + }, "template": { "type": "string", "description": "An optional template string to be used for autocomplete. It will be rendered with the Mustache templating language, and is passed the 'prefix' and 'suffix' variables." diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index 821f215f1..d9244ebfc 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -1,9 +1,9 @@ import type { IDE } from "core"; +import { CompletionProvider } from "core/autocomplete/completionProvider"; import { - AutocompleteOutcome, - CompletionProvider, type AutocompleteInput, -} from "core/autocomplete/completionProvider"; + type AutocompleteOutcome, +} from "core/autocomplete/types"; import { ConfigHandler } from "core/config/ConfigHandler"; import { v4 as uuidv4 } from "uuid"; import * as vscode from "vscode"; diff --git a/extensions/vscode/src/autocomplete/lsp.ts b/extensions/vscode/src/autocomplete/lsp.ts index f24b23bf3..c3382dd99 100644 --- a/extensions/vscode/src/autocomplete/lsp.ts +++ b/extensions/vscode/src/autocomplete/lsp.ts @@ -1,8 +1,8 @@ import type { IDE, Range, RangeInFile } from "core"; -import { getAst, getTreePathAtCursor } from "core/autocomplete/ast"; import { GetLspDefinitionsFunction } from "core/autocomplete/completionProvider"; -import { AutocompleteLanguageInfo } from "core/autocomplete/languages"; -import { AutocompleteSnippet } from "core/autocomplete/ranking"; +import { AutocompleteLanguageInfo } from "core/autocomplete/constants/AutocompleteLanguageInfo"; +import { AutocompleteSnippet } from "core/autocomplete/context/ranking"; +import { getAst, getTreePathAtCursor } from "core/autocomplete/util/ast"; import { RangeInFileWithContents } from "core/commands/util"; import { FUNCTION_BLOCK_NODE_TYPES, diff --git a/extensions/vscode/src/autocomplete/recentlyEdited.ts b/extensions/vscode/src/autocomplete/recentlyEdited.ts index 3c8b4e95f..c32739b1c 100644 --- a/extensions/vscode/src/autocomplete/recentlyEdited.ts +++ b/extensions/vscode/src/autocomplete/recentlyEdited.ts @@ -1,4 +1,4 @@ -import { getSymbolsForSnippet } from "core/autocomplete/ranking"; +import { getSymbolsForSnippet } from "core/autocomplete/context/ranking"; import { RecentlyEditedRange } from "core/autocomplete/recentlyEdited"; import { RangeInFileWithContents } from "core/commands/util"; import * as vscode from "vscode"; From e96bd89ebc614350695c7e48073519e5006c2711 Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 31 Oct 2024 12:48:40 -0700 Subject: [PATCH 20/96] refactor stop words --- core/autocomplete/constants/stopWords.ts | 11 ------- core/autocomplete/templating/getStopTokens.ts | 33 +++++++++++++++++++ core/autocomplete/templating/index.ts | 15 ++------- 3 files changed, 36 insertions(+), 23 deletions(-) delete mode 100644 core/autocomplete/constants/stopWords.ts create mode 100644 core/autocomplete/templating/getStopTokens.ts diff --git a/core/autocomplete/constants/stopWords.ts b/core/autocomplete/constants/stopWords.ts deleted file mode 100644 index 94d29cf40..000000000 --- a/core/autocomplete/constants/stopWords.ts +++ /dev/null @@ -1,11 +0,0 @@ -const DOUBLE_NEWLINE = "\n\n"; -const WINDOWS_DOUBLE_NEWLINE = "\r\n\r\n"; -// TODO: Do we want to stop completions when reaching a `/src/` string? -const SRC_DIRECTORY = "/src/"; -// Starcoder2 tends to output artifacts starting with the letter "t" -const STARCODER2_T_ARTIFACTS = ["t.", "\nt", ""]; -const PYTHON_ENCODING = "#- coding: utf-8"; -const CODE_BLOCK_END = "```"; - -const multilineStops: string[] = [DOUBLE_NEWLINE, WINDOWS_DOUBLE_NEWLINE]; -const commonStops = [SRC_DIRECTORY, PYTHON_ENCODING, CODE_BLOCK_END]; diff --git a/core/autocomplete/templating/getStopTokens.ts b/core/autocomplete/templating/getStopTokens.ts new file mode 100644 index 000000000..fffb5351b --- /dev/null +++ b/core/autocomplete/templating/getStopTokens.ts @@ -0,0 +1,33 @@ +import { CompletionOptions } from "../.."; +import { AutocompleteLanguageInfo } from "../constants/AutocompleteLanguageInfo"; + +const DOUBLE_NEWLINE = "\n\n"; +const WINDOWS_DOUBLE_NEWLINE = "\r\n\r\n"; +// TODO: Do we want to stop completions when reaching a `/src/` string? +const SRC_DIRECTORY = "/src/"; +// Starcoder2 tends to output artifacts starting with the letter "t" +const STARCODER2_T_ARTIFACTS = ["t.", "\nt", ""]; +const PYTHON_ENCODING = "#- coding: utf-8"; +const CODE_BLOCK_END = "```"; + +const multilineStops: string[] = [DOUBLE_NEWLINE, WINDOWS_DOUBLE_NEWLINE]; +const commonStops = [SRC_DIRECTORY, PYTHON_ENCODING, CODE_BLOCK_END]; + +export function getStopTokens( + completionOptions: Partial | undefined, + lang: AutocompleteLanguageInfo, + model: string, +): string[] { + const stopTokens = [ + ...(completionOptions?.stop || []), + // ...multilineStops, + ...commonStops, + ...(model.toLowerCase().includes("starcoder2") + ? STARCODER2_T_ARTIFACTS + : []), + ...(lang.stopWords ?? []), + // ...lang.topLevelKeywords.map((word) => `\n${word}`), + ]; + + return stopTokens; +} diff --git a/core/autocomplete/templating/index.ts b/core/autocomplete/templating/index.ts index e0890ca8b..7d81589a0 100644 --- a/core/autocomplete/templating/index.ts +++ b/core/autocomplete/templating/index.ts @@ -5,6 +5,7 @@ import { AutocompleteLanguageInfo } from "../constants/AutocompleteLanguageInfo" import { AutocompleteSnippet } from "../context/ranking"; import { AutocompleteInput } from "../types"; import { getTemplateForModel } from "./AutocompleteTemplate"; +import { getStopTokens } from "./getStopTokens"; export function formatExternalSnippet( filepath: string, @@ -92,18 +93,6 @@ export function renderPrompt( prompt = template(prefix, suffix, filepath, reponame, lang.name, snippets); } - // Stop tokens - const stopTokens = [ - ...(completionOptions?.stop || []), - // ...multilineStops, - ...commonStops, - ...(model.toLowerCase().includes("starcoder2") - ? STARCODER2_T_ARTIFACTS - : []), - ...(lang.stopWords ?? []), - // ...lang.topLevelKeywords.map((word) => `\n${word}`), - ]; - const multiline = !options.transform || decideMultilineEarly({ @@ -115,6 +104,8 @@ export function renderPrompt( completeMultiline, }); + const stopTokens = getStopTokens(completionOptions, lang, model); + completionOptions = { ...completionOptions, stop: stopTokens, From ebae6597382bd8676ff65588f56d53953deeccd1 Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 31 Oct 2024 12:53:15 -0700 Subject: [PATCH 21/96] rename completionProvider --- ...etionProvider.ts => CompletionProvider.ts} | 0 core/autocomplete/templating/index.ts | 68 ++++++++++++------- 2 files changed, 43 insertions(+), 25 deletions(-) rename core/autocomplete/{completionProvider.ts => CompletionProvider.ts} (100%) diff --git a/core/autocomplete/completionProvider.ts b/core/autocomplete/CompletionProvider.ts similarity index 100% rename from core/autocomplete/completionProvider.ts rename to core/autocomplete/CompletionProvider.ts diff --git a/core/autocomplete/templating/index.ts b/core/autocomplete/templating/index.ts index 7d81589a0..46ac9432d 100644 --- a/core/autocomplete/templating/index.ts +++ b/core/autocomplete/templating/index.ts @@ -23,7 +23,43 @@ export function formatExternalSnippet( ]; return lines.join("\n"); } +function renderStringTemplate( + template: string, + prefix: string, + suffix: string, + snippets: AutocompleteSnippet[], + lang: AutocompleteLanguageInfo, + filepath: string, + reponame: string, +) { + const filename = getBasename(filepath); + const compiledTemplate = Handlebars.compile(template); + // Format snippets as comments and prepend to prefix + const formattedSnippets = snippets + .map((snippet) => + formatExternalSnippet(snippet.filepath, snippet.contents, lang), + ) + .join("\n"); + if (formattedSnippets.length > 0) { + prefix = `${formattedSnippets}\n\n${prefix}`; + } else if (prefix.trim().length === 0 && suffix.trim().length === 0) { + // If it's an empty file, include the file name as a comment + prefix = `${lang.singleLineComment} ${getLastNPathParts( + filepath, + 2, + )}\n${prefix}`; + } + + const prompt = compiledTemplate({ + prefix, + suffix, + filename, + reponame, + language: lang.name, + }); + return prompt; +} export function renderPrompt( options: TabAutocompleteOptions, prefix: string, @@ -37,7 +73,6 @@ export function renderPrompt( selectedCompletionInfo: AutocompleteInput["selectedCompletionInfo"], completeMultiline: boolean, ): [string, Partial | undefined, boolean] { - // Template prompt let { template, completionOptions, @@ -47,7 +82,6 @@ export function renderPrompt( : getTemplateForModel(model); let prompt: string; - const filename = getBasename(filepath); const reponame = getBasename(workspaceDirs[0] ?? "myproject"); // Some models have prompts that need two passes. This lets us pass the compiled prefix/suffix @@ -62,34 +96,18 @@ export function renderPrompt( ); } + // Templates can be passed as a Handlebars template string or a function if (typeof template === "string") { - const compiledTemplate = Handlebars.compile(template); - - // Format snippets as comments and prepend to prefix - const formattedSnippets = snippets - .map((snippet) => - formatExternalSnippet(snippet.filepath, snippet.contents, lang), - ) - .join("\n"); - if (formattedSnippets.length > 0) { - prefix = `${formattedSnippets}\n\n${prefix}`; - } else if (prefix.trim().length === 0 && suffix.trim().length === 0) { - // If it's an empty file, include the file name as a comment - prefix = `${lang.singleLineComment} ${getLastNPathParts( - filepath, - 2, - )}\n${prefix}`; - } - - prompt = compiledTemplate({ + prompt = renderStringTemplate( + template, prefix, suffix, - filename, + snippets, + lang, + filepath, reponame, - language: lang.name, - }); + ); } else { - // Let the template function format snippets prompt = template(prefix, suffix, filepath, reponame, lang.name, snippets); } From 9a92ab4933edf97135016ced232e2c05a599646f Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 31 Oct 2024 12:55:22 -0700 Subject: [PATCH 22/96] fix casing --- core/autocomplete/filtering/test/util.ts | 2 +- core/autocomplete/test/util.ts | 2 +- core/core.ts | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/core/autocomplete/filtering/test/util.ts b/core/autocomplete/filtering/test/util.ts index 37890e1e8..f8564e258 100644 --- a/core/autocomplete/filtering/test/util.ts +++ b/core/autocomplete/filtering/test/util.ts @@ -2,7 +2,7 @@ import fs from "node:fs"; import path from "node:path"; import Mock from "../../../llm/llms/Mock"; import { testConfigHandler, testIde } from "../../../test/util/fixtures"; -import { CompletionProvider } from "../../completionProvider"; +import { CompletionProvider } from "../../CompletionProvider"; import { AutocompleteInput } from "../../types"; const FIM_DELIMITER = "<|fim|>"; diff --git a/core/autocomplete/test/util.ts b/core/autocomplete/test/util.ts index 4b008143f..85dbc60b3 100644 --- a/core/autocomplete/test/util.ts +++ b/core/autocomplete/test/util.ts @@ -2,7 +2,7 @@ import fs from "node:fs"; import path from "node:path"; import Mock from "../../llm/llms/Mock"; import { testConfigHandler, testIde } from "../../test/util/fixtures"; -import { CompletionProvider } from "../completionProvider"; +import { CompletionProvider } from "../CompletionProvider"; import { AutocompleteInput } from "../types"; const FIM_DELIMITER = "<|fim|>"; diff --git a/core/core.ts b/core/core.ts index 8ce7c7a5d..d7bd1846f 100644 --- a/core/core.ts +++ b/core/core.ts @@ -1,6 +1,6 @@ import { v4 as uuidv4 } from "uuid"; import type { ContextItemId, IDE, IndexingProgressUpdate } from "."; -import { CompletionProvider } from "./autocomplete/completionProvider"; +import { CompletionProvider } from "./autocomplete/CompletionProvider"; import { ConfigHandler } from "./config/ConfigHandler"; import { setupBestConfig, From 70eeddcd1744ef5fd1eec85d9771efabaeb53b80 Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 31 Oct 2024 13:50:29 -0700 Subject: [PATCH 23/96] HelperVars --- core/autocomplete/CompletionProvider.ts | 154 +++++++----------- core/autocomplete/HelperVars.ts | 61 +++++++ core/autocomplete/constructPrompt.ts | 78 +++++---- core/autocomplete/prefiltering/index.ts | 42 ++--- .../templating/constructPrefixSuffix.ts | 43 +++++ core/autocomplete/templating/index.ts | 46 +++--- 6 files changed, 248 insertions(+), 176 deletions(-) create mode 100644 core/autocomplete/HelperVars.ts create mode 100644 core/autocomplete/templating/constructPrefixSuffix.ts diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts index f11ce14e0..5ec075c6d 100644 --- a/core/autocomplete/CompletionProvider.ts +++ b/core/autocomplete/CompletionProvider.ts @@ -1,18 +1,14 @@ import { ConfigHandler } from "../config/ConfigHandler.js"; -import { IDE, ILLM, TabAutocompleteOptions } from "../index.js"; +import { IDE, ILLM } from "../index.js"; import { logDevData } from "../util/devdata.js"; import { COUNT_COMPLETION_REJECTED_AFTER, DEFAULT_AUTOCOMPLETE_OPTS, } from "../util/parameters.js"; import { Telemetry } from "../util/posthog.js"; -import { getRangeInString } from "../util/ranges.js"; import { AutocompleteLanguageInfo } from "./constants/AutocompleteLanguageInfo.js"; -import { - constructAutocompletePrompt, - languageForFilepath, -} from "./constructPrompt.js"; +import { constructAutocompletePrompt } from "./constructPrompt.js"; import { AutocompleteSnippet } from "./context/ranking/index.js"; import { RootPathContextService } from "./context/RootPathContextService.js"; import { GeneratorReuseManager } from "./generation/GeneratorReuseManager.js"; @@ -25,7 +21,9 @@ import AutocompleteLruCache from "./AutocompleteLruCache.js"; import { ImportDefinitionsService } from "./context/ImportDefinitionsService.js"; import { BracketMatchingService } from "./filtering/BracketMatchingService.js"; import { StreamTransformPipeline } from "./filtering/streamTransforms/StreamTransformPipeline.js"; +import { HelperVars } from "./HelperVars.js"; import { shouldPrefilter } from "./prefiltering/index.js"; +import { constructInitialPrefixSuffix } from "./templating/constructPrefixSuffix.js"; import { renderPrompt } from "./templating/index.js"; import { AutocompleteInput, AutocompleteOutcome } from "./types.js"; @@ -199,9 +197,15 @@ export class CompletionProvider { token: AbortSignal | undefined, ): Promise { try { - const options = await this._getAutocompleteOptions(); + const llm = await this._prepareLlm(); + if (!llm) { + return undefined; + } - if (await shouldPrefilter(input, options, this.ide)) { + const options = await this._getAutocompleteOptions(); + const helper = new HelperVars(input, options, llm.model, this.ide); + + if (await shouldPrefilter(helper, this.ide)) { return undefined; } @@ -211,10 +215,6 @@ export class CompletionProvider { } // Get completion - const llm = await this._prepareLlm(); - if (!llm) { - return undefined; - } // Create abort signal if not given if (!token) { @@ -223,7 +223,7 @@ export class CompletionProvider { this._abortControllers.set(input.completionId, controller); } - const outcome = await this.getTabCompletion(token, options, llm, input); + const outcome = await this.getTabCompletion(token, llm, helper); if (!outcome?.completion) { return undefined; @@ -287,59 +287,19 @@ export class CompletionProvider { }; } - async getTabCompletion( - token: AbortSignal, - options: TabAutocompleteOptions, - llm: ILLM, - input: AutocompleteInput, - ): Promise { - const startTime = Date.now(); - - const { - filepath, - pos, - recentlyEditedFiles, - recentlyEditedRanges, - clipboardText, - manuallyPassFileContents, - manuallyPassPrefix, - } = input; - const fileContents = - manuallyPassFileContents ?? (await this.ide.readFile(filepath)); - const fileLines = fileContents.split("\n"); - - // Filter - const lang = languageForFilepath(filepath); - - // Prompt - let fullPrefix = - getRangeInString(fileContents, { - start: { line: 0, character: 0 }, - end: input.selectedCompletionInfo?.range.start ?? pos, - }) + (input.selectedCompletionInfo?.text ?? ""); - - if (input.injectDetails) { - const lines = fullPrefix.split("\n"); - fullPrefix = `${lines.slice(0, -1).join("\n")}\n${ - lang.singleLineComment - } ${input.injectDetails - .split("\n") - .join(`\n${lang.singleLineComment} `)}\n${lines[lines.length - 1]}`; - } - - const fullSuffix = getRangeInString(fileContents, { - start: pos, - end: { line: fileLines.length - 1, character: Number.MAX_SAFE_INTEGER }, - }); - - let extrasSnippets = options.useOtherFiles + private async _getExtraSnippets( + helper: HelperVars, + fullPrefix: string, + fullSuffix: string, + ): Promise { + let extraSnippets = helper.options.useOtherFiles ? ((await Promise.race([ this.getDefinitionsFromLsp( - filepath, + helper.input.filepath, fullPrefix + fullSuffix, fullPrefix.length, this.ide, - lang, + helper.lang, ), new Promise((resolve) => { setTimeout(() => resolve([]), 100); @@ -348,54 +308,64 @@ export class CompletionProvider { : []; const workspaceDirs = await this.ide.getWorkspaceDirs(); - if (options.onlyMyCode) { - extrasSnippets = extrasSnippets.filter((snippet) => { + if (helper.options.onlyMyCode) { + extraSnippets = extraSnippets.filter((snippet) => { return workspaceDirs.some((dir) => snippet.filepath.startsWith(dir)); }); } + return extraSnippets; + } + + async getTabCompletion( + token: AbortSignal, + llm: ILLM, + helper: HelperVars, + ): Promise { + const startTime = Date.now(); + + // Construct full prefix/suffix (a few edge cases handled in here) + const { prefix: fullPrefix, suffix: fullSuffix } = + await constructInitialPrefixSuffix(helper.input, this.ide); + + // Some IDEs might have special ways of finding snippets (e.g. JetBrains and VS Code have different "LSP-equivalent" systems, + // or they might separately track recently edited ranges) + const extraSnippets = await this._getExtraSnippets( + helper, + fullPrefix, + fullSuffix, + ); + let { prefix, suffix, completeMultiline, snippets } = await constructAutocompletePrompt( - filepath, - pos.line, fullPrefix, fullSuffix, - clipboardText, - lang, - options, - recentlyEditedRanges, - recentlyEditedFiles, - llm.model, - extrasSnippets, + helper, + extraSnippets, this.importDefinitionsService, this.rootPathContextService, ); // If prefix is manually passed - if (manuallyPassPrefix) { - prefix = manuallyPassPrefix; + if (helper.input.manuallyPassPrefix) { + prefix = helper.input.manuallyPassPrefix; suffix = ""; } const [prompt, completionOptions, multiline] = renderPrompt( - options, prefix, suffix, - filepath, - lang, snippets, - llm.model, - workspaceDirs, - options.template, - input.selectedCompletionInfo, + await this.ide.getWorkspaceDirs(), completeMultiline, + helper, ); // Completion let completion: string | undefined = ""; const cache = await autocompleteCache; - const cachedCompletion = options.useCache + const cachedCompletion = helper.options.useCache ? await cache.get(prefix) : undefined; let cacheHit = false; @@ -434,17 +404,17 @@ export class CompletionProvider { }; const initialGenerator = generatorWithCancellation(); - const finalGenerator = options.transform + const finalGenerator = helper.options.transform ? this.streamTransformPipeline.transform( initialGenerator, prefix, suffix, - filepath, + helper.filepath, multiline, - pos, - fileLines, + helper.pos, + helper.fileLines, completionOptions?.stop || [], - lang, + helper.lang, fullStop, ) : initialGenerator; @@ -464,7 +434,7 @@ export class CompletionProvider { return undefined; } - const processedCompletion = options.transform + const processedCompletion = helper.options.transform ? postprocessCompletion({ completion, prefix, @@ -492,11 +462,11 @@ export class CompletionProvider { modelName: llm.model, completionOptions, cacheHit, - filepath: input.filepath, - completionId: input.completionId, - gitRepo: await this.ide.getRepoName(input.filepath), + filepath: helper.filepath, + completionId: helper.input.completionId, + gitRepo: await this.ide.getRepoName(helper.filepath), uniqueId: await this.ide.getUniqueId(), - ...options, + ...helper.options, }; } } diff --git a/core/autocomplete/HelperVars.ts b/core/autocomplete/HelperVars.ts new file mode 100644 index 000000000..124389509 --- /dev/null +++ b/core/autocomplete/HelperVars.ts @@ -0,0 +1,61 @@ +import { IDE, TabAutocompleteOptions } from ".."; +import { AutocompleteLanguageInfo } from "./constants/AutocompleteLanguageInfo"; +import { languageForFilepath } from "./constructPrompt"; +import { AutocompleteInput } from "./types"; + +/** + * A collection of variables that are often accessed throughout the autocomplete pipeline + * It's noisy to re-calculate all the time or inject them into each function + */ +export class HelperVars { + lang: AutocompleteLanguageInfo; + private _fileContents: string | undefined; + private _fileLines: string[] | undefined; + + constructor( + public readonly input: AutocompleteInput, + public readonly options: TabAutocompleteOptions, + public readonly modelName: string, + private readonly ide: IDE, + ) { + this.lang = languageForFilepath(input.filepath); + } + + async init() { + // Don't do anything if already initialized + if (this._fileContents !== undefined) return; + + this._fileContents = + this.input.manuallyPassFileContents ?? + (await this.ide.readFile(this.filepath)); + + this._fileLines = this._fileContents.split("\n"); + } + + // Fast access + get filepath() { + return this.input.filepath; + } + get pos() { + return this.input.pos; + } + + // Getters for lazy access + get fileContents(): string { + if (this._fileContents === undefined) { + throw new Error( + "HelperVars must be initialized before accessing fileContents", + ); + } + return this._fileContents; + } + + get fileLines(): string[] { + if (this._fileLines === undefined) { + throw new Error( + "HelperVars must be initialized before accessing fileLines", + ); + } + return this._fileLines; + } +} diff --git a/core/autocomplete/constructPrompt.ts b/core/autocomplete/constructPrompt.ts index 889db0d76..cbef4949b 100644 --- a/core/autocomplete/constructPrompt.ts +++ b/core/autocomplete/constructPrompt.ts @@ -1,6 +1,3 @@ -import { RangeInFileWithContents } from "../commands/util.js"; -import { TabAutocompleteOptions } from "../index.js"; - import { countTokens, pruneLinesFromBottom, @@ -21,7 +18,8 @@ import { type AutocompleteSnippet, } from "./context/ranking/index.js"; import { RootPathContextService } from "./context/RootPathContextService.js"; -import { RecentlyEditedRange, findMatchingRange } from "./recentlyEdited.js"; +import { HelperVars } from "./HelperVars.js"; +import { findMatchingRange } from "./recentlyEdited.js"; import { AstPath, getAst, getTreePathAtCursor } from "./util/ast.js"; export function languageForFilepath( @@ -31,16 +29,9 @@ export function languageForFilepath( } export async function constructAutocompletePrompt( - filepath: string, - cursorLine: number, fullPrefix: string, fullSuffix: string, - clipboardText: string, - language: AutocompleteLanguageInfo, - options: TabAutocompleteOptions, - recentlyEditedRanges: RecentlyEditedRange[], - recentlyEditedFiles: RangeInFileWithContents[], - modelName: string, + helper: HelperVars, extraSnippets: AutocompleteSnippet[], importDefinitionsService: ImportDefinitionsService, rootPathContextService: RootPathContextService, @@ -52,20 +43,29 @@ export async function constructAutocompletePrompt( snippets: AutocompleteSnippet[]; }> { // Construct basic prefix - const maxPrefixTokens = options.maxPromptTokens * options.prefixPercentage; - const prefix = pruneLinesFromTop(fullPrefix, maxPrefixTokens, modelName); + const maxPrefixTokens = + helper.options.maxPromptTokens * helper.options.prefixPercentage; + const prefix = pruneLinesFromTop( + fullPrefix, + maxPrefixTokens, + helper.modelName, + ); // Construct suffix const maxSuffixTokens = Math.min( - options.maxPromptTokens - countTokens(prefix, modelName), - options.maxSuffixPercentage * options.maxPromptTokens, + helper.options.maxPromptTokens - countTokens(prefix, helper.modelName), + helper.options.maxSuffixPercentage * helper.options.maxPromptTokens, + ); + const suffix = pruneLinesFromBottom( + fullSuffix, + maxSuffixTokens, + helper.modelName, ); - const suffix = pruneLinesFromBottom(fullSuffix, maxSuffixTokens, modelName); // Calculate AST Path let treePath: AstPath | undefined; try { - const ast = await getAst(filepath, fullPrefix + fullSuffix); + const ast = await getAst(helper.filepath, fullPrefix + fullSuffix); if (ast) { treePath = await getTreePathAtCursor(ast, fullPrefix.length); } @@ -76,15 +76,17 @@ export async function constructAutocompletePrompt( // Find external snippets let snippets: AutocompleteSnippet[] = []; - if (options.useOtherFiles) { + if (helper.options.useOtherFiles) { snippets.push(...extraSnippets); const windowAroundCursor = fullPrefix.slice( - -options.slidingWindowSize * options.slidingWindowPrefixPercentage, + -helper.options.slidingWindowSize * + helper.options.slidingWindowPrefixPercentage, ) + fullSuffix.slice( - options.slidingWindowSize * (1 - options.slidingWindowPrefixPercentage), + helper.options.slidingWindowSize * + (1 - helper.options.slidingWindowPrefixPercentage), ); // This was much too slow, and not super useful @@ -103,11 +105,14 @@ export async function constructAutocompletePrompt( // })), // ); - if (options.useRecentlyEdited) { + if (helper.options.useRecentlyEdited) { const currentLinePrefix = prefix.trim().split("\n").slice(-1)[0]; - if (currentLinePrefix?.length > options.recentLinePrefixMatchMinLength) { + if ( + currentLinePrefix?.length > + helper.options.recentLinePrefixMatchMinLength + ) { const matchingRange = findMatchingRange( - recentlyEditedRanges, + helper.input.recentlyEditedRanges, currentLinePrefix, ); if (matchingRange) { @@ -121,9 +126,9 @@ export async function constructAutocompletePrompt( } // Use imports - if (options.useImports) { + if (helper.options.useImports) { const importSnippets = []; - const fileInfo = importDefinitionsService.get(filepath); + const fileInfo = importDefinitionsService.get(helper.filepath); if (fileInfo) { const { imports } = fileInfo; // Look for imports of any symbols around the current range @@ -132,7 +137,7 @@ export async function constructAutocompletePrompt( fullSuffix.split("\n").slice(0, 3).join("\n"); const symbols = Array.from( getSymbolsForSnippet(textAroundCursor), - ).filter((symbol) => !language.topLevelKeywords.includes(symbol)); + ).filter((symbol) => !helper.lang.topLevelKeywords.includes(symbol)); for (const symbol of symbols) { const rifs = imports[symbol]; if (Array.isArray(rifs)) { @@ -143,9 +148,9 @@ export async function constructAutocompletePrompt( snippets.push(...importSnippets); } - if (options.useRootPathContext && treePath) { + if (helper.options.useRootPathContext && treePath) { const ctx = await rootPathContextService.getContextForPath( - filepath, + helper.filepath, treePath, ); snippets.push(...ctx); @@ -165,7 +170,7 @@ export async function constructAutocompletePrompt( // Fill maxSnippetTokens with snippets const maxSnippetTokens = - options.maxPromptTokens * options.maxSnippetPercentage; + helper.options.maxPromptTokens * helper.options.maxSnippetPercentage; // Remove prefix range from snippets const prefixLines = prefix.split("\n").length; @@ -173,28 +178,29 @@ export async function constructAutocompletePrompt( const buffer = 8; const prefixSuffixRangeWithBuffer = { start: { - line: cursorLine - prefixLines - buffer, + line: helper.pos.line - prefixLines - buffer, character: 0, }, end: { - line: cursorLine + suffixLines + buffer, + line: helper.pos.line + suffixLines + buffer, character: 0, }, }; let finalSnippets = removeRangeFromSnippets( scoredSnippets, - filepath.split("://").slice(-1)[0], + helper.filepath.split("://").slice(-1)[0], prefixSuffixRangeWithBuffer, ); // Filter snippets for those with best scores (must be above threshold) finalSnippets = finalSnippets.filter( - (snippet) => snippet.score >= options.recentlyEditedSimilarityThreshold, + (snippet) => + snippet.score >= helper.options.recentlyEditedSimilarityThreshold, ); finalSnippets = fillPromptWithSnippets( scoredSnippets, maxSnippetTokens, - modelName, + helper.modelName, ); snippets = finalSnippets; @@ -208,7 +214,7 @@ export async function constructAutocompletePrompt( treePath, fullPrefix, fullSuffix, - language, + helper.lang, ), snippets, }; diff --git a/core/autocomplete/prefiltering/index.ts b/core/autocomplete/prefiltering/index.ts index 1d8d089c9..45b521511 100644 --- a/core/autocomplete/prefiltering/index.ts +++ b/core/autocomplete/prefiltering/index.ts @@ -1,9 +1,8 @@ import path from "node:path"; -import { IDE, Position, TabAutocompleteOptions } from "../.."; +import { IDE } from "../.."; import { getBasename } from "../../util"; import { getConfigJsonPath } from "../../util/paths"; -import { languageForFilepath } from "../constructPrompt"; -import { AutocompleteInput } from "../types"; +import { HelperVars } from "../HelperVars"; async function isDisabledForFile( currentFilepath: string, @@ -38,52 +37,39 @@ async function isDisabledForFile( } } -async function shouldLanguageSpecificPrefilter( - manuallyPassFileContents: string | undefined, - filepath: string, - pos: Position, - ide: IDE, -) { - const lang = languageForFilepath(filepath); - const fileContents = - manuallyPassFileContents ?? (await ide.readFile(filepath)); - const fileLines = fileContents.split("\n"); - const line = fileLines[pos.line] ?? ""; - for (const endOfLine of lang.endOfLine) { - if (line.endsWith(endOfLine) && pos.character >= line.length) { +async function shouldLanguageSpecificPrefilter(helper: HelperVars) { + const line = helper.fileLines[helper.pos.line] ?? ""; + for (const endOfLine of helper.lang.endOfLine) { + if (line.endsWith(endOfLine) && helper.pos.character >= line.length) { return true; } } } export async function shouldPrefilter( - input: AutocompleteInput, - options: TabAutocompleteOptions, + helper: HelperVars, ide: IDE, ): Promise { // Allow disabling autocomplete from config.json - if (options.disable) { + if (helper.options.disable) { return true; } // Check whether we're in the continue config.json file - if (input.filepath === getConfigJsonPath()) { + if (helper.filepath === getConfigJsonPath()) { return true; } // Check whether autocomplete is disabled for this file - if (await isDisabledForFile(input.filepath, options.disableInFiles, ide)) { + if ( + await isDisabledForFile(helper.filepath, helper.options.disableInFiles, ide) + ) { return true; } if ( - options.transform && - (await shouldLanguageSpecificPrefilter( - input.manuallyPassFileContents, - input.filepath, - input.pos, - ide, - )) + helper.options.transform && + (await shouldLanguageSpecificPrefilter(helper)) ) { return true; } diff --git a/core/autocomplete/templating/constructPrefixSuffix.ts b/core/autocomplete/templating/constructPrefixSuffix.ts new file mode 100644 index 000000000..cead471c3 --- /dev/null +++ b/core/autocomplete/templating/constructPrefixSuffix.ts @@ -0,0 +1,43 @@ +import { IDE } from "../.."; +import { getRangeInString } from "../../util/ranges"; +import { languageForFilepath } from "../constructPrompt"; +import { AutocompleteInput } from "../types"; + +/** + * We have to handle a few edge cases in getting the entire prefix/suffix for the current file. + * This is entirely prior to finding snippets from other files + */ +export async function constructInitialPrefixSuffix( + input: AutocompleteInput, + ide: IDE, +): Promise<{ + prefix: string; + suffix: string; +}> { + const lang = languageForFilepath(input.filepath); + + const fileContents = + input.manuallyPassFileContents ?? (await ide.readFile(input.filepath)); + const fileLines = fileContents.split("\n"); + let prefix = + getRangeInString(fileContents, { + start: { line: 0, character: 0 }, + end: input.selectedCompletionInfo?.range.start ?? input.pos, + }) + (input.selectedCompletionInfo?.text ?? ""); + + if (input.injectDetails) { + const lines = prefix.split("\n"); + prefix = `${lines.slice(0, -1).join("\n")}\n${ + lang.singleLineComment + } ${input.injectDetails + .split("\n") + .join(`\n${lang.singleLineComment} `)}\n${lines[lines.length - 1]}`; + } + + const suffix = getRangeInString(fileContents, { + start: input.pos, + end: { line: fileLines.length - 1, character: Number.MAX_SAFE_INTEGER }, + }); + + return { prefix, suffix }; +} diff --git a/core/autocomplete/templating/index.ts b/core/autocomplete/templating/index.ts index 46ac9432d..ad9dc7391 100644 --- a/core/autocomplete/templating/index.ts +++ b/core/autocomplete/templating/index.ts @@ -1,9 +1,9 @@ -import { CompletionOptions, TabAutocompleteOptions } from "../.."; +import { CompletionOptions } from "../.."; import { getBasename, getLastNPathParts } from "../../util"; import { decideMultilineEarly } from "../classification/shouldCompleteMultiline"; import { AutocompleteLanguageInfo } from "../constants/AutocompleteLanguageInfo"; import { AutocompleteSnippet } from "../context/ranking"; -import { AutocompleteInput } from "../types"; +import { HelperVars } from "../HelperVars"; import { getTemplateForModel } from "./AutocompleteTemplate"; import { getStopTokens } from "./getStopTokens"; @@ -61,25 +61,20 @@ function renderStringTemplate( return prompt; } export function renderPrompt( - options: TabAutocompleteOptions, prefix: string, suffix: string, - filepath: string, - lang: AutocompleteLanguageInfo, snippets: AutocompleteSnippet[], - model: string, workspaceDirs: string[], - userDefinedTemplate: string | undefined, - selectedCompletionInfo: AutocompleteInput["selectedCompletionInfo"], completeMultiline: boolean, + helper: HelperVars, ): [string, Partial | undefined, boolean] { let { template, completionOptions, compilePrefixSuffix = undefined, - } = userDefinedTemplate - ? { template: userDefinedTemplate, completionOptions: {} } - : getTemplateForModel(model); + } = helper.options.template + ? { template: helper.options.template, completionOptions: {} } + : getTemplateForModel(helper.modelName); let prompt: string; const reponame = getBasename(workspaceDirs[0] ?? "myproject"); @@ -90,7 +85,7 @@ export function renderPrompt( [prefix, suffix] = compilePrefixSuffix( prefix, suffix, - filepath, + helper.filepath, reponame, snippets, ); @@ -103,26 +98,37 @@ export function renderPrompt( prefix, suffix, snippets, - lang, - filepath, + helper.lang, + helper.filepath, reponame, ); } else { - prompt = template(prefix, suffix, filepath, reponame, lang.name, snippets); + prompt = template( + prefix, + suffix, + helper.filepath, + reponame, + helper.lang.name, + snippets, + ); } const multiline = - !options.transform || + !helper.options.transform || decideMultilineEarly({ - multilineCompletions: options.multilineCompletions, - language: lang, - selectedCompletionInfo: selectedCompletionInfo, + multilineCompletions: helper.options.multilineCompletions, + language: helper.lang, + selectedCompletionInfo: helper.input.selectedCompletionInfo, prefix, suffix, completeMultiline, }); - const stopTokens = getStopTokens(completionOptions, lang, model); + const stopTokens = getStopTokens( + completionOptions, + helper.lang, + helper.modelName, + ); completionOptions = { ...completionOptions, From 4b15d00802fbcc7376a5edf194a09435efac2eac Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 31 Oct 2024 14:15:00 -0700 Subject: [PATCH 24/96] more refactoring --- core/autocomplete/CompletionProvider.ts | 277 +++++++----------- .../generation/CompletionStreamer.ts | 67 +++++ 2 files changed, 178 insertions(+), 166 deletions(-) create mode 100644 core/autocomplete/generation/CompletionStreamer.ts diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts index 5ec075c6d..665e88513 100644 --- a/core/autocomplete/CompletionProvider.ts +++ b/core/autocomplete/CompletionProvider.ts @@ -11,7 +11,6 @@ import { AutocompleteLanguageInfo } from "./constants/AutocompleteLanguageInfo.j import { constructAutocompletePrompt } from "./constructPrompt.js"; import { AutocompleteSnippet } from "./context/ranking/index.js"; import { RootPathContextService } from "./context/RootPathContextService.js"; -import { GeneratorReuseManager } from "./generation/GeneratorReuseManager.js"; import { postprocessCompletion } from "./postprocessing/index.js"; // @prettier-ignore import { TRIAL_FIM_MODEL } from "../config/onboarding.js"; @@ -20,7 +19,7 @@ import { AutocompleteDebouncer } from "./AutocompleteDebouncer.js"; import AutocompleteLruCache from "./AutocompleteLruCache.js"; import { ImportDefinitionsService } from "./context/ImportDefinitionsService.js"; import { BracketMatchingService } from "./filtering/BracketMatchingService.js"; -import { StreamTransformPipeline } from "./filtering/streamTransforms/StreamTransformPipeline.js"; +import { CompletionStreamer } from "./generation/CompletionStreamer.js"; import { HelperVars } from "./HelperVars.js"; import { shouldPrefilter } from "./prefiltering/index.js"; import { constructInitialPrefixSuffix } from "./templating/constructPrefixSuffix.js"; @@ -47,13 +46,11 @@ export type GetLspDefinitionsFunction = ( export class CompletionProvider { private importDefinitionsService: ImportDefinitionsService; private rootPathContextService: RootPathContextService; - private generatorReuseManager: GeneratorReuseManager; private autocompleteCache = AutocompleteLruCache.get(); public errorsShown: Set = new Set(); private bracketMatchingService = new BracketMatchingService(); private debouncer = new AutocompleteDebouncer(); - private streamTransformPipeline = new StreamTransformPipeline(); - // private nearbyDefinitionsService = new NearbyDefinitionsService(); + private completionStreamer: CompletionStreamer; constructor( private readonly configHandler: ConfigHandler, @@ -62,9 +59,7 @@ export class CompletionProvider { private readonly _onError: (e: any) => void, private readonly getDefinitionsFromLsp: GetLspDefinitionsFunction, ) { - this.generatorReuseManager = new GeneratorReuseManager( - this.onError.bind(this), - ); + this.completionStreamer = new CompletionStreamer(this.onError.bind(this)); this.importDefinitionsService = new ImportDefinitionsService(this.ide); this.rootPathContextService = new RootPathContextService( this.importDefinitionsService, @@ -103,7 +98,6 @@ export class CompletionProvider { } private onError(e: any) { - console.warn("Error generating autocompletion: ", e); if ( ERRORS_TO_IGNORE.some((err) => typeof e === "string" ? e.includes(err) : e?.message?.includes(err), @@ -111,6 +105,8 @@ export class CompletionProvider { ) { return; } + + console.warn("Error generating autocompletion: ", e); if (!this.errorsShown.has(e.message)) { this.errorsShown.add(e.message); this._onError(e); @@ -197,6 +193,8 @@ export class CompletionProvider { token: AbortSignal | undefined, ): Promise { try { + const startTime = Date.now(); + const llm = await this._prepareLlm(); if (!llm) { return undefined; @@ -214,8 +212,6 @@ export class CompletionProvider { return undefined; } - // Get completion - // Create abort signal if not given if (!token) { const controller = new AbortController(); @@ -223,12 +219,114 @@ export class CompletionProvider { this._abortControllers.set(input.completionId, controller); } - const outcome = await this.getTabCompletion(token, llm, helper); + ////////// - if (!outcome?.completion) { + // Construct full prefix/suffix (a few edge cases handled in here) + const { prefix: fullPrefix, suffix: fullSuffix } = + await constructInitialPrefixSuffix(helper.input, this.ide); + + // Some IDEs might have special ways of finding snippets (e.g. JetBrains and VS Code have different "LSP-equivalent" systems, + // or they might separately track recently edited ranges) + const extraSnippets = await this._getExtraSnippets( + helper, + fullPrefix, + fullSuffix, + ); + + let { prefix, suffix, completeMultiline, snippets } = + await constructAutocompletePrompt( + fullPrefix, + fullSuffix, + helper, + extraSnippets, + this.importDefinitionsService, + this.rootPathContextService, + ); + + // If prefix is manually passed + if (helper.input.manuallyPassPrefix) { + prefix = helper.input.manuallyPassPrefix; + suffix = ""; + } + + const [prompt, completionOptions, multiline] = renderPrompt( + prefix, + suffix, + snippets, + await this.ide.getWorkspaceDirs(), + completeMultiline, + helper, + ); + + // Completion + let completion: string | undefined = ""; + + const cache = await autocompleteCache; + const cachedCompletion = helper.options.useCache + ? await cache.get(prefix) + : undefined; + let cacheHit = false; + if (cachedCompletion) { + // Cache + cacheHit = true; + completion = cachedCompletion; + } else { + const completionStream = + this.completionStreamer.streamCompletionWithFilters( + token, + llm, + prefix, + suffix, + prompt, + multiline, + completionOptions, + helper, + ); + + for await (const update of completionStream) { + completion += update; + } + + // Don't postprocess if aborted + if (token.aborted) { + return undefined; + } + + const processedCompletion = helper.options.transform + ? postprocessCompletion({ + completion, + prefix, + suffix, + llm, + }) + : completion; + + completion = processedCompletion; + } + + if (!completion) { return undefined; } + const outcome: AutocompleteOutcome = { + time: Date.now() - startTime, + completion, + prefix, + suffix, + prompt, + modelProvider: llm.providerName, + modelName: llm.model, + completionOptions, + cacheHit, + filepath: helper.filepath, + completionId: helper.input.completionId, + gitRepo: await this.ide.getRepoName(helper.filepath), + uniqueId: await this.ide.getUniqueId(), + ...helper.options, + }; + + ////////// + // Do some stuff later so as not to block return. Latency matters const completionToCache = outcome.completion; setTimeout(async () => { @@ -316,157 +414,4 @@ export class CompletionProvider { return extraSnippets; } - - async getTabCompletion( - token: AbortSignal, - llm: ILLM, - helper: HelperVars, - ): Promise { - const startTime = Date.now(); - - // Construct full prefix/suffix (a few edge cases handled in here) - const { prefix: fullPrefix, suffix: fullSuffix } = - await constructInitialPrefixSuffix(helper.input, this.ide); - - // Some IDEs might have special ways of finding snippets (e.g. JetBrains and VS Code have different "LSP-equivalent" systems, - // or they might separately track recently edited ranges) - const extraSnippets = await this._getExtraSnippets( - helper, - fullPrefix, - fullSuffix, - ); - - let { prefix, suffix, completeMultiline, snippets } = - await constructAutocompletePrompt( - fullPrefix, - fullSuffix, - helper, - extraSnippets, - this.importDefinitionsService, - this.rootPathContextService, - ); - - // If prefix is manually passed - if (helper.input.manuallyPassPrefix) { - prefix = helper.input.manuallyPassPrefix; - suffix = ""; - } - - const [prompt, completionOptions, multiline] = renderPrompt( - prefix, - suffix, - snippets, - await this.ide.getWorkspaceDirs(), - completeMultiline, - helper, - ); - - // Completion - let completion: string | undefined = ""; - - const cache = await autocompleteCache; - const cachedCompletion = helper.options.useCache - ? await cache.get(prefix) - : undefined; - let cacheHit = false; - if (cachedCompletion) { - // Cache - cacheHit = true; - completion = cachedCompletion; - } else { - // Try to reuse pending requests if what the user typed matches start of completion - const generator = this.generatorReuseManager.getGenerator( - prefix, - () => - llm.supportsFim() - ? llm.streamFim(prefix, suffix, completionOptions) - : llm.streamComplete(prompt, { - ...completionOptions, - raw: true, - }), - multiline, - ); - - // Full stop means to stop the LLM's generation, instead of just truncating the displayed completion - const fullStop = () => - this.generatorReuseManager.currentGenerator?.cancel(); - - // LLM - let cancelled = false; - const generatorWithCancellation = async function* () { - for await (const update of generator) { - if (token.aborted) { - cancelled = true; - return; - } - yield update; - } - }; - - const initialGenerator = generatorWithCancellation(); - const finalGenerator = helper.options.transform - ? this.streamTransformPipeline.transform( - initialGenerator, - prefix, - suffix, - helper.filepath, - multiline, - helper.pos, - helper.fileLines, - completionOptions?.stop || [], - helper.lang, - fullStop, - ) - : initialGenerator; - - try { - for await (const update of finalGenerator) { - completion += update; - } - } catch (e: any) { - if (ERRORS_TO_IGNORE.some((err) => e.includes(err))) { - return undefined; - } - throw e; - } - - if (cancelled) { - return undefined; - } - - const processedCompletion = helper.options.transform - ? postprocessCompletion({ - completion, - prefix, - suffix, - llm, - }) - : completion; - - completion = processedCompletion; - } - - const time = Date.now() - startTime; - - if (!completion) { - return undefined; - } - - return { - time, - completion, - prefix, - suffix, - prompt, - modelProvider: llm.providerName, - modelName: llm.model, - completionOptions, - cacheHit, - filepath: helper.filepath, - completionId: helper.input.completionId, - gitRepo: await this.ide.getRepoName(helper.filepath), - uniqueId: await this.ide.getUniqueId(), - ...helper.options, - }; - } } diff --git a/core/autocomplete/generation/CompletionStreamer.ts b/core/autocomplete/generation/CompletionStreamer.ts new file mode 100644 index 000000000..803420be9 --- /dev/null +++ b/core/autocomplete/generation/CompletionStreamer.ts @@ -0,0 +1,67 @@ +import { CompletionOptions, ILLM } from "../.."; +import { StreamTransformPipeline } from "../filtering/streamTransforms/StreamTransformPipeline"; +import { HelperVars } from "../HelperVars"; +import { GeneratorReuseManager } from "./GeneratorReuseManager"; + +export class CompletionStreamer { + private streamTransformPipeline = new StreamTransformPipeline(); + private generatorReuseManager: GeneratorReuseManager; + + constructor(private readonly onError: (err: any) => void) { + this.generatorReuseManager = new GeneratorReuseManager(onError); + } + + async *streamCompletionWithFilters( + token: AbortSignal, + llm: ILLM, + prefix: string, + suffix: string, + prompt: string, + multiline: boolean, + completionOptions: Partial | undefined, + helper: HelperVars, + ) { + // Try to reuse pending requests if what the user typed matches start of completion + const generator = this.generatorReuseManager.getGenerator( + prefix, + () => + llm.supportsFim() + ? llm.streamFim(prefix, suffix, completionOptions) + : llm.streamComplete(prompt, { + ...completionOptions, + raw: true, + }), + multiline, + ); + + // Full stop means to stop the LLM's generation, instead of just truncating the displayed completion + const fullStop = () => + this.generatorReuseManager.currentGenerator?.cancel(); + + // LLM + const generatorWithCancellation = async function* () { + for await (const update of generator) { + if (token.aborted) { + return; + } + yield update; + } + }; + + const initialGenerator = generatorWithCancellation(); + const finalGenerator = helper.options.transform + ? this.streamTransformPipeline.transform( + initialGenerator, + prefix, + suffix, + helper.filepath, + multiline, + helper.pos, + helper.fileLines, + completionOptions?.stop || [], + helper.lang, + fullStop, + ) + : initialGenerator; + } +} From 93d9bc577580a0f02c32ef6e1676a0e2346d4bc9 Mon Sep 17 00:00:00 2001 From: Adam Shedivy Date: Thu, 31 Oct 2024 16:24:24 -0500 Subject: [PATCH 25/96] update Extension API Docs --- .../build-your-own-context-provider.md | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/docs/docs/customize/tutorials/build-your-own-context-provider.md b/docs/docs/customize/tutorials/build-your-own-context-provider.md index 78125548a..9b564f087 100644 --- a/docs/docs/customize/tutorials/build-your-own-context-provider.md +++ b/docs/docs/customize/tutorials/build-your-own-context-provider.md @@ -203,13 +203,27 @@ The `"options"` property can be used to send additional parameters to your endpo Continue exposes an API for registering context providers from a 3rd party VSCode extension. This is useful if you have a VSCode extension that provides some additional context that you would like to use in Continue. To use this API, add the following to your `package.json`: -```json +```json title="package.json" { "extensionDependencies": ["continue.continue"] } ``` -Or copy `~/.continue/type/core/index.d.ts` to your extension repository. +Or install the Continue Core module from npm: + +```bash +npm i @continuedev/core +``` + +You can add the Continue core module as a dev dependency in your `package.json`: + +```json title="package.json" +{ + "devDependencies": { + "@continuedev/core": "^0.0.1" + } +} +``` Then, you can use the `registerCustomContextProvider` function to register your context provider. Your custom context provider must implement the `IContextProvider` interface. Here is an example: From c74c92848f1c365184443c9c1f7b088ba16346b8 Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 31 Oct 2024 14:25:25 -0700 Subject: [PATCH 26/96] fix bugs --- core/autocomplete/CompletionProvider.ts | 7 ++++++- core/autocomplete/HelperVars.ts | 15 +++++++++++++-- .../autocomplete/generation/CompletionStreamer.ts | 4 ++++ 3 files changed, 23 insertions(+), 3 deletions(-) diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts index 665e88513..17b3c871d 100644 --- a/core/autocomplete/CompletionProvider.ts +++ b/core/autocomplete/CompletionProvider.ts @@ -201,7 +201,12 @@ export class CompletionProvider { } const options = await this._getAutocompleteOptions(); - const helper = new HelperVars(input, options, llm.model, this.ide); + const helper = await HelperVars.create( + input, + options, + llm.model, + this.ide, + ); if (await shouldPrefilter(helper, this.ide)) { return undefined; diff --git a/core/autocomplete/HelperVars.ts b/core/autocomplete/HelperVars.ts index 124389509..9dd56653d 100644 --- a/core/autocomplete/HelperVars.ts +++ b/core/autocomplete/HelperVars.ts @@ -12,7 +12,7 @@ export class HelperVars { private _fileContents: string | undefined; private _fileLines: string[] | undefined; - constructor( + private constructor( public readonly input: AutocompleteInput, public readonly options: TabAutocompleteOptions, public readonly modelName: string, @@ -21,7 +21,7 @@ export class HelperVars { this.lang = languageForFilepath(input.filepath); } - async init() { + private async init() { // Don't do anything if already initialized if (this._fileContents !== undefined) return; @@ -32,6 +32,17 @@ export class HelperVars { this._fileLines = this._fileContents.split("\n"); } + static async create( + input: AutocompleteInput, + options: TabAutocompleteOptions, + modelName: string, + ide: IDE, + ): Promise { + const instance = new HelperVars(input, options, modelName, ide); + await instance.init(); + return instance; + } + // Fast access get filepath() { return this.input.filepath; diff --git a/core/autocomplete/generation/CompletionStreamer.ts b/core/autocomplete/generation/CompletionStreamer.ts index 803420be9..a723a3c1b 100644 --- a/core/autocomplete/generation/CompletionStreamer.ts +++ b/core/autocomplete/generation/CompletionStreamer.ts @@ -63,5 +63,9 @@ export class CompletionStreamer { fullStop, ) : initialGenerator; + + for await (const update of finalGenerator) { + yield update; + } } } From 39fd5a4868253028b0242fc2a371fd89f4429b01 Mon Sep 17 00:00:00 2001 From: Adam Shedivy Date: Thu, 31 Oct 2024 16:29:03 -0500 Subject: [PATCH 27/96] add imports for clarity --- .../tutorials/build-your-own-context-provider.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/docs/docs/customize/tutorials/build-your-own-context-provider.md b/docs/docs/customize/tutorials/build-your-own-context-provider.md index 9b564f087..296049ac1 100644 --- a/docs/docs/customize/tutorials/build-your-own-context-provider.md +++ b/docs/docs/customize/tutorials/build-your-own-context-provider.md @@ -230,6 +230,14 @@ Here is an example: ```typescript import * as vscode from "vscode"; +import { + IContextProvider, + ContextProviderDescription, + ContextProviderExtras, + ContextItem, + LoadSubmenuItemsArgs, + ContextSubmenuItem, +} from "@continuedev/core"; class MyCustomProvider implements IContextProvider { get description(): ContextProviderDescription { From 9850834c227aa79802381d388f853b7f7ce8201c Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 31 Oct 2024 14:36:28 -0700 Subject: [PATCH 28/96] refactor logging service --- .../AutocompleteLoggingService.ts | 119 +++++++++++++++++ core/autocomplete/CompletionProvider.ts | 123 +++--------------- 2 files changed, 135 insertions(+), 107 deletions(-) create mode 100644 core/autocomplete/AutocompleteLoggingService.ts diff --git a/core/autocomplete/AutocompleteLoggingService.ts b/core/autocomplete/AutocompleteLoggingService.ts new file mode 100644 index 000000000..6771b1dd6 --- /dev/null +++ b/core/autocomplete/AutocompleteLoggingService.ts @@ -0,0 +1,119 @@ +import { logDevData } from "../util/devdata"; +import { COUNT_COMPLETION_REJECTED_AFTER } from "../util/parameters"; +import { Telemetry } from "../util/posthog"; +import { AutocompleteOutcome } from "./types"; + +export class AutocompleteLoggingService { + // Key is completionId + private _abortControllers = new Map(); + private _logRejectionTimeouts = new Map(); + private _outcomes = new Map(); + _lastDisplayedCompletion: { id: string; displayedAt: number } | undefined = + undefined; + + public createAbortController(completionId: string): AbortController { + const abortController = new AbortController(); + this._abortControllers.set(completionId, abortController); + return abortController; + } + + public deleteAbortController(completionId: string) { + this._abortControllers.delete(completionId); + } + + public cancel() { + this._abortControllers.forEach((abortController, id) => { + abortController.abort(); + }); + this._abortControllers.clear(); + } + + public accept(completionId: string): AutocompleteOutcome | undefined { + if (this._logRejectionTimeouts.has(completionId)) { + clearTimeout(this._logRejectionTimeouts.get(completionId)); + this._logRejectionTimeouts.delete(completionId); + } + + if (this._outcomes.has(completionId)) { + const outcome = this._outcomes.get(completionId)!; + this.logAutocompleteOutcome(outcome); + this._outcomes.delete(completionId); + return outcome; + } + } + + public cancelRejectionTimeout(completionId: string) { + if (this._logRejectionTimeouts.has(completionId)) { + clearTimeout(this._logRejectionTimeouts.get(completionId)!); + this._logRejectionTimeouts.delete(completionId); + } + + if (this._outcomes.has(completionId)) { + this._outcomes.delete(completionId); + } + } + + public markDisplayed(completionId: string, outcome: AutocompleteOutcome) { + const logRejectionTimeout = setTimeout(() => { + // Wait 10 seconds, then assume it wasn't accepted + outcome.accepted = false; + this.logAutocompleteOutcome(outcome); + this._logRejectionTimeouts.delete(completionId); + }, COUNT_COMPLETION_REJECTED_AFTER); + this._outcomes.set(completionId, outcome); + this._logRejectionTimeouts.set(completionId, logRejectionTimeout); + + // If the previously displayed completion is still waiting for rejection, + // and this one is a continuation of that (the outcome.completion is the same modulo prefix) + // then we should cancel the rejection timeout + const previous = this._lastDisplayedCompletion; + const now = Date.now(); + if (previous && this._logRejectionTimeouts.has(previous.id)) { + const previousOutcome = this._outcomes.get(previous.id); + const c1 = previousOutcome?.completion.split("\n")[0] ?? ""; + const c2 = outcome.completion.split("\n")[0]; + if ( + previousOutcome && + (c1.endsWith(c2) || + c2.endsWith(c1) || + c1.startsWith(c2) || + c2.startsWith(c1)) + ) { + this.cancelRejectionTimeout(previous.id); + } else if (now - previous.displayedAt < 500) { + // If a completion isn't shown for more than + this.cancelRejectionTimeout(previous.id); + } + } + + this._lastDisplayedCompletion = { + id: completionId, + displayedAt: now, + }; + } + + private logAutocompleteOutcome(outcome: AutocompleteOutcome) { + outcome.accepted = true; + logDevData("autocomplete", outcome); + const { prompt, completion, prefix, suffix, ...restOfOutcome } = outcome; + void Telemetry.capture( + "autocomplete", + { + accepted: restOfOutcome.accepted, + cacheHit: restOfOutcome.cacheHit, + completionId: restOfOutcome.completionId, + completionOptions: restOfOutcome.completionOptions, + debounceDelay: restOfOutcome.debounceDelay, + fileExtension: restOfOutcome.filepath.split(".")?.slice(-1)[0], + maxPromptTokens: restOfOutcome.maxPromptTokens, + modelName: restOfOutcome.modelName, + modelProvider: restOfOutcome.modelProvider, + multilineCompletions: restOfOutcome.multilineCompletions, + time: restOfOutcome.time, + useRecentlyEdited: restOfOutcome.useRecentlyEdited, + useRootPathContext: restOfOutcome.useRootPathContext, + }, + true, + ); + } +} diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts index 17b3c871d..323f737c5 100644 --- a/core/autocomplete/CompletionProvider.ts +++ b/core/autocomplete/CompletionProvider.ts @@ -1,11 +1,6 @@ import { ConfigHandler } from "../config/ConfigHandler.js"; import { IDE, ILLM } from "../index.js"; -import { logDevData } from "../util/devdata.js"; -import { - COUNT_COMPLETION_REJECTED_AFTER, - DEFAULT_AUTOCOMPLETE_OPTS, -} from "../util/parameters.js"; -import { Telemetry } from "../util/posthog.js"; +import { DEFAULT_AUTOCOMPLETE_OPTS } from "../util/parameters.js"; import { AutocompleteLanguageInfo } from "./constants/AutocompleteLanguageInfo.js"; import { constructAutocompletePrompt } from "./constructPrompt.js"; @@ -16,6 +11,7 @@ import { postprocessCompletion } from "./postprocessing/index.js"; import { TRIAL_FIM_MODEL } from "../config/onboarding.js"; import OpenAI from "../llm/llms/OpenAI.js"; import { AutocompleteDebouncer } from "./AutocompleteDebouncer.js"; +import { AutocompleteLoggingService } from "./AutocompleteLoggingService.js"; import AutocompleteLruCache from "./AutocompleteLruCache.js"; import { ImportDefinitionsService } from "./context/ImportDefinitionsService.js"; import { BracketMatchingService } from "./filtering/BracketMatchingService.js"; @@ -51,6 +47,7 @@ export class CompletionProvider { private bracketMatchingService = new BracketMatchingService(); private debouncer = new AutocompleteDebouncer(); private completionStreamer: CompletionStreamer; + private loggingService = new AutocompleteLoggingService(); constructor( private readonly configHandler: ConfigHandler, @@ -114,69 +111,22 @@ export class CompletionProvider { } public cancel() { - this._abortControllers.forEach((abortController, id) => { - abortController.abort(); - }); - this._abortControllers.clear(); + this.loggingService.cancel(); } - // Key is completionId - private _abortControllers = new Map(); - private _logRejectionTimeouts = new Map(); - private _outcomes = new Map(); - public accept(completionId: string) { - if (this._logRejectionTimeouts.has(completionId)) { - clearTimeout(this._logRejectionTimeouts.get(completionId)); - this._logRejectionTimeouts.delete(completionId); + const outcome = this.loggingService.accept(completionId); + if (!outcome) { + return; } - - if (this._outcomes.has(completionId)) { - const outcome = this._outcomes.get(completionId)!; - this.logAutocompleteOutcome(outcome); - this._outcomes.delete(completionId); - - this.bracketMatchingService.handleAcceptedCompletion( - outcome.completion, - outcome.filepath, - ); - } - } - - private logAutocompleteOutcome(outcome: AutocompleteOutcome) { - outcome.accepted = true; - logDevData("autocomplete", outcome); - const { prompt, completion, prefix, suffix, ...restOfOutcome } = outcome; - void Telemetry.capture( - "autocomplete", - { - accepted: restOfOutcome.accepted, - cacheHit: restOfOutcome.cacheHit, - completionId: restOfOutcome.completionId, - completionOptions: restOfOutcome.completionOptions, - debounceDelay: restOfOutcome.debounceDelay, - fileExtension: restOfOutcome.filepath.split(".")?.slice(-1)[0], - maxPromptTokens: restOfOutcome.maxPromptTokens, - modelName: restOfOutcome.modelName, - modelProvider: restOfOutcome.modelProvider, - multilineCompletions: restOfOutcome.multilineCompletions, - time: restOfOutcome.time, - useRecentlyEdited: restOfOutcome.useRecentlyEdited, - useRootPathContext: restOfOutcome.useRootPathContext, - }, - true, + this.bracketMatchingService.handleAcceptedCompletion( + outcome.completion, + outcome.filepath, ); } - public cancelRejectionTimeout(completionId: string) { - if (this._logRejectionTimeouts.has(completionId)) { - clearTimeout(this._logRejectionTimeouts.get(completionId)!); - this._logRejectionTimeouts.delete(completionId); - } - - if (this._outcomes.has(completionId)) { - this._outcomes.delete(completionId); - } + public markDisplayed(completionId: string, outcome: AutocompleteOutcome) { + this.loggingService.markDisplayed(completionId, outcome); } private async _getAutocompleteOptions() { @@ -219,9 +169,10 @@ export class CompletionProvider { // Create abort signal if not given if (!token) { - const controller = new AbortController(); + const controller = this.loggingService.createAbortController( + input.completionId, + ); token = controller.signal; - this._abortControllers.set(input.completionId, controller); } ////////// @@ -344,52 +295,10 @@ export class CompletionProvider { } catch (e: any) { this.onError(e); } finally { - this._abortControllers.delete(input.completionId); + this.loggingService.deleteAbortController(input.completionId); } } - _lastDisplayedCompletion: { id: string; displayedAt: number } | undefined = - undefined; - - markDisplayed(completionId: string, outcome: AutocompleteOutcome) { - const logRejectionTimeout = setTimeout(() => { - // Wait 10 seconds, then assume it wasn't accepted - outcome.accepted = false; - this.logAutocompleteOutcome(outcome); - this._logRejectionTimeouts.delete(completionId); - }, COUNT_COMPLETION_REJECTED_AFTER); - this._outcomes.set(completionId, outcome); - this._logRejectionTimeouts.set(completionId, logRejectionTimeout); - - // If the previously displayed completion is still waiting for rejection, - // and this one is a continuation of that (the outcome.completion is the same modulo prefix) - // then we should cancel the rejection timeout - const previous = this._lastDisplayedCompletion; - const now = Date.now(); - if (previous && this._logRejectionTimeouts.has(previous.id)) { - const previousOutcome = this._outcomes.get(previous.id); - const c1 = previousOutcome?.completion.split("\n")[0] ?? ""; - const c2 = outcome.completion.split("\n")[0]; - if ( - previousOutcome && - (c1.endsWith(c2) || - c2.endsWith(c1) || - c1.startsWith(c2) || - c2.startsWith(c1)) - ) { - this.cancelRejectionTimeout(previous.id); - } else if (now - previous.displayedAt < 500) { - // If a completion isn't shown for more than - this.cancelRejectionTimeout(previous.id); - } - } - - this._lastDisplayedCompletion = { - id: completionId, - displayedAt: now, - }; - } - private async _getExtraSnippets( helper: HelperVars, fullPrefix: string, From 55645ec5c6e8bc392ee7cfbf9ff0175a4f694024 Mon Sep 17 00:00:00 2001 From: Adam Shedivy Date: Thu, 31 Oct 2024 16:39:21 -0500 Subject: [PATCH 29/96] update code example --- docs/docs/customize/tutorials/assets/image.png | Bin 0 -> 76020 bytes .../build-your-own-context-provider.md | 10 +++++++--- 2 files changed, 7 insertions(+), 3 deletions(-) create mode 100644 docs/docs/customize/tutorials/assets/image.png diff --git a/docs/docs/customize/tutorials/assets/image.png b/docs/docs/customize/tutorials/assets/image.png new file mode 100644 index 0000000000000000000000000000000000000000..284b2afc9c84965b3edd29d5d4c2c99f1549e90e GIT binary patch literal 76020 zcmeFZbySpF8#fF{2_hgO(%mr%0@4_C3Mk#uB`rCClpx*RAkr;4Vv*9_-7$1b@ZOwr z9?vz%b`=4S4F@A&PjuWR#GSy2iPhYSY=1qDw=`l$*E3MLW-1$6`) z6Zi#EghZgA+)%W5@YZDX{>9=v}SQ@Gw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?h>}x`lSWVp1s< zQ#d<~Ilj@kUC7*M_Q|ES$F=LAYL27@y5~VvCZj}-5k7g-g{@|x@n`HzSO0EcvLS`} zjk)c<2ib#v>h(`Pg-Q!(T_o?EyIP^zim5P%T~0tiwj&Fxu(0Gm_|1EWV)C|1Dl_ZM z=C-F$g(6ZSlh?{K!N@ahE6>am>WrEgpKkaEvHW#@WZ00e^6gS2+nml~pZH`dP#B|= zv*#dfR3F;n8zp`TcH{%&Y#%h66&M(RnS%+XOc#@E)C!?4D+uZb=__)*xX_@uOX7c@ z&3`SHX2{RwM!HP`1k!r zN8UAYxxw@xMp;}wn8m)#ki6$TnS9zW)F&&fZer&cVq*nfK@!biPZHQUj_04X>fN8CL+T zzdv35W*?~={z{0v8%CZ9AOqyR5N7MxLnDM1>j!cIg?~@^pN1A#VB+2iH+EZ|C~&=) z8V3stwGclWe_?l&3u!!3TSK*)yoe4J9vl=Dutw2gxHlc}CBCUarne$AERNwnmbm~8 d5C}dJpug4%cw}_J%0A~{{vc?W}*N9 literal 0 HcmV?d00001 diff --git a/docs/docs/customize/tutorials/build-your-own-context-provider.md b/docs/docs/customize/tutorials/build-your-own-context-provider.md index 296049ac1..e70cb36f2 100644 --- a/docs/docs/customize/tutorials/build-your-own-context-provider.md +++ b/docs/docs/customize/tutorials/build-your-own-context-provider.md @@ -242,9 +242,9 @@ import { class MyCustomProvider implements IContextProvider { get description(): ContextProviderDescription { return { - title: "custom", + title: "Custom", displayTitle: "Custom", - description: "Custom description", + description: "my custom context provider", type: "normal", }; } @@ -273,7 +273,7 @@ class MyCustomProvider implements IContextProvider { const customProvider = new MyCustomProvider(); // get Continue extension using vscode API -const continueExt = vscode.extensions.getExtension("continue.continue"); +const continueExt = vscode.extensions.getExtension("Continue.continue"); // get the API from the extension const continueApi = continueExt?.exports; @@ -281,3 +281,7 @@ const continueApi = continueExt?.exports; // register your custom provider continueApi?.registerCustomContextProvider(customProvider); ``` + +This will register `MyCustomProvider` provider with Continue + +![alt text](./assets/image.png) From 211594c11fa7e0f79c03b72c454477d6822af3bd Mon Sep 17 00:00:00 2001 From: Adam Shedivy Date: Thu, 31 Oct 2024 16:40:47 -0500 Subject: [PATCH 30/96] add file name --- .../docs/customize/tutorials/build-your-own-context-provider.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/docs/customize/tutorials/build-your-own-context-provider.md b/docs/docs/customize/tutorials/build-your-own-context-provider.md index e70cb36f2..33c474c04 100644 --- a/docs/docs/customize/tutorials/build-your-own-context-provider.md +++ b/docs/docs/customize/tutorials/build-your-own-context-provider.md @@ -228,7 +228,7 @@ You can add the Continue core module as a dev dependency in your `package.json`: Then, you can use the `registerCustomContextProvider` function to register your context provider. Your custom context provider must implement the `IContextProvider` interface. Here is an example: -```typescript +```typescript title="myCustomContextProvider.ts" import * as vscode from "vscode"; import { IContextProvider, From 45b03efe26802f6f0407976365c43cda0e4031af Mon Sep 17 00:00:00 2001 From: Adam Shedivy Date: Thu, 31 Oct 2024 16:41:56 -0500 Subject: [PATCH 31/96] fix typo --- .../docs/customize/tutorials/build-your-own-context-provider.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/docs/customize/tutorials/build-your-own-context-provider.md b/docs/docs/customize/tutorials/build-your-own-context-provider.md index 33c474c04..3d37790cd 100644 --- a/docs/docs/customize/tutorials/build-your-own-context-provider.md +++ b/docs/docs/customize/tutorials/build-your-own-context-provider.md @@ -282,6 +282,6 @@ const continueApi = continueExt?.exports; continueApi?.registerCustomContextProvider(customProvider); ``` -This will register `MyCustomProvider` provider with Continue +This will register `MyCustomProvider` with Continue! ![alt text](./assets/image.png) From d6e54c39329d485423b03d8d7cb85d4c142cb77b Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 31 Oct 2024 15:35:19 -0700 Subject: [PATCH 32/96] more refactoring --- core/autocomplete/CompletionProvider.ts | 47 +--- core/autocomplete/HelperVars.ts | 39 +++ .../classification/shouldCompleteMultiline.ts | 13 +- core/autocomplete/constructPrompt.ts | 222 +++++------------- .../context/ContextRetrievalService.ts | 85 +++++++ core/autocomplete/context/ranking/index.ts | 13 +- 6 files changed, 215 insertions(+), 204 deletions(-) create mode 100644 core/autocomplete/context/ContextRetrievalService.ts diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts index 323f737c5..50629e30e 100644 --- a/core/autocomplete/CompletionProvider.ts +++ b/core/autocomplete/CompletionProvider.ts @@ -1,11 +1,9 @@ import { ConfigHandler } from "../config/ConfigHandler.js"; import { IDE, ILLM } from "../index.js"; import { DEFAULT_AUTOCOMPLETE_OPTS } from "../util/parameters.js"; - import { AutocompleteLanguageInfo } from "./constants/AutocompleteLanguageInfo.js"; import { constructAutocompletePrompt } from "./constructPrompt.js"; import { AutocompleteSnippet } from "./context/ranking/index.js"; -import { RootPathContextService } from "./context/RootPathContextService.js"; import { postprocessCompletion } from "./postprocessing/index.js"; // @prettier-ignore import { TRIAL_FIM_MODEL } from "../config/onboarding.js"; @@ -13,12 +11,11 @@ import OpenAI from "../llm/llms/OpenAI.js"; import { AutocompleteDebouncer } from "./AutocompleteDebouncer.js"; import { AutocompleteLoggingService } from "./AutocompleteLoggingService.js"; import AutocompleteLruCache from "./AutocompleteLruCache.js"; -import { ImportDefinitionsService } from "./context/ImportDefinitionsService.js"; +import { ContextRetrievalService } from "./context/ContextRetrievalService.js"; import { BracketMatchingService } from "./filtering/BracketMatchingService.js"; import { CompletionStreamer } from "./generation/CompletionStreamer.js"; import { HelperVars } from "./HelperVars.js"; import { shouldPrefilter } from "./prefiltering/index.js"; -import { constructInitialPrefixSuffix } from "./templating/constructPrefixSuffix.js"; import { renderPrompt } from "./templating/index.js"; import { AutocompleteInput, AutocompleteOutcome } from "./types.js"; @@ -40,14 +37,13 @@ export type GetLspDefinitionsFunction = ( ) => Promise; export class CompletionProvider { - private importDefinitionsService: ImportDefinitionsService; - private rootPathContextService: RootPathContextService; private autocompleteCache = AutocompleteLruCache.get(); public errorsShown: Set = new Set(); private bracketMatchingService = new BracketMatchingService(); private debouncer = new AutocompleteDebouncer(); private completionStreamer: CompletionStreamer; private loggingService = new AutocompleteLoggingService(); + private contextRetrievalService: ContextRetrievalService; constructor( private readonly configHandler: ConfigHandler, @@ -57,11 +53,7 @@ export class CompletionProvider { private readonly getDefinitionsFromLsp: GetLspDefinitionsFunction, ) { this.completionStreamer = new CompletionStreamer(this.onError.bind(this)); - this.importDefinitionsService = new ImportDefinitionsService(this.ide); - this.rootPathContextService = new RootPathContextService( - this.importDefinitionsService, - this.ide, - ); + this.contextRetrievalService = new ContextRetrievalService(this.ide); } private async _prepareLlm(): Promise { @@ -144,13 +136,18 @@ export class CompletionProvider { ): Promise { try { const startTime = Date.now(); + const options = await this._getAutocompleteOptions(); + + // Debounce + if (await this.debouncer.delayAndShouldDebounce(options.debounceDelay)) { + return undefined; + } const llm = await this._prepareLlm(); if (!llm) { return undefined; } - const options = await this._getAutocompleteOptions(); const helper = await HelperVars.create( input, options, @@ -162,11 +159,6 @@ export class CompletionProvider { return undefined; } - // Debounce - if (await this.debouncer.delayAndShouldDebounce(options.debounceDelay)) { - return undefined; - } - // Create abort signal if not given if (!token) { const controller = this.loggingService.createAbortController( @@ -177,26 +169,15 @@ export class CompletionProvider { ////////// - // Construct full prefix/suffix (a few edge cases handled in here) - const { prefix: fullPrefix, suffix: fullSuffix } = - await constructInitialPrefixSuffix(helper.input, this.ide); - // Some IDEs might have special ways of finding snippets (e.g. JetBrains and VS Code have different "LSP-equivalent" systems, // or they might separately track recently edited ranges) - const extraSnippets = await this._getExtraSnippets( - helper, - fullPrefix, - fullSuffix, - ); + const extraSnippets = await this._getExtraSnippets(helper); let { prefix, suffix, completeMultiline, snippets } = await constructAutocompletePrompt( - fullPrefix, - fullSuffix, helper, extraSnippets, - this.importDefinitionsService, - this.rootPathContextService, + this.contextRetrievalService, ); // If prefix is manually passed @@ -301,15 +282,13 @@ export class CompletionProvider { private async _getExtraSnippets( helper: HelperVars, - fullPrefix: string, - fullSuffix: string, ): Promise { let extraSnippets = helper.options.useOtherFiles ? ((await Promise.race([ this.getDefinitionsFromLsp( helper.input.filepath, - fullPrefix + fullSuffix, - fullPrefix.length, + helper.fullPrefix + helper.fullSuffix, + helper.fullPrefix.length, this.ide, helper.lang, ), diff --git a/core/autocomplete/HelperVars.ts b/core/autocomplete/HelperVars.ts index 9dd56653d..2c9f0fe27 100644 --- a/core/autocomplete/HelperVars.ts +++ b/core/autocomplete/HelperVars.ts @@ -1,7 +1,9 @@ import { IDE, TabAutocompleteOptions } from ".."; import { AutocompleteLanguageInfo } from "./constants/AutocompleteLanguageInfo"; import { languageForFilepath } from "./constructPrompt"; +import { constructInitialPrefixSuffix } from "./templating/constructPrefixSuffix"; import { AutocompleteInput } from "./types"; +import { AstPath, getAst, getTreePathAtCursor } from "./util/ast"; /** * A collection of variables that are often accessed throughout the autocomplete pipeline @@ -9,8 +11,12 @@ import { AutocompleteInput } from "./types"; */ export class HelperVars { lang: AutocompleteLanguageInfo; + treePath: AstPath | undefined; + private _fileContents: string | undefined; private _fileLines: string[] | undefined; + private _fullPrefix: string | undefined; + private _fullSuffix: string | undefined; private constructor( public readonly input: AutocompleteInput, @@ -30,6 +36,21 @@ export class HelperVars { (await this.ide.readFile(this.filepath)); this._fileLines = this._fileContents.split("\n"); + + // Construct full prefix/suffix (a few edge cases handled in here) + const { prefix: fullPrefix, suffix: fullSuffix } = + await constructInitialPrefixSuffix(this.input, this.ide); + this._fullPrefix = fullPrefix; + this._fullSuffix = fullSuffix; + + try { + const ast = await getAst(this.filepath, fullPrefix + fullSuffix); + if (ast) { + this.treePath = await getTreePathAtCursor(ast, fullPrefix.length); + } + } catch (e) { + console.error("Failed to parse AST", e); + } } static async create( @@ -69,4 +90,22 @@ export class HelperVars { } return this._fileLines; } + + get fullPrefix(): string { + if (this._fullPrefix === undefined) { + throw new Error( + "HelperVars must be initialized before accessing fullPrefix", + ); + } + return this._fullPrefix; + } + + get fullSuffix(): string { + if (this._fullSuffix === undefined) { + throw new Error( + "HelperVars must be initialized before accessing fullSuffix", + ); + } + return this._fullSuffix; + } } diff --git a/core/autocomplete/classification/shouldCompleteMultiline.ts b/core/autocomplete/classification/shouldCompleteMultiline.ts index 8bc5e5de4..d8df8aeb0 100644 --- a/core/autocomplete/classification/shouldCompleteMultiline.ts +++ b/core/autocomplete/classification/shouldCompleteMultiline.ts @@ -1,7 +1,7 @@ import { TabAutocompleteOptions } from "@continuedev/config-types"; import { AutocompleteLanguageInfo } from "../constants/AutocompleteLanguageInfo"; +import { HelperVars } from "../HelperVars"; import { AutocompleteInput } from "../types"; -import { AstPath } from "../util/ast"; const BLOCK_TYPES = ["body", "statement_block"]; @@ -10,23 +10,20 @@ function isMidlineCompletion(prefix: string, suffix: string): boolean { } export async function shouldCompleteMultiline( - treePath: AstPath | undefined, - fullPrefix: string, - fullSuffix: string, - language: AutocompleteLanguageInfo, + helper: HelperVars, ): Promise { // Don't complete multi-line if you are mid-line - if (isMidlineCompletion(fullPrefix, fullSuffix)) { + if (isMidlineCompletion(helper.fullPrefix, helper.fullSuffix)) { return false; } // Don't complete multi-line for single-line comments if ( - fullPrefix + helper.fullPrefix .split("\n") .slice(-1)[0] ?.trimStart() - .startsWith(language.singleLineComment) + .startsWith(helper.lang.singleLineComment) ) { return false; } diff --git a/core/autocomplete/constructPrompt.ts b/core/autocomplete/constructPrompt.ts index cbef4949b..c83e1b107 100644 --- a/core/autocomplete/constructPrompt.ts +++ b/core/autocomplete/constructPrompt.ts @@ -9,18 +9,14 @@ import { LANGUAGES, Typescript, } from "./constants/AutocompleteLanguageInfo.js"; -import { ImportDefinitionsService } from "./context/ImportDefinitionsService.js"; +import { ContextRetrievalService } from "./context/ContextRetrievalService.js"; import { fillPromptWithSnippets, - getSymbolsForSnippet, rankSnippets, removeRangeFromSnippets, type AutocompleteSnippet, } from "./context/ranking/index.js"; -import { RootPathContextService } from "./context/RootPathContextService.js"; import { HelperVars } from "./HelperVars.js"; -import { findMatchingRange } from "./recentlyEdited.js"; -import { AstPath, getAst, getTreePathAtCursor } from "./util/ast.js"; export function languageForFilepath( filepath: string, @@ -29,12 +25,9 @@ export function languageForFilepath( } export async function constructAutocompletePrompt( - fullPrefix: string, - fullSuffix: string, helper: HelperVars, extraSnippets: AutocompleteSnippet[], - importDefinitionsService: ImportDefinitionsService, - rootPathContextService: RootPathContextService, + contextRetrievalService: ContextRetrievalService, ): Promise<{ prefix: string; suffix: string; @@ -45,177 +38,84 @@ export async function constructAutocompletePrompt( // Construct basic prefix const maxPrefixTokens = helper.options.maxPromptTokens * helper.options.prefixPercentage; - const prefix = pruneLinesFromTop( - fullPrefix, + const prunedPrefix = pruneLinesFromTop( + helper.fullPrefix, maxPrefixTokens, helper.modelName, ); // Construct suffix const maxSuffixTokens = Math.min( - helper.options.maxPromptTokens - countTokens(prefix, helper.modelName), + helper.options.maxPromptTokens - + countTokens(prunedPrefix, helper.modelName), helper.options.maxSuffixPercentage * helper.options.maxPromptTokens, ); - const suffix = pruneLinesFromBottom( - fullSuffix, + const prunedSuffix = pruneLinesFromBottom( + helper.fullSuffix, maxSuffixTokens, helper.modelName, ); - // Calculate AST Path - let treePath: AstPath | undefined; - try { - const ast = await getAst(helper.filepath, fullPrefix + fullSuffix); - if (ast) { - treePath = await getTreePathAtCursor(ast, fullPrefix.length); - } - } catch (e) { - console.error("Failed to parse AST", e); - } + let snippets = await contextRetrievalService.retrieve( + prunedPrefix, + helper, + extraSnippets, + ); - // Find external snippets - let snippets: AutocompleteSnippet[] = []; - - if (helper.options.useOtherFiles) { - snippets.push(...extraSnippets); - - const windowAroundCursor = - fullPrefix.slice( - -helper.options.slidingWindowSize * - helper.options.slidingWindowPrefixPercentage, - ) + - fullSuffix.slice( - helper.options.slidingWindowSize * - (1 - helper.options.slidingWindowPrefixPercentage), - ); - - // This was much too slow, and not super useful - // const slidingWindowMatches = await slidingWindowMatcher( - // recentlyEditedFiles, - // windowAroundCursor, - // 3, - // options.slidingWindowSize, - // ); - // snippets.push(...slidingWindowMatches); - - // snippets.push( - // ...recentlyEditedRanges.map((r) => ({ - // ...r, - // contents: r.lines.join("\n"), - // })), - // ); - - if (helper.options.useRecentlyEdited) { - const currentLinePrefix = prefix.trim().split("\n").slice(-1)[0]; - if ( - currentLinePrefix?.length > - helper.options.recentLinePrefixMatchMinLength - ) { - const matchingRange = findMatchingRange( - helper.input.recentlyEditedRanges, - currentLinePrefix, - ); - if (matchingRange) { - snippets.push({ - ...matchingRange, - contents: matchingRange.lines.join("\n"), - score: 0.8, - }); - } - } - } - - // Use imports - if (helper.options.useImports) { - const importSnippets = []; - const fileInfo = importDefinitionsService.get(helper.filepath); - if (fileInfo) { - const { imports } = fileInfo; - // Look for imports of any symbols around the current range - const textAroundCursor = - fullPrefix.split("\n").slice(-5).join("\n") + - fullSuffix.split("\n").slice(0, 3).join("\n"); - const symbols = Array.from( - getSymbolsForSnippet(textAroundCursor), - ).filter((symbol) => !helper.lang.topLevelKeywords.includes(symbol)); - for (const symbol of symbols) { - const rifs = imports[symbol]; - if (Array.isArray(rifs)) { - importSnippets.push(...rifs); - } - } - } - snippets.push(...importSnippets); - } - - if (helper.options.useRootPathContext && treePath) { - const ctx = await rootPathContextService.getContextForPath( - helper.filepath, - treePath, - ); - snippets.push(...ctx); - } - - // Filter out empty snippets and ones that are already in the prefix/suffix - snippets = snippets - .map((snippet) => ({ ...snippet })) - .filter( - (s) => - s.contents.trim() !== "" && - !(prefix + suffix).includes(s.contents.trim()), - ); - - // Rank / order the snippets - const scoredSnippets = rankSnippets(snippets, windowAroundCursor); - - // Fill maxSnippetTokens with snippets - const maxSnippetTokens = - helper.options.maxPromptTokens * helper.options.maxSnippetPercentage; - - // Remove prefix range from snippets - const prefixLines = prefix.split("\n").length; - const suffixLines = suffix.split("\n").length; - const buffer = 8; - const prefixSuffixRangeWithBuffer = { - start: { - line: helper.pos.line - prefixLines - buffer, - character: 0, - }, - end: { - line: helper.pos.line + suffixLines + buffer, - character: 0, - }, - }; - let finalSnippets = removeRangeFromSnippets( - scoredSnippets, - helper.filepath.split("://").slice(-1)[0], - prefixSuffixRangeWithBuffer, + // Filter out empty snippets and ones that are already in the prefix/suffix + snippets = snippets + .map((snippet) => ({ ...snippet })) + .filter( + (s) => + s.contents.trim() !== "" && + !(prunedPrefix + prunedSuffix).includes(s.contents.trim()), ); - // Filter snippets for those with best scores (must be above threshold) - finalSnippets = finalSnippets.filter( - (snippet) => - snippet.score >= helper.options.recentlyEditedSimilarityThreshold, - ); - finalSnippets = fillPromptWithSnippets( - scoredSnippets, - maxSnippetTokens, - helper.modelName, - ); + // Rank / order the snippets + const scoredSnippets = rankSnippets(snippets, helper); - snippets = finalSnippets; - } + // Fill maxSnippetTokens with snippets + const maxSnippetTokens = + helper.options.maxPromptTokens * helper.options.maxSnippetPercentage; + + // Remove prefix range from snippets + const prefixLines = prunedPrefix.split("\n").length; + const suffixLines = prunedSuffix.split("\n").length; + const buffer = 8; + const prefixSuffixRangeWithBuffer = { + start: { + line: helper.pos.line - prefixLines - buffer, + character: 0, + }, + end: { + line: helper.pos.line + suffixLines + buffer, + character: 0, + }, + }; + let finalSnippets = removeRangeFromSnippets( + scoredSnippets, + helper.filepath.split("://").slice(-1)[0], + prefixSuffixRangeWithBuffer, + ); + + // Filter snippets for those with best scores (must be above threshold) + finalSnippets = finalSnippets.filter( + (snippet) => + snippet.score >= helper.options.recentlyEditedSimilarityThreshold, + ); + finalSnippets = fillPromptWithSnippets( + scoredSnippets, + maxSnippetTokens, + helper.modelName, + ); + + snippets = finalSnippets; return { - prefix, - suffix, + prefix: prunedPrefix, + suffix: prunedSuffix, useFim: true, - completeMultiline: await shouldCompleteMultiline( - treePath, - fullPrefix, - fullSuffix, - helper.lang, - ), + completeMultiline: await shouldCompleteMultiline(helper), snippets, }; } diff --git a/core/autocomplete/context/ContextRetrievalService.ts b/core/autocomplete/context/ContextRetrievalService.ts new file mode 100644 index 000000000..cdf5f2bcd --- /dev/null +++ b/core/autocomplete/context/ContextRetrievalService.ts @@ -0,0 +1,85 @@ +import { IDE } from "../.."; +import { HelperVars } from "../HelperVars"; +import { findMatchingRange } from "../recentlyEdited"; +import { ImportDefinitionsService } from "./ImportDefinitionsService"; +import { AutocompleteSnippet, getSymbolsForSnippet } from "./ranking"; +import { RootPathContextService } from "./RootPathContextService"; + +export class ContextRetrievalService { + private importDefinitionsService: ImportDefinitionsService; + private rootPathContextService: RootPathContextService; + + constructor(private readonly ide: IDE) { + this.importDefinitionsService = new ImportDefinitionsService(this.ide); + this.rootPathContextService = new RootPathContextService( + this.importDefinitionsService, + this.ide, + ); + } + + public async retrieve( + prunedPrefix: string, + helper: HelperVars, + extraSnippets: AutocompleteSnippet[], + ) { + // Find external snippets + let snippets: AutocompleteSnippet[] = []; + + if (helper.options.useOtherFiles) { + snippets.push(...extraSnippets); + + if (helper.options.useRecentlyEdited) { + const currentLinePrefix = prunedPrefix.trim().split("\n").slice(-1)[0]; + if ( + currentLinePrefix?.length > + helper.options.recentLinePrefixMatchMinLength + ) { + const matchingRange = findMatchingRange( + helper.input.recentlyEditedRanges, + currentLinePrefix, + ); + if (matchingRange) { + snippets.push({ + ...matchingRange, + contents: matchingRange.lines.join("\n"), + score: 0.8, + }); + } + } + } + + // Use imports + if (helper.options.useImports) { + const importSnippets = []; + const fileInfo = this.importDefinitionsService.get(helper.filepath); + if (fileInfo) { + const { imports } = fileInfo; + // Look for imports of any symbols around the current range + const textAroundCursor = + helper.fullPrefix.split("\n").slice(-5).join("\n") + + helper.fullSuffix.split("\n").slice(0, 3).join("\n"); + const symbols = Array.from( + getSymbolsForSnippet(textAroundCursor), + ).filter((symbol) => !helper.lang.topLevelKeywords.includes(symbol)); + for (const symbol of symbols) { + const rifs = imports[symbol]; + if (Array.isArray(rifs)) { + importSnippets.push(...rifs); + } + } + } + snippets.push(...importSnippets); + } + + if (helper.options.useRootPathContext && helper.treePath) { + const ctx = await this.rootPathContextService.getContextForPath( + helper.filepath, + helper.treePath, + ); + snippets.push(...ctx); + } + } + + return snippets; + } +} diff --git a/core/autocomplete/context/ranking/index.ts b/core/autocomplete/context/ranking/index.ts index 4809901cd..119056ca8 100644 --- a/core/autocomplete/context/ranking/index.ts +++ b/core/autocomplete/context/ranking/index.ts @@ -1,6 +1,7 @@ import { RangeInFileWithContents } from "../../../commands/util.js"; import { Range } from "../../../index.js"; import { countTokens } from "../../../llm/countTokens.js"; +import { HelperVars } from "../../HelperVars.js"; export type AutocompleteSnippet = RangeInFileWithContents & { score?: number; @@ -43,8 +44,18 @@ export function jaccardSimilarity(a: string, b: string): number { */ export function rankSnippets( ranges: AutocompleteSnippet[], - windowAroundCursor: string, + helper: HelperVars, ): Required[] { + const windowAroundCursor = + helper.fullPrefix.slice( + -helper.options.slidingWindowSize * + helper.options.slidingWindowPrefixPercentage, + ) + + helper.fullSuffix.slice( + helper.options.slidingWindowSize * + (1 - helper.options.slidingWindowPrefixPercentage), + ); + const snippets: Required[] = ranges.map((snippet) => ({ score: snippet.score ?? jaccardSimilarity(snippet.contents, windowAroundCursor), From 40dfede087707aefccd5e6333a498e5d0c67ec4f Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 31 Oct 2024 15:54:29 -0700 Subject: [PATCH 33/96] refactor constructPrompt --- core/autocomplete/HelperVars.ts | 9 +- .../constants/AutocompleteLanguageInfo.ts | 6 + core/autocomplete/constructPrompt.ts | 119 ++++++++++-------- core/autocomplete/context/ranking/index.ts | 2 +- .../templating/constructPrefixSuffix.ts | 3 +- core/commands/slash/share.ts | 2 +- core/util/parameters.ts | 2 +- extensions/vscode/src/util/expandSnippet.ts | 2 +- 8 files changed, 85 insertions(+), 60 deletions(-) diff --git a/core/autocomplete/HelperVars.ts b/core/autocomplete/HelperVars.ts index 2c9f0fe27..e5e3af61c 100644 --- a/core/autocomplete/HelperVars.ts +++ b/core/autocomplete/HelperVars.ts @@ -1,6 +1,8 @@ import { IDE, TabAutocompleteOptions } from ".."; -import { AutocompleteLanguageInfo } from "./constants/AutocompleteLanguageInfo"; -import { languageForFilepath } from "./constructPrompt"; +import { + AutocompleteLanguageInfo, + languageForFilepath, +} from "./constants/AutocompleteLanguageInfo"; import { constructInitialPrefixSuffix } from "./templating/constructPrefixSuffix"; import { AutocompleteInput } from "./types"; import { AstPath, getAst, getTreePathAtCursor } from "./util/ast"; @@ -71,6 +73,9 @@ export class HelperVars { get pos() { return this.input.pos; } + get maxSnippetTokens() { + return this.options.maxPromptTokens * this.options.maxSnippetPercentage; + } // Getters for lazy access get fileContents(): string { diff --git a/core/autocomplete/constants/AutocompleteLanguageInfo.ts b/core/autocomplete/constants/AutocompleteLanguageInfo.ts index 3af6e2e15..397d32ed6 100644 --- a/core/autocomplete/constants/AutocompleteLanguageInfo.ts +++ b/core/autocomplete/constants/AutocompleteLanguageInfo.ts @@ -346,3 +346,9 @@ export const LANGUAGES: { [extension: string]: AutocompleteLanguageInfo } = { yml: YAML, md: Markdown, }; + +export function languageForFilepath( + filepath: string, +): AutocompleteLanguageInfo { + return LANGUAGES[filepath.split(".").slice(-1)[0]] || Typescript; +} diff --git a/core/autocomplete/constructPrompt.ts b/core/autocomplete/constructPrompt.ts index c83e1b107..7c7d898e6 100644 --- a/core/autocomplete/constructPrompt.ts +++ b/core/autocomplete/constructPrompt.ts @@ -1,40 +1,20 @@ +import { Position, Range } from "../index.js"; import { countTokens, pruneLinesFromBottom, pruneLinesFromTop, } from "../llm/countTokens.js"; import { shouldCompleteMultiline } from "./classification/shouldCompleteMultiline.js"; -import { - AutocompleteLanguageInfo, - LANGUAGES, - Typescript, -} from "./constants/AutocompleteLanguageInfo.js"; import { ContextRetrievalService } from "./context/ContextRetrievalService.js"; import { fillPromptWithSnippets, - rankSnippets, + rankAndOrderSnippets, removeRangeFromSnippets, type AutocompleteSnippet, } from "./context/ranking/index.js"; import { HelperVars } from "./HelperVars.js"; -export function languageForFilepath( - filepath: string, -): AutocompleteLanguageInfo { - return LANGUAGES[filepath.split(".").slice(-1)[0]] || Typescript; -} - -export async function constructAutocompletePrompt( - helper: HelperVars, - extraSnippets: AutocompleteSnippet[], - contextRetrievalService: ContextRetrievalService, -): Promise<{ - prefix: string; - suffix: string; - useFim: boolean; - completeMultiline: boolean; - snippets: AutocompleteSnippet[]; -}> { +function prunePrefixSuffix(helper: HelperVars) { // Construct basic prefix const maxPrefixTokens = helper.options.maxPromptTokens * helper.options.prefixPercentage; @@ -56,46 +36,78 @@ export async function constructAutocompletePrompt( helper.modelName, ); + return { + prunedPrefix, + prunedSuffix, + }; +} + +function filterSnippetsAlreadyInCaretWindow( + snippets: AutocompleteSnippet[], + caretWindow: string, +): AutocompleteSnippet[] { + return snippets + .map((snippet) => ({ ...snippet })) + .filter( + (s) => + s.contents.trim() !== "" && !caretWindow.includes(s.contents.trim()), + ); +} + +function getRangeOfPrefixAndSuffixWithBuffer( + prefix: string, + suffix: string, + caretPos: Position, +): Range { + // Remove prefix range from snippets + const prefixLines = prefix.split("\n").length; + const suffixLines = suffix.split("\n").length; + const buffer = 8; + const prefixSuffixRangeWithBuffer = { + start: { + line: caretPos.line - prefixLines - buffer, + character: 0, + }, + end: { + line: caretPos.line + suffixLines + buffer, + character: 0, + }, + }; + + return prefixSuffixRangeWithBuffer; +} + +export async function constructAutocompletePrompt( + helper: HelperVars, + extraSnippets: AutocompleteSnippet[], + contextRetrievalService: ContextRetrievalService, +): Promise<{ + prefix: string; + suffix: string; + useFim: boolean; + completeMultiline: boolean; + snippets: AutocompleteSnippet[]; +}> { + // Prune prefix/suffix based on token budgets + const { prunedPrefix, prunedSuffix } = prunePrefixSuffix(helper); + let snippets = await contextRetrievalService.retrieve( prunedPrefix, helper, extraSnippets, ); - // Filter out empty snippets and ones that are already in the prefix/suffix - snippets = snippets - .map((snippet) => ({ ...snippet })) - .filter( - (s) => - s.contents.trim() !== "" && - !(prunedPrefix + prunedSuffix).includes(s.contents.trim()), - ); + snippets = filterSnippetsAlreadyInCaretWindow( + snippets, + prunedPrefix + prunedSuffix, + ); - // Rank / order the snippets - const scoredSnippets = rankSnippets(snippets, helper); + const scoredSnippets = rankAndOrderSnippets(snippets, helper); - // Fill maxSnippetTokens with snippets - const maxSnippetTokens = - helper.options.maxPromptTokens * helper.options.maxSnippetPercentage; - - // Remove prefix range from snippets - const prefixLines = prunedPrefix.split("\n").length; - const suffixLines = prunedSuffix.split("\n").length; - const buffer = 8; - const prefixSuffixRangeWithBuffer = { - start: { - line: helper.pos.line - prefixLines - buffer, - character: 0, - }, - end: { - line: helper.pos.line + suffixLines + buffer, - character: 0, - }, - }; let finalSnippets = removeRangeFromSnippets( scoredSnippets, helper.filepath.split("://").slice(-1)[0], - prefixSuffixRangeWithBuffer, + getRangeOfPrefixAndSuffixWithBuffer(prunedPrefix, prunedSuffix, helper.pos), ); // Filter snippets for those with best scores (must be above threshold) @@ -103,9 +115,10 @@ export async function constructAutocompletePrompt( (snippet) => snippet.score >= helper.options.recentlyEditedSimilarityThreshold, ); + finalSnippets = fillPromptWithSnippets( scoredSnippets, - maxSnippetTokens, + helper.maxSnippetTokens, helper.modelName, ); diff --git a/core/autocomplete/context/ranking/index.ts b/core/autocomplete/context/ranking/index.ts index 119056ca8..58e97cc04 100644 --- a/core/autocomplete/context/ranking/index.ts +++ b/core/autocomplete/context/ranking/index.ts @@ -42,7 +42,7 @@ export function jaccardSimilarity(a: string, b: string): number { /** * Rank code snippets to be used in tab-autocomplete prompt. Returns a sorted version of the snippet array. */ -export function rankSnippets( +export function rankAndOrderSnippets( ranges: AutocompleteSnippet[], helper: HelperVars, ): Required[] { diff --git a/core/autocomplete/templating/constructPrefixSuffix.ts b/core/autocomplete/templating/constructPrefixSuffix.ts index cead471c3..9bbffa181 100644 --- a/core/autocomplete/templating/constructPrefixSuffix.ts +++ b/core/autocomplete/templating/constructPrefixSuffix.ts @@ -1,6 +1,7 @@ import { IDE } from "../.."; import { getRangeInString } from "../../util/ranges"; -import { languageForFilepath } from "../constructPrompt"; +import { languageForFilepath } from "../constants/AutocompleteLanguageInfo"; + import { AutocompleteInput } from "../types"; /** diff --git a/core/commands/slash/share.ts b/core/commands/slash/share.ts index a615ec70d..a43b694da 100644 --- a/core/commands/slash/share.ts +++ b/core/commands/slash/share.ts @@ -1,7 +1,7 @@ import * as fs from "node:fs"; import { homedir } from "node:os"; import path from "path"; -import { languageForFilepath } from "../../autocomplete/constructPrompt.js"; +import { languageForFilepath } from "../../autocomplete/constants/AutocompleteLanguageInfo.js"; import { SlashCommand } from "../../index.js"; import { stripImages } from "../../llm/images.js"; diff --git a/core/util/parameters.ts b/core/util/parameters.ts index 4a99dec8c..7144ba4d6 100644 --- a/core/util/parameters.ts +++ b/core/util/parameters.ts @@ -12,7 +12,7 @@ export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = { slidingWindowPrefixPercentage: 0.75, slidingWindowSize: 500, maxSnippetPercentage: 0.6, - recentlyEditedSimilarityThreshold: 0.3, + recentlyEditedSimilarityThreshold: 0.0, // Effectively no threshold. useCache: true, onlyMyCode: true, useOtherFiles: true, diff --git a/extensions/vscode/src/util/expandSnippet.ts b/extensions/vscode/src/util/expandSnippet.ts index cd83691f7..10d1cda5b 100644 --- a/extensions/vscode/src/util/expandSnippet.ts +++ b/extensions/vscode/src/util/expandSnippet.ts @@ -1,5 +1,5 @@ import { Chunk, IDE } from "core"; -import { languageForFilepath } from "core/autocomplete/constructPrompt"; +import { languageForFilepath } from "core/autocomplete/constants/AutocompleteLanguageInfo"; import { DEFAULT_IGNORE_DIRS } from "core/indexing/ignore"; import { deduplicateArray } from "core/util"; import { getParserForFile } from "core/util/treeSitter"; From 3e1eca6c885f744c28c5f070512f784ca5f01f2d Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 31 Oct 2024 16:17:25 -0700 Subject: [PATCH 34/96] refactor multi-line decision --- core/autocomplete/CompletionProvider.ts | 12 ++- .../classification/shouldCompleteMultiline.ts | 77 ++++++------------- core/autocomplete/constructPrompt.ts | 8 +- core/autocomplete/context/ranking/index.ts | 3 +- core/autocomplete/templating/index.ts | 12 +-- 5 files changed, 35 insertions(+), 77 deletions(-) diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts index 50629e30e..ab8df6629 100644 --- a/core/autocomplete/CompletionProvider.ts +++ b/core/autocomplete/CompletionProvider.ts @@ -173,12 +173,11 @@ export class CompletionProvider { // or they might separately track recently edited ranges) const extraSnippets = await this._getExtraSnippets(helper); - let { prefix, suffix, completeMultiline, snippets } = - await constructAutocompletePrompt( - helper, - extraSnippets, - this.contextRetrievalService, - ); + let { prefix, suffix, snippets } = await constructAutocompletePrompt( + helper, + extraSnippets, + this.contextRetrievalService, + ); // If prefix is manually passed if (helper.input.manuallyPassPrefix) { @@ -191,7 +190,6 @@ export class CompletionProvider { suffix, snippets, await this.ide.getWorkspaceDirs(), - completeMultiline, helper, ); diff --git a/core/autocomplete/classification/shouldCompleteMultiline.ts b/core/autocomplete/classification/shouldCompleteMultiline.ts index d8df8aeb0..1c999fe01 100644 --- a/core/autocomplete/classification/shouldCompleteMultiline.ts +++ b/core/autocomplete/classification/shouldCompleteMultiline.ts @@ -1,17 +1,33 @@ -import { TabAutocompleteOptions } from "@continuedev/config-types"; import { AutocompleteLanguageInfo } from "../constants/AutocompleteLanguageInfo"; import { HelperVars } from "../HelperVars"; -import { AutocompleteInput } from "../types"; - -const BLOCK_TYPES = ["body", "statement_block"]; function isMidlineCompletion(prefix: string, suffix: string): boolean { return !suffix.startsWith("\n"); } -export async function shouldCompleteMultiline( +function shouldCompleteMultilineBasedOnLanguage( + language: AutocompleteLanguageInfo, + prefix: string, + suffix: string, +) { + let langMultilineDecision = language.useMultiline?.({ prefix, suffix }); + return langMultilineDecision; +} + +export function decideMultilineEarly( helper: HelperVars, -): Promise { + prefix: string, + suffix: string, +) { + switch (helper.options.multilineCompletions) { + case "always": + return true; + case "never": + return false; + default: + break; + } + // Don't complete multi-line if you are mid-line if (isMidlineCompletion(helper.fullPrefix, helper.fullSuffix)) { return false; @@ -28,56 +44,11 @@ export async function shouldCompleteMultiline( return false; } - return true; -} - -function shouldCompleteMultilineBasedOnLanguage( - language: AutocompleteLanguageInfo, - prefix: string, - suffix: string, -) { - let langMultilineDecision = language.useMultiline?.({ prefix, suffix }); - return langMultilineDecision; -} - -function shouldCompleteMultilineBasedOnSelectedCompletion( - selectedCompletionInfo: AutocompleteInput["selectedCompletionInfo"], - multilineCompletions: TabAutocompleteOptions["multilineCompletions"], - completeMultiline: boolean, -) { - return ( - !selectedCompletionInfo && // Only ever single-line if using intellisense selected value - multilineCompletions !== "never" && - (multilineCompletions === "always" || completeMultiline) - ); -} - -export function decideMultilineEarly({ - language, - prefix, - suffix, - selectedCompletionInfo, - multilineCompletions, - completeMultiline, -}: { - language: AutocompleteLanguageInfo; - prefix: string; - suffix: string; - selectedCompletionInfo: AutocompleteInput["selectedCompletionInfo"]; - multilineCompletions: TabAutocompleteOptions["multilineCompletions"]; - completeMultiline: boolean; -}) { - if (shouldCompleteMultilineBasedOnLanguage(language, prefix, suffix)) { + if (shouldCompleteMultilineBasedOnLanguage(helper.lang, prefix, suffix)) { return true; } - if ( - shouldCompleteMultilineBasedOnSelectedCompletion( - selectedCompletionInfo, - multilineCompletions, - completeMultiline, - ) - ) { + if (helper.input.selectedCompletionInfo) { return true; } diff --git a/core/autocomplete/constructPrompt.ts b/core/autocomplete/constructPrompt.ts index 7c7d898e6..62c28543e 100644 --- a/core/autocomplete/constructPrompt.ts +++ b/core/autocomplete/constructPrompt.ts @@ -4,7 +4,6 @@ import { pruneLinesFromBottom, pruneLinesFromTop, } from "../llm/countTokens.js"; -import { shouldCompleteMultiline } from "./classification/shouldCompleteMultiline.js"; import { ContextRetrievalService } from "./context/ContextRetrievalService.js"; import { fillPromptWithSnippets, @@ -84,8 +83,6 @@ export async function constructAutocompletePrompt( ): Promise<{ prefix: string; suffix: string; - useFim: boolean; - completeMultiline: boolean; snippets: AutocompleteSnippet[]; }> { // Prune prefix/suffix based on token budgets @@ -104,13 +101,14 @@ export async function constructAutocompletePrompt( const scoredSnippets = rankAndOrderSnippets(snippets, helper); + // This might be redundant with filterSnippetsAlreadyInCaretWindow let finalSnippets = removeRangeFromSnippets( scoredSnippets, helper.filepath.split("://").slice(-1)[0], getRangeOfPrefixAndSuffixWithBuffer(prunedPrefix, prunedSuffix, helper.pos), ); - // Filter snippets for those with best scores (must be above threshold) + // Filter snippets below similarity threshold finalSnippets = finalSnippets.filter( (snippet) => snippet.score >= helper.options.recentlyEditedSimilarityThreshold, @@ -127,8 +125,6 @@ export async function constructAutocompletePrompt( return { prefix: prunedPrefix, suffix: prunedSuffix, - useFim: true, - completeMultiline: await shouldCompleteMultiline(helper), snippets, }; } diff --git a/core/autocomplete/context/ranking/index.ts b/core/autocomplete/context/ranking/index.ts index 58e97cc04..aba29d7aa 100644 --- a/core/autocomplete/context/ranking/index.ts +++ b/core/autocomplete/context/ranking/index.ts @@ -130,7 +130,8 @@ function mergeOverlappingRangeContents( } /** - * Fill the allowed space with snippets + * Fill the allowed space with snippets. + * It is assumed that the snippets are sorted by score. */ export function fillPromptWithSnippets( snippets: Required[], diff --git a/core/autocomplete/templating/index.ts b/core/autocomplete/templating/index.ts index ad9dc7391..dea0f5885 100644 --- a/core/autocomplete/templating/index.ts +++ b/core/autocomplete/templating/index.ts @@ -1,6 +1,6 @@ import { CompletionOptions } from "../.."; import { getBasename, getLastNPathParts } from "../../util"; -import { decideMultilineEarly } from "../classification/shouldCompleteMultiline"; +import { decideMultilineEarly as shouldCompleteMultiline } from "../classification/shouldCompleteMultiline"; import { AutocompleteLanguageInfo } from "../constants/AutocompleteLanguageInfo"; import { AutocompleteSnippet } from "../context/ranking"; import { HelperVars } from "../HelperVars"; @@ -65,7 +65,6 @@ export function renderPrompt( suffix: string, snippets: AutocompleteSnippet[], workspaceDirs: string[], - completeMultiline: boolean, helper: HelperVars, ): [string, Partial | undefined, boolean] { let { @@ -115,14 +114,7 @@ export function renderPrompt( const multiline = !helper.options.transform || - decideMultilineEarly({ - multilineCompletions: helper.options.multilineCompletions, - language: helper.lang, - selectedCompletionInfo: helper.input.selectedCompletionInfo, - prefix, - suffix, - completeMultiline, - }); + shouldCompleteMultiline(helper, prefix, suffix); const stopTokens = getStopTokens( completionOptions, From 176c50210dbf4ee417fd02d1e42abfbf4b64b781 Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 31 Oct 2024 16:26:51 -0700 Subject: [PATCH 35/96] more refactoring --- core/autocomplete/CompletionProvider.ts | 10 ++-- core/autocomplete/README.md | 29 ----------- .../classification/shouldCompleteMultiline.ts | 13 ++--- core/autocomplete/constructPrompt.ts | 2 +- .../context/ContextRetrievalService.ts | 15 +++++- core/autocomplete/context/ranking/index.ts | 2 +- core/autocomplete/filtering/test/util.ts | 2 +- .../generation/CompletionStreamer.ts | 2 +- core/autocomplete/prefiltering/index.ts | 2 +- core/autocomplete/recentlyEdited.ts | 18 ------- .../templating/constructPrefixSuffix.ts | 2 +- core/autocomplete/templating/index.ts | 5 +- .../test/NEGATIVE_CASES_STARCODER.tsx | 51 ------------------- core/autocomplete/test/util.ts | 2 +- .../{ => util}/AutocompleteDebouncer.ts | 0 .../{ => util}/AutocompleteLoggingService.ts | 6 +-- .../{ => util}/AutocompleteLruCache.ts | 9 ++-- core/autocomplete/{ => util}/HelperVars.ts | 8 +-- core/autocomplete/{ => util}/types.ts | 11 ++-- core/protocol/core.ts | 2 +- 20 files changed, 57 insertions(+), 134 deletions(-) delete mode 100644 core/autocomplete/README.md delete mode 100644 core/autocomplete/recentlyEdited.ts delete mode 100644 core/autocomplete/test/NEGATIVE_CASES_STARCODER.tsx rename core/autocomplete/{ => util}/AutocompleteDebouncer.ts (100%) rename core/autocomplete/{ => util}/AutocompleteLoggingService.ts (96%) rename core/autocomplete/{ => util}/AutocompleteLruCache.ts (92%) rename core/autocomplete/{ => util}/HelperVars.ts (92%) rename core/autocomplete/{ => util}/types.ts (76%) diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts index ab8df6629..31f9d4aa6 100644 --- a/core/autocomplete/CompletionProvider.ts +++ b/core/autocomplete/CompletionProvider.ts @@ -8,16 +8,16 @@ import { postprocessCompletion } from "./postprocessing/index.js"; // @prettier-ignore import { TRIAL_FIM_MODEL } from "../config/onboarding.js"; import OpenAI from "../llm/llms/OpenAI.js"; -import { AutocompleteDebouncer } from "./AutocompleteDebouncer.js"; -import { AutocompleteLoggingService } from "./AutocompleteLoggingService.js"; -import AutocompleteLruCache from "./AutocompleteLruCache.js"; import { ContextRetrievalService } from "./context/ContextRetrievalService.js"; import { BracketMatchingService } from "./filtering/BracketMatchingService.js"; import { CompletionStreamer } from "./generation/CompletionStreamer.js"; -import { HelperVars } from "./HelperVars.js"; import { shouldPrefilter } from "./prefiltering/index.js"; import { renderPrompt } from "./templating/index.js"; -import { AutocompleteInput, AutocompleteOutcome } from "./types.js"; +import { AutocompleteDebouncer } from "./util/AutocompleteDebouncer.js"; +import { AutocompleteLoggingService } from "./util/AutocompleteLoggingService.js"; +import AutocompleteLruCache from "./util/AutocompleteLruCache.js"; +import { HelperVars } from "./util/HelperVars.js"; +import { AutocompleteInput, AutocompleteOutcome } from "./util/types.js"; const autocompleteCache = AutocompleteLruCache.get(); diff --git a/core/autocomplete/README.md b/core/autocomplete/README.md deleted file mode 100644 index 8b860a3cc..000000000 --- a/core/autocomplete/README.md +++ /dev/null @@ -1,29 +0,0 @@ -# Autocomplete - -The autocomplete pipeline: - -## 1. Triggering - -### Debouncing - -## 2. Context gathering - -## 3. Prompt construction - -This is fairly trivial, we just use the correct template/endpoint for the model. Any templates are defined in [`templates.ts`](./templates.ts). - -## 4. Caching - -## 4. Generation - -### Reusing previous requests - -## 4. Classification - -Is it multi-line or single-line? - -## 4. Filtering - -## 5. Postprocessing - -## 6. Telemetry diff --git a/core/autocomplete/classification/shouldCompleteMultiline.ts b/core/autocomplete/classification/shouldCompleteMultiline.ts index 1c999fe01..fb47cd467 100644 --- a/core/autocomplete/classification/shouldCompleteMultiline.ts +++ b/core/autocomplete/classification/shouldCompleteMultiline.ts @@ -1,5 +1,5 @@ import { AutocompleteLanguageInfo } from "../constants/AutocompleteLanguageInfo"; -import { HelperVars } from "../HelperVars"; +import { HelperVars } from "../util/HelperVars"; function isMidlineCompletion(prefix: string, suffix: string): boolean { return !suffix.startsWith("\n"); @@ -14,7 +14,7 @@ function shouldCompleteMultilineBasedOnLanguage( return langMultilineDecision; } -export function decideMultilineEarly( +export function shouldCompleteMultiline( helper: HelperVars, prefix: string, suffix: string, @@ -28,6 +28,11 @@ export function decideMultilineEarly( break; } + // Always single-line if an intellisense option is selected + if (helper.input.selectedCompletionInfo) { + return true; + } + // Don't complete multi-line if you are mid-line if (isMidlineCompletion(helper.fullPrefix, helper.fullSuffix)) { return false; @@ -48,9 +53,5 @@ export function decideMultilineEarly( return true; } - if (helper.input.selectedCompletionInfo) { - return true; - } - return false; } diff --git a/core/autocomplete/constructPrompt.ts b/core/autocomplete/constructPrompt.ts index 62c28543e..08bde361c 100644 --- a/core/autocomplete/constructPrompt.ts +++ b/core/autocomplete/constructPrompt.ts @@ -11,7 +11,7 @@ import { removeRangeFromSnippets, type AutocompleteSnippet, } from "./context/ranking/index.js"; -import { HelperVars } from "./HelperVars.js"; +import { HelperVars } from "./util/HelperVars.js"; function prunePrefixSuffix(helper: HelperVars) { // Construct basic prefix diff --git a/core/autocomplete/context/ContextRetrievalService.ts b/core/autocomplete/context/ContextRetrievalService.ts index cdf5f2bcd..21e9eddf4 100644 --- a/core/autocomplete/context/ContextRetrievalService.ts +++ b/core/autocomplete/context/ContextRetrievalService.ts @@ -1,10 +1,21 @@ import { IDE } from "../.."; -import { HelperVars } from "../HelperVars"; -import { findMatchingRange } from "../recentlyEdited"; +import { HelperVars } from "../util/HelperVars"; +import { RecentlyEditedRange } from "../util/types"; import { ImportDefinitionsService } from "./ImportDefinitionsService"; import { AutocompleteSnippet, getSymbolsForSnippet } from "./ranking"; import { RootPathContextService } from "./RootPathContextService"; +export function findMatchingRange( + recentlyEditedRanges: RecentlyEditedRange[], + linePrefix: string, +): RecentlyEditedRange | undefined { + return recentlyEditedRanges.find((recentlyEditedRange) => { + return recentlyEditedRange.lines.some((line) => + line.startsWith(linePrefix), + ); + }); +} + export class ContextRetrievalService { private importDefinitionsService: ImportDefinitionsService; private rootPathContextService: RootPathContextService; diff --git a/core/autocomplete/context/ranking/index.ts b/core/autocomplete/context/ranking/index.ts index aba29d7aa..e761d994e 100644 --- a/core/autocomplete/context/ranking/index.ts +++ b/core/autocomplete/context/ranking/index.ts @@ -1,7 +1,7 @@ import { RangeInFileWithContents } from "../../../commands/util.js"; import { Range } from "../../../index.js"; import { countTokens } from "../../../llm/countTokens.js"; -import { HelperVars } from "../../HelperVars.js"; +import { HelperVars } from "../../util/HelperVars.js"; export type AutocompleteSnippet = RangeInFileWithContents & { score?: number; diff --git a/core/autocomplete/filtering/test/util.ts b/core/autocomplete/filtering/test/util.ts index f8564e258..5a9b61a72 100644 --- a/core/autocomplete/filtering/test/util.ts +++ b/core/autocomplete/filtering/test/util.ts @@ -3,7 +3,7 @@ import path from "node:path"; import Mock from "../../../llm/llms/Mock"; import { testConfigHandler, testIde } from "../../../test/util/fixtures"; import { CompletionProvider } from "../../CompletionProvider"; -import { AutocompleteInput } from "../../types"; +import { AutocompleteInput } from "../../util/types"; const FIM_DELIMITER = "<|fim|>"; diff --git a/core/autocomplete/generation/CompletionStreamer.ts b/core/autocomplete/generation/CompletionStreamer.ts index a723a3c1b..11b0755d8 100644 --- a/core/autocomplete/generation/CompletionStreamer.ts +++ b/core/autocomplete/generation/CompletionStreamer.ts @@ -1,6 +1,6 @@ import { CompletionOptions, ILLM } from "../.."; import { StreamTransformPipeline } from "../filtering/streamTransforms/StreamTransformPipeline"; -import { HelperVars } from "../HelperVars"; +import { HelperVars } from "../util/HelperVars"; import { GeneratorReuseManager } from "./GeneratorReuseManager"; export class CompletionStreamer { diff --git a/core/autocomplete/prefiltering/index.ts b/core/autocomplete/prefiltering/index.ts index 45b521511..c844696ac 100644 --- a/core/autocomplete/prefiltering/index.ts +++ b/core/autocomplete/prefiltering/index.ts @@ -2,7 +2,7 @@ import path from "node:path"; import { IDE } from "../.."; import { getBasename } from "../../util"; import { getConfigJsonPath } from "../../util/paths"; -import { HelperVars } from "../HelperVars"; +import { HelperVars } from "../util/HelperVars"; async function isDisabledForFile( currentFilepath: string, diff --git a/core/autocomplete/recentlyEdited.ts b/core/autocomplete/recentlyEdited.ts deleted file mode 100644 index d0e7817ed..000000000 --- a/core/autocomplete/recentlyEdited.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { RangeInFile } from "../index.js"; - -export type RecentlyEditedRange = RangeInFile & { - timestamp: number; - lines: string[]; - symbols: Set; -}; - -export function findMatchingRange( - recentlyEditedRanges: RecentlyEditedRange[], - linePrefix: string, -): RecentlyEditedRange | undefined { - return recentlyEditedRanges.find((recentlyEditedRange) => { - return recentlyEditedRange.lines.some((line) => - line.startsWith(linePrefix), - ); - }); -} diff --git a/core/autocomplete/templating/constructPrefixSuffix.ts b/core/autocomplete/templating/constructPrefixSuffix.ts index 9bbffa181..d4024bf06 100644 --- a/core/autocomplete/templating/constructPrefixSuffix.ts +++ b/core/autocomplete/templating/constructPrefixSuffix.ts @@ -2,7 +2,7 @@ import { IDE } from "../.."; import { getRangeInString } from "../../util/ranges"; import { languageForFilepath } from "../constants/AutocompleteLanguageInfo"; -import { AutocompleteInput } from "../types"; +import { AutocompleteInput } from "../util/types"; /** * We have to handle a few edge cases in getting the entire prefix/suffix for the current file. diff --git a/core/autocomplete/templating/index.ts b/core/autocomplete/templating/index.ts index dea0f5885..a8723cb6c 100644 --- a/core/autocomplete/templating/index.ts +++ b/core/autocomplete/templating/index.ts @@ -1,9 +1,9 @@ import { CompletionOptions } from "../.."; import { getBasename, getLastNPathParts } from "../../util"; -import { decideMultilineEarly as shouldCompleteMultiline } from "../classification/shouldCompleteMultiline"; +import { shouldCompleteMultiline } from "../classification/shouldCompleteMultiline"; import { AutocompleteLanguageInfo } from "../constants/AutocompleteLanguageInfo"; import { AutocompleteSnippet } from "../context/ranking"; -import { HelperVars } from "../HelperVars"; +import { HelperVars } from "../util/HelperVars"; import { getTemplateForModel } from "./AutocompleteTemplate"; import { getStopTokens } from "./getStopTokens"; @@ -60,6 +60,7 @@ function renderStringTemplate( }); return prompt; } + export function renderPrompt( prefix: string, suffix: string, diff --git a/core/autocomplete/test/NEGATIVE_CASES_STARCODER.tsx b/core/autocomplete/test/NEGATIVE_CASES_STARCODER.tsx deleted file mode 100644 index 269d25f0f..000000000 --- a/core/autocomplete/test/NEGATIVE_CASES_STARCODER.tsx +++ /dev/null @@ -1,51 +0,0 @@ -##### Prompt ##### -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; - } -} -========================================================================== -========================================================================== -Completion: - - this.result /= number; - return this; - } -} - -module.exports = Calculator; \ No newline at end of file diff --git a/core/autocomplete/test/util.ts b/core/autocomplete/test/util.ts index 85dbc60b3..bfcf31885 100644 --- a/core/autocomplete/test/util.ts +++ b/core/autocomplete/test/util.ts @@ -3,7 +3,7 @@ import path from "node:path"; import Mock from "../../llm/llms/Mock"; import { testConfigHandler, testIde } from "../../test/util/fixtures"; import { CompletionProvider } from "../CompletionProvider"; -import { AutocompleteInput } from "../types"; +import { AutocompleteInput } from "../util/types"; const FIM_DELIMITER = "<|fim|>"; diff --git a/core/autocomplete/AutocompleteDebouncer.ts b/core/autocomplete/util/AutocompleteDebouncer.ts similarity index 100% rename from core/autocomplete/AutocompleteDebouncer.ts rename to core/autocomplete/util/AutocompleteDebouncer.ts diff --git a/core/autocomplete/AutocompleteLoggingService.ts b/core/autocomplete/util/AutocompleteLoggingService.ts similarity index 96% rename from core/autocomplete/AutocompleteLoggingService.ts rename to core/autocomplete/util/AutocompleteLoggingService.ts index 6771b1dd6..7fd3d24cb 100644 --- a/core/autocomplete/AutocompleteLoggingService.ts +++ b/core/autocomplete/util/AutocompleteLoggingService.ts @@ -1,6 +1,6 @@ -import { logDevData } from "../util/devdata"; -import { COUNT_COMPLETION_REJECTED_AFTER } from "../util/parameters"; -import { Telemetry } from "../util/posthog"; +import { logDevData } from "../../util/devdata"; +import { COUNT_COMPLETION_REJECTED_AFTER } from "../../util/parameters"; +import { Telemetry } from "../../util/posthog"; import { AutocompleteOutcome } from "./types"; export class AutocompleteLoggingService { diff --git a/core/autocomplete/AutocompleteLruCache.ts b/core/autocomplete/util/AutocompleteLruCache.ts similarity index 92% rename from core/autocomplete/AutocompleteLruCache.ts rename to core/autocomplete/util/AutocompleteLruCache.ts index c04770a4c..ec9478c8a 100644 --- a/core/autocomplete/AutocompleteLruCache.ts +++ b/core/autocomplete/util/AutocompleteLruCache.ts @@ -1,14 +1,17 @@ import { Mutex } from "async-mutex"; import { open } from "sqlite"; import sqlite3 from "sqlite3"; -import { DatabaseConnection, truncateSqliteLikePattern } from "../indexing/refreshIndex.js"; -import { getTabAutocompleteCacheSqlitePath } from "../util/paths.js"; +import { + DatabaseConnection, + truncateSqliteLikePattern, +} from "../../indexing/refreshIndex.js"; +import { getTabAutocompleteCacheSqlitePath } from "../../util/paths.js"; export class AutocompleteLruCache { private static capacity = 1000; private mutex = new Mutex(); - constructor(private db: DatabaseConnection) { } + constructor(private db: DatabaseConnection) {} static async get(): Promise { const db = await open({ diff --git a/core/autocomplete/HelperVars.ts b/core/autocomplete/util/HelperVars.ts similarity index 92% rename from core/autocomplete/HelperVars.ts rename to core/autocomplete/util/HelperVars.ts index e5e3af61c..57a81e668 100644 --- a/core/autocomplete/HelperVars.ts +++ b/core/autocomplete/util/HelperVars.ts @@ -1,11 +1,11 @@ -import { IDE, TabAutocompleteOptions } from ".."; +import { IDE, TabAutocompleteOptions } from "../.."; import { AutocompleteLanguageInfo, languageForFilepath, -} from "./constants/AutocompleteLanguageInfo"; -import { constructInitialPrefixSuffix } from "./templating/constructPrefixSuffix"; +} from "../constants/AutocompleteLanguageInfo"; +import { constructInitialPrefixSuffix } from "../templating/constructPrefixSuffix"; +import { AstPath, getAst, getTreePathAtCursor } from "./ast"; import { AutocompleteInput } from "./types"; -import { AstPath, getAst, getTreePathAtCursor } from "./util/ast"; /** * A collection of variables that are often accessed throughout the autocomplete pipeline diff --git a/core/autocomplete/types.ts b/core/autocomplete/util/types.ts similarity index 76% rename from core/autocomplete/types.ts rename to core/autocomplete/util/types.ts index 745ea563b..44ee9fab1 100644 --- a/core/autocomplete/types.ts +++ b/core/autocomplete/util/types.ts @@ -1,6 +1,11 @@ -import { Position, Range, TabAutocompleteOptions } from ".."; -import { RangeInFileWithContents } from "../commands/util"; -import { RecentlyEditedRange } from "./recentlyEdited"; +import { Position, Range, RangeInFile, TabAutocompleteOptions } from "../.."; +import { RangeInFileWithContents } from "../../commands/util"; + +export type RecentlyEditedRange = RangeInFile & { + timestamp: number; + lines: string[]; + symbols: Set; +}; export interface AutocompleteInput { completionId: string; diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 090ee2c5a..abe6c8fe1 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -15,7 +15,7 @@ import type { SessionInfo, SiteIndexingConfig, } from "../"; -import { AutocompleteInput } from "../autocomplete/types"; +import { AutocompleteInput } from "../autocomplete/util/types"; import { ProfileDescription } from "../config/ConfigHandler"; export type ProtocolGeneratorType = AsyncGenerator<{ From bf13f2004283603b71b22061b7366cf3fc1a62c1 Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 31 Oct 2024 16:27:44 -0700 Subject: [PATCH 36/96] fix type errs --- extensions/vscode/src/autocomplete/completionProvider.ts | 2 +- extensions/vscode/src/autocomplete/recentlyEdited.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index d9244ebfc..b1af40435 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -3,7 +3,7 @@ import { CompletionProvider } from "core/autocomplete/completionProvider"; import { type AutocompleteInput, type AutocompleteOutcome, -} from "core/autocomplete/types"; +} from "core/autocomplete/util/types"; import { ConfigHandler } from "core/config/ConfigHandler"; import { v4 as uuidv4 } from "uuid"; import * as vscode from "vscode"; diff --git a/extensions/vscode/src/autocomplete/recentlyEdited.ts b/extensions/vscode/src/autocomplete/recentlyEdited.ts index c32739b1c..0b206eab2 100644 --- a/extensions/vscode/src/autocomplete/recentlyEdited.ts +++ b/extensions/vscode/src/autocomplete/recentlyEdited.ts @@ -1,5 +1,5 @@ import { getSymbolsForSnippet } from "core/autocomplete/context/ranking"; -import { RecentlyEditedRange } from "core/autocomplete/recentlyEdited"; +import { RecentlyEditedRange } from "core/autocomplete/util/types"; import { RangeInFileWithContents } from "core/commands/util"; import * as vscode from "vscode"; From ef4b32975d052f5e768613c185c8a486e8fc4a75 Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 31 Oct 2024 16:41:03 -0700 Subject: [PATCH 37/96] refactor context retrieval service --- core/autocomplete/constructPrompt.ts | 2 +- .../context/ContextRetrievalService.ts | 150 +++++++++++------- 2 files changed, 90 insertions(+), 62 deletions(-) diff --git a/core/autocomplete/constructPrompt.ts b/core/autocomplete/constructPrompt.ts index 08bde361c..fdf16abad 100644 --- a/core/autocomplete/constructPrompt.ts +++ b/core/autocomplete/constructPrompt.ts @@ -88,7 +88,7 @@ export async function constructAutocompletePrompt( // Prune prefix/suffix based on token budgets const { prunedPrefix, prunedSuffix } = prunePrefixSuffix(helper); - let snippets = await contextRetrievalService.retrieve( + let snippets = await contextRetrievalService.retrieveCandidateSnippets( prunedPrefix, helper, extraSnippets, diff --git a/core/autocomplete/context/ContextRetrievalService.ts b/core/autocomplete/context/ContextRetrievalService.ts index 21e9eddf4..b8484421d 100644 --- a/core/autocomplete/context/ContextRetrievalService.ts +++ b/core/autocomplete/context/ContextRetrievalService.ts @@ -5,17 +5,6 @@ import { ImportDefinitionsService } from "./ImportDefinitionsService"; import { AutocompleteSnippet, getSymbolsForSnippet } from "./ranking"; import { RootPathContextService } from "./RootPathContextService"; -export function findMatchingRange( - recentlyEditedRanges: RecentlyEditedRange[], - linePrefix: string, -): RecentlyEditedRange | undefined { - return recentlyEditedRanges.find((recentlyEditedRange) => { - return recentlyEditedRange.lines.some((line) => - line.startsWith(linePrefix), - ); - }); -} - export class ContextRetrievalService { private importDefinitionsService: ImportDefinitionsService; private rootPathContextService: RootPathContextService; @@ -28,69 +17,108 @@ export class ContextRetrievalService { ); } - public async retrieve( + private getSnippetsFromRecentlyEditedRanges( + prunedPrefix: string, + helper: HelperVars, + ): AutocompleteSnippet[] { + if (helper.options.useRecentlyEdited === false) { + return []; + } + + const currentLinePrefix = prunedPrefix.trim().split("\n").slice(-1)[0]; + if ( + currentLinePrefix?.length > helper.options.recentLinePrefixMatchMinLength + ) { + const matchingRange = this.findMatchingRange( + helper.input.recentlyEditedRanges, + currentLinePrefix, + ); + + if (matchingRange) { + return [ + { + ...matchingRange, + contents: matchingRange.lines.join("\n"), + score: 0.8, + }, + ]; + } + } + + return []; + } + + private async getSnippetsFromImportDefinitions( + helper: HelperVars, + ): Promise { + if (helper.options.useImports === false) { + return []; + } + + const importSnippets = []; + const fileInfo = this.importDefinitionsService.get(helper.filepath); + if (fileInfo) { + const { imports } = fileInfo; + // Look for imports of any symbols around the current range + const textAroundCursor = + helper.fullPrefix.split("\n").slice(-5).join("\n") + + helper.fullSuffix.split("\n").slice(0, 3).join("\n"); + const symbols = Array.from(getSymbolsForSnippet(textAroundCursor)).filter( + (symbol) => !helper.lang.topLevelKeywords.includes(symbol), + ); + for (const symbol of symbols) { + const rifs = imports[symbol]; + if (Array.isArray(rifs)) { + importSnippets.push(...rifs); + } + } + } + return importSnippets; + } + + public async retrieveCandidateSnippets( prunedPrefix: string, helper: HelperVars, extraSnippets: AutocompleteSnippet[], ) { - // Find external snippets + if (helper.options.useOtherFiles === false) { + return []; + } + let snippets: AutocompleteSnippet[] = []; - if (helper.options.useOtherFiles) { - snippets.push(...extraSnippets); + // Snippets injected by the IDE for IDE-specific reasons + snippets.push(...extraSnippets); - if (helper.options.useRecentlyEdited) { - const currentLinePrefix = prunedPrefix.trim().split("\n").slice(-1)[0]; - if ( - currentLinePrefix?.length > - helper.options.recentLinePrefixMatchMinLength - ) { - const matchingRange = findMatchingRange( - helper.input.recentlyEditedRanges, - currentLinePrefix, - ); - if (matchingRange) { - snippets.push({ - ...matchingRange, - contents: matchingRange.lines.join("\n"), - score: 0.8, - }); - } - } - } + // If a recently edited range has a line that is a perfect match with the start of the current line + snippets.push( + ...this.getSnippetsFromRecentlyEditedRanges(prunedPrefix, helper), + ); - // Use imports - if (helper.options.useImports) { - const importSnippets = []; - const fileInfo = this.importDefinitionsService.get(helper.filepath); - if (fileInfo) { - const { imports } = fileInfo; - // Look for imports of any symbols around the current range - const textAroundCursor = - helper.fullPrefix.split("\n").slice(-5).join("\n") + - helper.fullSuffix.split("\n").slice(0, 3).join("\n"); - const symbols = Array.from( - getSymbolsForSnippet(textAroundCursor), - ).filter((symbol) => !helper.lang.topLevelKeywords.includes(symbol)); - for (const symbol of symbols) { - const rifs = imports[symbol]; - if (Array.isArray(rifs)) { - importSnippets.push(...rifs); - } - } - } - snippets.push(...importSnippets); - } + // Import definitions of any symbols in near range of the caret + snippets.push(...(await this.getSnippetsFromImportDefinitions(helper))); - if (helper.options.useRootPathContext && helper.treePath) { - const ctx = await this.rootPathContextService.getContextForPath( + // Root path context https://blog.continue.dev/root-path-context-the-secret-ingredient-in-continues-autocomplete-prompt/ + if (helper.options.useRootPathContext && helper.treePath) { + snippets.push( + ...(await this.rootPathContextService.getContextForPath( helper.filepath, helper.treePath, - ); - snippets.push(...ctx); - } + )), + ); } return snippets; } + + findMatchingRange( + recentlyEditedRanges: RecentlyEditedRange[], + linePrefix: string, + ): RecentlyEditedRange | undefined { + return recentlyEditedRanges.find((recentlyEditedRange) => { + return recentlyEditedRange.lines.some((line) => + line.startsWith(linePrefix), + ); + }); + } } From 263dbaef8c38c6a480a141923c490384699e8d46 Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 31 Oct 2024 18:05:32 -0700 Subject: [PATCH 38/96] more refactoring --- core/autocomplete/CompletionProvider.ts | 39 +++++----- .../classification/shouldCompleteMultiline.ts | 14 ++-- core/autocomplete/constructPrompt.ts | 59 ++------------- .../context/ContextRetrievalService.ts | 73 +++++++++---------- .../templating/AutocompleteTemplate.ts | 2 +- core/autocomplete/templating/index.ts | 50 ++++++++----- core/autocomplete/util/HelperVars.ts | 40 ++++++++++ 7 files changed, 144 insertions(+), 133 deletions(-) diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts index 31f9d4aa6..2c7950288 100644 --- a/core/autocomplete/CompletionProvider.ts +++ b/core/autocomplete/CompletionProvider.ts @@ -8,6 +8,7 @@ import { postprocessCompletion } from "./postprocessing/index.js"; // @prettier-ignore import { TRIAL_FIM_MODEL } from "../config/onboarding.js"; import OpenAI from "../llm/llms/OpenAI.js"; +import { shouldCompleteMultiline } from "./classification/shouldCompleteMultiline.js"; import { ContextRetrievalService } from "./context/ContextRetrievalService.js"; import { BracketMatchingService } from "./filtering/BracketMatchingService.js"; import { CompletionStreamer } from "./generation/CompletionStreamer.js"; @@ -173,32 +174,25 @@ export class CompletionProvider { // or they might separately track recently edited ranges) const extraSnippets = await this._getExtraSnippets(helper); - let { prefix, suffix, snippets } = await constructAutocompletePrompt( + let snippets = await constructAutocompletePrompt( helper, extraSnippets, this.contextRetrievalService, ); - // If prefix is manually passed - if (helper.input.manuallyPassPrefix) { - prefix = helper.input.manuallyPassPrefix; - suffix = ""; - } - - const [prompt, completionOptions, multiline] = renderPrompt( - prefix, - suffix, - snippets, - await this.ide.getWorkspaceDirs(), - helper, - ); + const { + prompt, + prefix: finalPrefix, + suffix: finalSuffix, + completionOptions, + } = renderPrompt(snippets, await this.ide.getWorkspaceDirs(), helper); // Completion let completion: string | undefined = ""; const cache = await autocompleteCache; const cachedCompletion = helper.options.useCache - ? await cache.get(prefix) + ? await cache.get(helper.prunedPrefix) : undefined; let cacheHit = false; if (cachedCompletion) { @@ -206,12 +200,15 @@ export class CompletionProvider { cacheHit = true; completion = cachedCompletion; } else { + const multiline = + !helper.options.transform || shouldCompleteMultiline(helper); + const completionStream = this.completionStreamer.streamCompletionWithFilters( token, llm, - prefix, - suffix, + finalPrefix, + finalSuffix, prompt, multiline, completionOptions, @@ -230,8 +227,8 @@ export class CompletionProvider { const processedCompletion = helper.options.transform ? postprocessCompletion({ completion, - prefix, - suffix, + prefix: helper.prunedPrefix, + suffix: helper.prunedSuffix, llm, }) : completion; @@ -246,8 +243,8 @@ export class CompletionProvider { const outcome: AutocompleteOutcome = { time: Date.now() - startTime, completion, - prefix, - suffix, + prefix: finalPrefix, + suffix: finalSuffix, prompt, modelProvider: llm.providerName, modelName: llm.model, diff --git a/core/autocomplete/classification/shouldCompleteMultiline.ts b/core/autocomplete/classification/shouldCompleteMultiline.ts index fb47cd467..16d2a6c47 100644 --- a/core/autocomplete/classification/shouldCompleteMultiline.ts +++ b/core/autocomplete/classification/shouldCompleteMultiline.ts @@ -14,11 +14,7 @@ function shouldCompleteMultilineBasedOnLanguage( return langMultilineDecision; } -export function shouldCompleteMultiline( - helper: HelperVars, - prefix: string, - suffix: string, -) { +export function shouldCompleteMultiline(helper: HelperVars) { switch (helper.options.multilineCompletions) { case "always": return true; @@ -49,7 +45,13 @@ export function shouldCompleteMultiline( return false; } - if (shouldCompleteMultilineBasedOnLanguage(helper.lang, prefix, suffix)) { + if ( + shouldCompleteMultilineBasedOnLanguage( + helper.lang, + helper.prunedPrefix, + helper.prunedSuffix, + ) + ) { return true; } diff --git a/core/autocomplete/constructPrompt.ts b/core/autocomplete/constructPrompt.ts index fdf16abad..2c5d43f42 100644 --- a/core/autocomplete/constructPrompt.ts +++ b/core/autocomplete/constructPrompt.ts @@ -1,9 +1,4 @@ import { Position, Range } from "../index.js"; -import { - countTokens, - pruneLinesFromBottom, - pruneLinesFromTop, -} from "../llm/countTokens.js"; import { ContextRetrievalService } from "./context/ContextRetrievalService.js"; import { fillPromptWithSnippets, @@ -13,34 +8,6 @@ import { } from "./context/ranking/index.js"; import { HelperVars } from "./util/HelperVars.js"; -function prunePrefixSuffix(helper: HelperVars) { - // Construct basic prefix - const maxPrefixTokens = - helper.options.maxPromptTokens * helper.options.prefixPercentage; - const prunedPrefix = pruneLinesFromTop( - helper.fullPrefix, - maxPrefixTokens, - helper.modelName, - ); - - // Construct suffix - const maxSuffixTokens = Math.min( - helper.options.maxPromptTokens - - countTokens(prunedPrefix, helper.modelName), - helper.options.maxSuffixPercentage * helper.options.maxPromptTokens, - ); - const prunedSuffix = pruneLinesFromBottom( - helper.fullSuffix, - maxSuffixTokens, - helper.modelName, - ); - - return { - prunedPrefix, - prunedSuffix, - }; -} - function filterSnippetsAlreadyInCaretWindow( snippets: AutocompleteSnippet[], caretWindow: string, @@ -80,23 +47,15 @@ export async function constructAutocompletePrompt( helper: HelperVars, extraSnippets: AutocompleteSnippet[], contextRetrievalService: ContextRetrievalService, -): Promise<{ - prefix: string; - suffix: string; - snippets: AutocompleteSnippet[]; -}> { - // Prune prefix/suffix based on token budgets - const { prunedPrefix, prunedSuffix } = prunePrefixSuffix(helper); - +): Promise { let snippets = await contextRetrievalService.retrieveCandidateSnippets( - prunedPrefix, helper, extraSnippets, ); snippets = filterSnippetsAlreadyInCaretWindow( snippets, - prunedPrefix + prunedSuffix, + helper.prunedCaretWindow, ); const scoredSnippets = rankAndOrderSnippets(snippets, helper); @@ -105,7 +64,11 @@ export async function constructAutocompletePrompt( let finalSnippets = removeRangeFromSnippets( scoredSnippets, helper.filepath.split("://").slice(-1)[0], - getRangeOfPrefixAndSuffixWithBuffer(prunedPrefix, prunedSuffix, helper.pos), + getRangeOfPrefixAndSuffixWithBuffer( + helper.prunedPrefix, + helper.prunedSuffix, + helper.pos, + ), ); // Filter snippets below similarity threshold @@ -120,11 +83,5 @@ export async function constructAutocompletePrompt( helper.modelName, ); - snippets = finalSnippets; - - return { - prefix: prunedPrefix, - suffix: prunedSuffix, - snippets, - }; + return finalSnippets; } diff --git a/core/autocomplete/context/ContextRetrievalService.ts b/core/autocomplete/context/ContextRetrievalService.ts index b8484421d..3c6ed3376 100644 --- a/core/autocomplete/context/ContextRetrievalService.ts +++ b/core/autocomplete/context/ContextRetrievalService.ts @@ -17,15 +17,49 @@ export class ContextRetrievalService { ); } + public async retrieveCandidateSnippets( + helper: HelperVars, + extraSnippets: AutocompleteSnippet[], + ) { + if (helper.options.useOtherFiles === false) { + return []; + } + + let snippets: AutocompleteSnippet[] = []; + + // Snippets injected by the IDE for IDE-specific reasons + snippets.push(...extraSnippets); + + // If a recently edited range has a line that is a perfect match with the start of the current line + snippets.push(...this.getSnippetsFromRecentlyEditedRanges(helper)); + + // Import definitions of any symbols in near range of the caret + snippets.push(...(await this.getSnippetsFromImportDefinitions(helper))); + + // Root path context https://blog.continue.dev/root-path-context-the-secret-ingredient-in-continues-autocomplete-prompt/ + if (helper.options.useRootPathContext && helper.treePath) { + snippets.push( + ...(await this.rootPathContextService.getContextForPath( + helper.filepath, + helper.treePath, + )), + ); + } + + return snippets; + } + private getSnippetsFromRecentlyEditedRanges( - prunedPrefix: string, helper: HelperVars, ): AutocompleteSnippet[] { if (helper.options.useRecentlyEdited === false) { return []; } - const currentLinePrefix = prunedPrefix.trim().split("\n").slice(-1)[0]; + const currentLinePrefix = helper.prunedPrefix + .trim() + .split("\n") + .slice(-1)[0]; if ( currentLinePrefix?.length > helper.options.recentLinePrefixMatchMinLength ) { @@ -76,41 +110,6 @@ export class ContextRetrievalService { return importSnippets; } - public async retrieveCandidateSnippets( - prunedPrefix: string, - helper: HelperVars, - extraSnippets: AutocompleteSnippet[], - ) { - if (helper.options.useOtherFiles === false) { - return []; - } - - let snippets: AutocompleteSnippet[] = []; - - // Snippets injected by the IDE for IDE-specific reasons - snippets.push(...extraSnippets); - - // If a recently edited range has a line that is a perfect match with the start of the current line - snippets.push( - ...this.getSnippetsFromRecentlyEditedRanges(prunedPrefix, helper), - ); - - // Import definitions of any symbols in near range of the caret - snippets.push(...(await this.getSnippetsFromImportDefinitions(helper))); - - // Root path context https://blog.continue.dev/root-path-context-the-secret-ingredient-in-continues-autocomplete-prompt/ - if (helper.options.useRootPathContext && helper.treePath) { - snippets.push( - ...(await this.rootPathContextService.getContextForPath( - helper.filepath, - helper.treePath, - )), - ); - } - - return snippets; - } - findMatchingRange( recentlyEditedRanges: RecentlyEditedRange[], linePrefix: string, diff --git a/core/autocomplete/templating/AutocompleteTemplate.ts b/core/autocomplete/templating/AutocompleteTemplate.ts index 034426f91..ae8cf1487 100644 --- a/core/autocomplete/templating/AutocompleteTemplate.ts +++ b/core/autocomplete/templating/AutocompleteTemplate.ts @@ -4,7 +4,7 @@ import { CompletionOptions } from "../../index.js"; import { getLastNPathParts, shortestRelativePaths } from "../../util/index.js"; import { AutocompleteSnippet } from "../context/ranking/index.js"; -interface AutocompleteTemplate { +export interface AutocompleteTemplate { compilePrefixSuffix?: ( prefix: string, suffix: string, diff --git a/core/autocomplete/templating/index.ts b/core/autocomplete/templating/index.ts index a8723cb6c..6ee99b862 100644 --- a/core/autocomplete/templating/index.ts +++ b/core/autocomplete/templating/index.ts @@ -1,10 +1,12 @@ import { CompletionOptions } from "../.."; import { getBasename, getLastNPathParts } from "../../util"; -import { shouldCompleteMultiline } from "../classification/shouldCompleteMultiline"; import { AutocompleteLanguageInfo } from "../constants/AutocompleteLanguageInfo"; import { AutocompleteSnippet } from "../context/ranking"; import { HelperVars } from "../util/HelperVars"; -import { getTemplateForModel } from "./AutocompleteTemplate"; +import { + AutocompleteTemplate, + getTemplateForModel, +} from "./AutocompleteTemplate"; import { getStopTokens } from "./getStopTokens"; export function formatExternalSnippet( @@ -61,24 +63,42 @@ function renderStringTemplate( return prompt; } +function getTemplate(helper: HelperVars): AutocompleteTemplate { + if (helper.options.template) { + return { + template: helper.options.template, + completionOptions: {}, + compilePrefixSuffix: undefined, + }; + } + return getTemplateForModel(helper.modelName); +} + export function renderPrompt( - prefix: string, - suffix: string, snippets: AutocompleteSnippet[], workspaceDirs: string[], helper: HelperVars, -): [string, Partial | undefined, boolean] { - let { - template, - completionOptions, - compilePrefixSuffix = undefined, - } = helper.options.template - ? { template: helper.options.template, completionOptions: {} } - : getTemplateForModel(helper.modelName); +): { + prompt: string; + prefix: string; + suffix: string; + completionOptions: Partial | undefined; +} { + // If prefix is manually passed + let prefix = helper.prunedPrefix; + let suffix = helper.prunedSuffix; + + if (helper.input.manuallyPassPrefix) { + prefix = helper.input.manuallyPassPrefix; + suffix = ""; + } let prompt: string; const reponame = getBasename(workspaceDirs[0] ?? "myproject"); + let { template, compilePrefixSuffix, completionOptions } = + getTemplate(helper); + // Some models have prompts that need two passes. This lets us pass the compiled prefix/suffix // into either the 2nd template to generate a raw string, or to pass prefix, suffix to a FIM endpoint if (compilePrefixSuffix) { @@ -113,10 +133,6 @@ export function renderPrompt( ); } - const multiline = - !helper.options.transform || - shouldCompleteMultiline(helper, prefix, suffix); - const stopTokens = getStopTokens( completionOptions, helper.lang, @@ -128,5 +144,5 @@ export function renderPrompt( stop: stopTokens, }; - return [prompt, completionOptions, multiline]; + return { prompt, prefix, suffix, completionOptions }; } diff --git a/core/autocomplete/util/HelperVars.ts b/core/autocomplete/util/HelperVars.ts index 57a81e668..dd8eb717b 100644 --- a/core/autocomplete/util/HelperVars.ts +++ b/core/autocomplete/util/HelperVars.ts @@ -1,4 +1,9 @@ import { IDE, TabAutocompleteOptions } from "../.."; +import { + countTokens, + pruneLinesFromBottom, + pruneLinesFromTop, +} from "../../llm/countTokens"; import { AutocompleteLanguageInfo, languageForFilepath, @@ -14,6 +19,8 @@ import { AutocompleteInput } from "./types"; export class HelperVars { lang: AutocompleteLanguageInfo; treePath: AstPath | undefined; + prunedPrefix: string; + prunedSuffix: string; private _fileContents: string | undefined; private _fileLines: string[] | undefined; @@ -27,6 +34,9 @@ export class HelperVars { private readonly ide: IDE, ) { this.lang = languageForFilepath(input.filepath); + const { prunedPrefix, prunedSuffix } = this.prunePrefixSuffix(); + this.prunedPrefix = prunedPrefix; + this.prunedSuffix = prunedSuffix; } private async init() { @@ -66,6 +76,33 @@ export class HelperVars { return instance; } + prunePrefixSuffix() { + // Construct basic prefix + const maxPrefixTokens = + this.options.maxPromptTokens * this.options.prefixPercentage; + const prunedPrefix = pruneLinesFromTop( + this.fullPrefix, + maxPrefixTokens, + this.modelName, + ); + + // Construct suffix + const maxSuffixTokens = Math.min( + this.options.maxPromptTokens - countTokens(prunedPrefix, this.modelName), + this.options.maxSuffixPercentage * this.options.maxPromptTokens, + ); + const prunedSuffix = pruneLinesFromBottom( + this.fullSuffix, + maxSuffixTokens, + this.modelName, + ); + + return { + prunedPrefix, + prunedSuffix, + }; + } + // Fast access get filepath() { return this.input.filepath; @@ -76,6 +113,9 @@ export class HelperVars { get maxSnippetTokens() { return this.options.maxPromptTokens * this.options.maxSnippetPercentage; } + get prunedCaretWindow() { + return this.prunedPrefix + this.prunedSuffix; + } // Getters for lazy access get fileContents(): string { From 664d84dfa0b3fba885f9fc209e2ac71407bc9958 Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 31 Oct 2024 18:21:07 -0700 Subject: [PATCH 39/96] show whatever lines we have at x ms --- .../StreamTransformPipeline.ts | 24 ++++++++++--------- .../filtering/streamTransforms/lineStream.ts | 16 +++++++++++++ .../generation/CompletionStreamer.ts | 11 ++++----- core/index.d.ts | 13 +++++----- core/util/parameters.ts | 1 + .../src/autocomplete/completionProvider.ts | 2 +- 6 files changed, 42 insertions(+), 25 deletions(-) diff --git a/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts b/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts index edc4f8c40..42ab89829 100644 --- a/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts +++ b/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts @@ -1,10 +1,10 @@ -import { Position } from "../../.."; import { streamLines } from "../../../diff/util"; -import { AutocompleteLanguageInfo } from "../../constants/AutocompleteLanguageInfo"; +import { HelperVars } from "../../util/HelperVars"; import { BracketMatchingService } from "../BracketMatchingService"; import { stopAtStopTokens } from "./charStream"; import { avoidPathLineAndEmptyComments, + showWhateverWeHaveAtXMs, skipPrefixes, stopAtLines, stopAtRepeatingLines, @@ -19,13 +19,10 @@ export class StreamTransformPipeline { generator: AsyncGenerator, prefix: string, suffix: string, - filepath: string, multiline: boolean, - pos: Position, - fileLines: string[], stopTokens: string[], - lang: AutocompleteLanguageInfo, fullStop: () => void, + helper: HelperVars, ): AsyncGenerator { let charGenerator = generator; @@ -40,7 +37,7 @@ export class StreamTransformPipeline { charGenerator, prefix, suffix, - filepath, + helper.filepath, multiline, ); @@ -51,9 +48,12 @@ export class StreamTransformPipeline { let i = 1; while ( lineBelowCursor.trim() === "" && - pos.line + i <= fileLines.length - 1 + helper.pos.line + i <= helper.fileLines.length - 1 ) { - lineBelowCursor = fileLines[Math.min(pos.line + i, fileLines.length - 1)]; + lineBelowCursor = + helper.fileLines[ + Math.min(helper.pos.line + i, helper.fileLines.length - 1) + ]; i++; } @@ -61,7 +61,7 @@ export class StreamTransformPipeline { lineGenerator = stopAtRepeatingLines(lineGenerator, fullStop); lineGenerator = avoidPathLineAndEmptyComments( lineGenerator, - lang.singleLineComment, + helper.lang.singleLineComment, ); lineGenerator = skipPrefixes(lineGenerator); @@ -70,12 +70,14 @@ export class StreamTransformPipeline { // lang.topLevelKeywords, // fullStop, // ); - for (const lineFilter of lang.lineFilters ?? []) { + for (const lineFilter of helper.lang.lineFilters ?? []) { lineGenerator = lineFilter({ lines: lineGenerator, fullStop }); } lineGenerator = stopAtSimilarLine(lineGenerator, lineBelowCursor, fullStop); + lineGenerator = showWhateverWeHaveAtXMs(lineGenerator, 250); + const finalGenerator = streamWithNewLines(lineGenerator); for await (const update of finalGenerator) { yield update; diff --git a/core/autocomplete/filtering/streamTransforms/lineStream.ts b/core/autocomplete/filtering/streamTransforms/lineStream.ts index 918acaf26..cd8363672 100644 --- a/core/autocomplete/filtering/streamTransforms/lineStream.ts +++ b/core/autocomplete/filtering/streamTransforms/lineStream.ts @@ -510,3 +510,19 @@ export async function* logLines( } console.log(`${prefix}:\n${linesToLog.join("\n")}\n\n`); } + +export async function* showWhateverWeHaveAtXMs( + lines: LineStream, + ms: number, +): LineStream { + const startTime = Date.now(); + for await (const line of lines) { + // Always get at least one line + yield line; + + // But after that, soft break at X ms + if (Date.now() - startTime > ms) { + break; + } + } +} diff --git a/core/autocomplete/generation/CompletionStreamer.ts b/core/autocomplete/generation/CompletionStreamer.ts index 11b0755d8..3f46f5033 100644 --- a/core/autocomplete/generation/CompletionStreamer.ts +++ b/core/autocomplete/generation/CompletionStreamer.ts @@ -7,7 +7,7 @@ export class CompletionStreamer { private streamTransformPipeline = new StreamTransformPipeline(); private generatorReuseManager: GeneratorReuseManager; - constructor(private readonly onError: (err: any) => void) { + constructor(onError: (err: any) => void) { this.generatorReuseManager = new GeneratorReuseManager(onError); } @@ -49,22 +49,19 @@ export class CompletionStreamer { }; const initialGenerator = generatorWithCancellation(); - const finalGenerator = helper.options.transform + const transformedGenerator = helper.options.transform ? this.streamTransformPipeline.transform( initialGenerator, prefix, suffix, - helper.filepath, multiline, - helper.pos, - helper.fileLines, completionOptions?.stop || [], - helper.lang, fullStop, + helper, ) : initialGenerator; - for await (const update of finalGenerator) { + for await (const update of transformedGenerator) { yield update; } } diff --git a/core/index.d.ts b/core/index.d.ts index 2cc9dc56a..40bcae662 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -48,9 +48,9 @@ export interface IndexingProgressUpdate { export type PromptTemplate = | string | (( - history: ChatMessage[], - otherData: Record, - ) => string | ChatMessage[]); + history: ChatMessage[], + otherData: Record, + ) => string | ChatMessage[]); export interface ILLM extends LLMOptions { get providerName(): ModelProvider; @@ -904,6 +904,7 @@ export interface TabAutocompleteOptions { disableInFiles?: string[]; useImports?: boolean; useRootPathContext?: boolean; + showWhateverWeHaveAtXMs?: number; } export interface ContinueUIConfig { @@ -1053,9 +1054,9 @@ export interface Config { embeddingsProvider?: EmbeddingsProviderDescription | EmbeddingsProvider; /** The model that Continue will use for tab autocompletions. */ tabAutocompleteModel?: - | CustomLLM - | ModelDescription - | (CustomLLM | ModelDescription)[]; + | CustomLLM + | ModelDescription + | (CustomLLM | ModelDescription)[]; /** Options for tab autocomplete */ tabAutocompleteOptions?: Partial; /** UI styles customization */ diff --git a/core/util/parameters.ts b/core/util/parameters.ts index 7144ba4d6..7a94abc03 100644 --- a/core/util/parameters.ts +++ b/core/util/parameters.ts @@ -22,6 +22,7 @@ export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = { useImports: true, useRootPathContext: true, transform: true, + showWhateverWeHaveAtXMs: 300, }; export const COUNT_COMPLETION_REJECTED_AFTER = 10_000; diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index b1af40435..131d61ffa 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -1,5 +1,5 @@ import type { IDE } from "core"; -import { CompletionProvider } from "core/autocomplete/completionProvider"; +import { CompletionProvider } from "core/autocomplete/CompletionProvider"; import { type AutocompleteInput, type AutocompleteOutcome, From a2c192c778720c21742e863bd17350deab91b4c9 Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 31 Oct 2024 20:32:58 -0700 Subject: [PATCH 40/96] fix bug --- core/autocomplete/READEME.md | 3 +++ core/autocomplete/util/HelperVars.ts | 29 +++++++++++++++++++++++----- 2 files changed, 27 insertions(+), 5 deletions(-) create mode 100644 core/autocomplete/READEME.md diff --git a/core/autocomplete/READEME.md b/core/autocomplete/READEME.md new file mode 100644 index 000000000..170e673a5 --- /dev/null +++ b/core/autocomplete/READEME.md @@ -0,0 +1,3 @@ +TODO + +- The generator reuse thing isn't working it seems diff --git a/core/autocomplete/util/HelperVars.ts b/core/autocomplete/util/HelperVars.ts index dd8eb717b..a6ecb21a9 100644 --- a/core/autocomplete/util/HelperVars.ts +++ b/core/autocomplete/util/HelperVars.ts @@ -19,13 +19,13 @@ import { AutocompleteInput } from "./types"; export class HelperVars { lang: AutocompleteLanguageInfo; treePath: AstPath | undefined; - prunedPrefix: string; - prunedSuffix: string; private _fileContents: string | undefined; private _fileLines: string[] | undefined; private _fullPrefix: string | undefined; private _fullSuffix: string | undefined; + private _prunedPrefix: string | undefined; + private _prunedSuffix: string | undefined; private constructor( public readonly input: AutocompleteInput, @@ -34,9 +34,6 @@ export class HelperVars { private readonly ide: IDE, ) { this.lang = languageForFilepath(input.filepath); - const { prunedPrefix, prunedSuffix } = this.prunePrefixSuffix(); - this.prunedPrefix = prunedPrefix; - this.prunedSuffix = prunedSuffix; } private async init() { @@ -55,6 +52,10 @@ export class HelperVars { this._fullPrefix = fullPrefix; this._fullSuffix = fullSuffix; + const { prunedPrefix, prunedSuffix } = this.prunePrefixSuffix(); + this._prunedPrefix = prunedPrefix; + this._prunedSuffix = prunedSuffix; + try { const ast = await getAst(this.filepath, fullPrefix + fullSuffix); if (ast) { @@ -153,4 +154,22 @@ export class HelperVars { } return this._fullSuffix; } + + get prunedPrefix(): string { + if (this._prunedPrefix === undefined) { + throw new Error( + "HelperVars must be initialized before accessing prunedPrefix", + ); + } + return this._prunedPrefix; + } + + get prunedSuffix(): string { + if (this._prunedSuffix === undefined) { + throw new Error( + "HelperVars must be initialized before accessing prunedSuffix", + ); + } + return this._prunedSuffix; + } } From cc7d41e8dc4b7524e917b7b0cdb1ed655e033b4c Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 31 Oct 2024 21:27:10 -0700 Subject: [PATCH 41/96] WIP testing rootpathcontext --- core/autocomplete/READEME.md | 6 ++ .../context/ContextRetrievalService.ts | 2 +- .../RootPathContextService.test.ts | 97 +++++++++++++++++++ .../RootPathContextService.ts | 10 +- .../test/typescript/file1.ts | 13 +++ .../test/typescript/types.ts | 11 +++ 6 files changed, 133 insertions(+), 6 deletions(-) create mode 100644 core/autocomplete/context/root-path-context/RootPathContextService.test.ts rename core/autocomplete/context/{ => root-path-context}/RootPathContextService.ts (92%) create mode 100644 core/autocomplete/context/root-path-context/test/typescript/file1.ts create mode 100644 core/autocomplete/context/root-path-context/test/typescript/types.ts diff --git a/core/autocomplete/READEME.md b/core/autocomplete/READEME.md index 170e673a5..d5e822273 100644 --- a/core/autocomplete/READEME.md +++ b/core/autocomplete/READEME.md @@ -1,3 +1,9 @@ TODO - The generator reuse thing isn't working it seems + +Tests for context: + +- You need a static set of files to test. Ideally you don't have to rewrite the exact same files every time you want to make a new test. +- So put some example files in a few folders. There should be a folder for each language I think. +- You should definitely test each of the services separately diff --git a/core/autocomplete/context/ContextRetrievalService.ts b/core/autocomplete/context/ContextRetrievalService.ts index 3c6ed3376..a12d1962e 100644 --- a/core/autocomplete/context/ContextRetrievalService.ts +++ b/core/autocomplete/context/ContextRetrievalService.ts @@ -3,7 +3,7 @@ import { HelperVars } from "../util/HelperVars"; import { RecentlyEditedRange } from "../util/types"; import { ImportDefinitionsService } from "./ImportDefinitionsService"; import { AutocompleteSnippet, getSymbolsForSnippet } from "./ranking"; -import { RootPathContextService } from "./RootPathContextService"; +import { RootPathContextService } from "./root-path-context/RootPathContextService"; export class ContextRetrievalService { private importDefinitionsService: ImportDefinitionsService; diff --git a/core/autocomplete/context/root-path-context/RootPathContextService.test.ts b/core/autocomplete/context/root-path-context/RootPathContextService.test.ts new file mode 100644 index 000000000..87795611b --- /dev/null +++ b/core/autocomplete/context/root-path-context/RootPathContextService.test.ts @@ -0,0 +1,97 @@ +import fs from "fs"; +import path from "path"; +import { Range } from "../../.."; +import { testIde } from "../../../test/util/fixtures"; +import { getAst, getTreePathAtCursor } from "../../util/ast"; +import { ImportDefinitionsService } from "../ImportDefinitionsService"; +import { RootPathContextService } from "./RootPathContextService"; + +function splitTextAtRange(fileContent: string, range: Range): [string, string] { + const lines = fileContent.split("\n"); + let currentPos = 0; + + if (range.start.line === range.end.line) { + // If range is on the same line, calculate position once + for (let i = 0; i < range.start.line; i++) { + currentPos += lines[i].length + 1; // +1 for the newline character + } + const startPos = currentPos + range.start.character; + const endPos = currentPos + range.end.character; + return [fileContent.slice(0, startPos), fileContent.slice(endPos)]; + } + + // Calculate position of range start + for (let i = 0; i < range.start.line; i++) { + currentPos += lines[i].length + 1; + } + const startPos = currentPos + range.start.character; + + // Calculate position of range end + currentPos = 0; + for (let i = 0; i < range.end.line; i++) { + currentPos += lines[i].length + 1; + } + const endPos = currentPos + range.end.character; + + return [fileContent.slice(0, startPos), fileContent.slice(endPos)]; +} + +export async function testRootPathContext( + folderName: string, + relativeFilepath: string, + rangeToFill: Range, + expectedSnippets: string[], +) { + const ide = testIde; + const importDefinitionsService = new ImportDefinitionsService(ide); + const service = new RootPathContextService(importDefinitionsService, ide); + + // Copy the folder to the test directory + const folderPath = path.join( + __dirname, + "autocomplete", + "context", + "root-path-context", + "test", + folderName, + ); + const workspaceDir = (await ide.getWorkspaceDirs())[0]; + const testFolderPath = path.join(workspaceDir, folderName); + fs.cpSync(folderPath, testFolderPath, { + recursive: true, + force: true, + }); + + // Get results of root path context + const startPath = path.join(testFolderPath, relativeFilepath); + const [prefix, suffix] = splitTextAtRange( + fs.readFileSync(startPath, "utf8"), + rangeToFill, + ); + const fileContents = prefix + suffix; + const ast = await getAst(startPath, fileContents); + if (!ast) { + throw new Error("AST is undefined"); + } + + const treePath = await getTreePathAtCursor(ast, rangeToFill.start.character); + const snippets = await service.getContextForPath(startPath, treePath); + + expectedSnippets.forEach((expectedSnippet) => { + const found = snippets.find((snippet) => + snippet.contents.includes(expectedSnippet), + ); + expect(found).toBeDefined(); + }); +} + +describe("RootPathContextService", () => { + it("should be true", async () => { + await testRootPathContext( + "typescript", + "file1.ts", + { start: { line: 3, character: 2 }, end: { line: 3, character: 24 } }, + ["export interface Person", "export interface Address"], + ); + }); +}); diff --git a/core/autocomplete/context/RootPathContextService.ts b/core/autocomplete/context/root-path-context/RootPathContextService.ts similarity index 92% rename from core/autocomplete/context/RootPathContextService.ts rename to core/autocomplete/context/root-path-context/RootPathContextService.ts index 2b2986b75..ba99b2e83 100644 --- a/core/autocomplete/context/RootPathContextService.ts +++ b/core/autocomplete/context/root-path-context/RootPathContextService.ts @@ -1,11 +1,11 @@ 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 "../util/ast"; -import { ImportDefinitionsService } from "./ImportDefinitionsService"; -import { AutocompleteSnippet } from "./ranking"; +import { IDE } from "../../.."; +import { getQueryForFile, TSQueryType } from "../../../util/treeSitter"; +import { AstPath } from "../../util/ast"; +import { ImportDefinitionsService } from "../ImportDefinitionsService"; +import { AutocompleteSnippet } from "../ranking"; export class RootPathContextService { private cache = new LRUCache({ diff --git a/core/autocomplete/context/root-path-context/test/typescript/file1.ts b/core/autocomplete/context/root-path-context/test/typescript/file1.ts new file mode 100644 index 000000000..c67ae91e2 --- /dev/null +++ b/core/autocomplete/context/root-path-context/test/typescript/file1.ts @@ -0,0 +1,13 @@ +import { Address, Person } from "./types"; + +function getAddress(person: Person): Address { + return person.address; +} + +class Group { + people: Person[]; + + constructor(people: Person[]) { + this.people = people; + } +} diff --git a/core/autocomplete/context/root-path-context/test/typescript/types.ts b/core/autocomplete/context/root-path-context/test/typescript/types.ts new file mode 100644 index 000000000..272ec27d7 --- /dev/null +++ b/core/autocomplete/context/root-path-context/test/typescript/types.ts @@ -0,0 +1,11 @@ +export interface Person { + firstName: string; + lastName: string; + age: number; + address: Address; +} + +export interface Address { + street: string; + city: string; +} From d9af61f4471b6aa7fe21554feb5926d143e5c4f9 Mon Sep 17 00:00:00 2001 From: Pranjal Rana <129268721+PRANJALRANA11@users.noreply.github.com> Date: Fri, 1 Nov 2024 12:16:55 +0530 Subject: [PATCH 42/96] Add memoization for the walk-dir --- core/core.ts | 33 +++++++++++++++++++++++++++++---- 1 file changed, 29 insertions(+), 4 deletions(-) diff --git a/core/core.ts b/core/core.ts index db965dec1..11b5ddb01 100644 --- a/core/core.ts +++ b/core/core.ts @@ -704,16 +704,41 @@ export class Core { const url = await getAuthUrlForTokenPage(); return { url }; }); - on("didChangeActiveTextEditor", async ({ data: { filepath } }) => { - const dirs = await this.ide.getWorkspaceDirs(); - const paths = await walkDir(dirs[0], this.ide); - if (paths.includes(filepath)) { + let dirs = await this.ide.getWorkspaceDirs(); + let memoizedFunction = await this.memoizedFunction(dirs); + if (memoizedFunction.includes(filepath)) { + console.log("yep running"); recentlyEditedFilesCache.set(filepath, filepath); } }); } + private memoize Promise>( + fn: T, + ): (...args: Parameters) => Promise> { + const cache = new Map>>(); + + return async function (...args: Parameters): Promise> { + const key = JSON.stringify(args); + if (cache.has(key)) { + return cache.get(key) as Promise>; + } + const result = await fn(...args); + cache.set(key, Promise.resolve(result)); + return result; + }; + } + + private async checkIgnoredFiles(dirs: string[]): Promise { + console.log("called"); + const paths = await walkDir(dirs[0], this.ide); + return paths; + } + + // Memoize the async checkIgnoredFiles function + memoizedFunction = this.memoize(this.checkIgnoredFiles.bind(this)); + private indexingCancellationController: AbortController | undefined; private async refreshCodebaseIndex(dirs: string[]) { From 6f4b0f18adbf0da8a74d5248de72b4dfee9cd2c7 Mon Sep 17 00:00:00 2001 From: Pranjal Rana <129268721+PRANJALRANA11@users.noreply.github.com> Date: Sat, 2 Nov 2024 10:46:39 +0530 Subject: [PATCH 43/96] fix rel-path for ignore --- core/core.ts | 38 ++++++++------------------------------ 1 file changed, 8 insertions(+), 30 deletions(-) diff --git a/core/core.ts b/core/core.ts index 11b5ddb01..a3f59ec8e 100644 --- a/core/core.ts +++ b/core/core.ts @@ -29,7 +29,9 @@ import type { IMessenger, Message } from "./util/messenger"; import { editConfigJson, setupInitialDotContinueDirectory } from "./util/paths"; import { Telemetry } from "./util/posthog"; import { TTS } from "./util/tts"; -import { walkDir } from "./indexing/walkDir"; +import ignore from "ignore"; +import { defaultIgnoreFile } from "./indexing/ignore.js"; +import path from "path"; export class Core { // implements IMessenger @@ -704,41 +706,17 @@ export class Core { const url = await getAuthUrlForTokenPage(); return { url }; }); + on("didChangeActiveTextEditor", async ({ data: { filepath } }) => { - let dirs = await this.ide.getWorkspaceDirs(); - let memoizedFunction = await this.memoizedFunction(dirs); - if (memoizedFunction.includes(filepath)) { - console.log("yep running"); + const ignoreInstance = ignore().add(defaultIgnoreFile); + let rootDirectory = await this.ide.getWorkspaceDirs(); + const relativeFilePath = path.relative(rootDirectory[0], filepath); + if (!ignoreInstance.ignores(relativeFilePath)) { recentlyEditedFilesCache.set(filepath, filepath); } }); } - private memoize Promise>( - fn: T, - ): (...args: Parameters) => Promise> { - const cache = new Map>>(); - - return async function (...args: Parameters): Promise> { - const key = JSON.stringify(args); - if (cache.has(key)) { - return cache.get(key) as Promise>; - } - const result = await fn(...args); - cache.set(key, Promise.resolve(result)); - return result; - }; - } - - private async checkIgnoredFiles(dirs: string[]): Promise { - console.log("called"); - const paths = await walkDir(dirs[0], this.ide); - return paths; - } - - // Memoize the async checkIgnoredFiles function - memoizedFunction = this.memoize(this.checkIgnoredFiles.bind(this)); - private indexingCancellationController: AbortController | undefined; private async refreshCodebaseIndex(dirs: string[]) { From b0e470f0fc5facbf9a4c891b779af297131b5692 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luis=20Eduardo=20Chac=C3=B3n=20Borrego?= Date: Sat, 2 Nov 2024 19:25:25 -0600 Subject: [PATCH 44/96] [#2791] - Proposal for addin use_mmap parameter --- core/config/types.ts | 1 + core/control-plane/schema.ts | 1 + core/index.d.ts | 1 + core/llm/llms/Ollama.ts | 2 ++ docs/docs/customize/model-providers/more/msty.md | 1 + docs/docs/reference.md | 1 + .../intellij/src/main/resources/continue_rc_schema.json | 5 +++++ extensions/vscode/config_schema.json | 5 +++++ packages/config-types/src/index.ts | 1 + 9 files changed, 18 insertions(+) diff --git a/core/config/types.ts b/core/config/types.ts index ca8ee9bec..74a2bf2a8 100644 --- a/core/config/types.ts +++ b/core/config/types.ts @@ -730,6 +730,7 @@ declare global { stop?: string[]; maxTokens?: number; numThreads?: number; + useMmap?: boolean; keepAlive?: number; raw?: boolean; stream?: boolean; diff --git a/core/control-plane/schema.ts b/core/control-plane/schema.ts index 3a984ae33..e6987f1fe 100644 --- a/core/control-plane/schema.ts +++ b/core/control-plane/schema.ts @@ -54,6 +54,7 @@ const modelDescriptionSchema = z.object({ stop: z.array(z.string()).optional(), maxTokens: z.number().optional(), numThreads: z.number().optional(), + useMmap: z.boolean().optional(), keepAlive: z.number().optional(), raw: z.boolean().optional(), stream: z.boolean().optional(), diff --git a/core/index.d.ts b/core/index.d.ts index 133270873..ae7c8edf0 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -788,6 +788,7 @@ interface BaseCompletionOptions { stop?: string[]; maxTokens?: number; numThreads?: number; + useMmap?: boolean; keepAlive?: number; raw?: boolean; stream?: boolean; diff --git a/core/llm/llms/Ollama.ts b/core/llm/llms/Ollama.ts index 91d7976b7..a9ac7ab75 100644 --- a/core/llm/llms/Ollama.ts +++ b/core/llm/llms/Ollama.ts @@ -30,6 +30,7 @@ interface ModelFileParams { min_p?: number; // deprecated? num_thread?: number; + use_mmap?: boolean; num_gqa?: number; num_gpu?: number; } @@ -191,6 +192,7 @@ class Ollama extends BaseLLM { num_ctx: this.contextLength, mirostat: options.mirostat, num_thread: options.numThreads, + use_mmap: options.useMmap, min_p: options.minP, }; } diff --git a/docs/docs/customize/model-providers/more/msty.md b/docs/docs/customize/model-providers/more/msty.md index d7554aeae..1fda1d88b 100644 --- a/docs/docs/customize/model-providers/more/msty.md +++ b/docs/docs/customize/model-providers/more/msty.md @@ -24,6 +24,7 @@ In addition to the model type, you can also configure some of the parameters tha - top_k: options.topK - This parameter limits the number of unique tokens to consider when generating the next token in the sequence. Higher values increase the variety of generated sequences, while lower values lead to more focused outputs. - num_predict: options.maxTokens - This determines the maximum number of tokens (words or characters) to generate for the given input prompt. - num_thread: options.numThreads - This is the multi-threading configuration option that controls how many threads the model uses for parallel processing. Higher values may lead to faster generation times but could also increase memory usage and complexity. Set this to one or two lower than the number of threads your CPU can handle to leave some for your GUI when running the model locally. +- use_mmap: options.useMmap - For Ollama, this parameter allows the model to be mapped into memory. If disabled can enhance response time on low end devices but will slow down the stream. ## Authentication diff --git a/docs/docs/reference.md b/docs/docs/reference.md index 19e8f386e..8444e344b 100644 --- a/docs/docs/reference.md +++ b/docs/docs/reference.md @@ -158,6 +158,7 @@ Parameters that control the behavior of text generation and completion settings. - `maxTokens`: The maximum number of tokens to generate in a completion (default: `2048`). - `numThreads`: The number of threads used during the generation process. Available only for Ollama as `num_thread`. - `keepAlive`: For Ollama, this parameter sets the number of seconds to keep the model loaded after the last request, unloading it from memory if inactive (default: `1800` seconds, or 30 minutes). +- `useMmap`: For Ollama, this parameter allows the model to be mapped into memory. If disabled can enhance response time on low end devices but will slow down the stream. Example diff --git a/extensions/intellij/src/main/resources/continue_rc_schema.json b/extensions/intellij/src/main/resources/continue_rc_schema.json index 3282e0344..9147fb3ad 100644 --- a/extensions/intellij/src/main/resources/continue_rc_schema.json +++ b/extensions/intellij/src/main/resources/continue_rc_schema.json @@ -61,6 +61,11 @@ "description": "The number of threads used in the generation process. Only available for Ollama (this is the num_thread parameter)", "type": "integer" }, + "useMmap": { + "title": "Use Memory Map", + "description": "Allows the model to be mapped into memory. If disabled can enhance response time on low end devices. Only available for Ollama (this is the use_mmap parameter)", + "type": "boolean" + }, "keepAlive": { "title": "Ollama keep_alive", "description": "The number of seconds after no requests are made to unload the model from memory. Defaults to 60*30 = 30min", diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index c0a734b02..2dada1591 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -61,6 +61,11 @@ "description": "The number of threads used in the generation process. Only available for Ollama (this is the num_thread parameter)", "type": "integer" }, + "useMmap": { + "title": "Use Memory Map", + "description": "Allows the model to be mapped into memory. If disabled can enhance response time on low end devices. Only available for Ollama (this is the use_mmap parameter)", + "type": "boolean" + }, "keepAlive": { "title": "Ollama keep_alive", "description": "The number of seconds after no requests are made to unload the model from memory. Defaults to 60*30 = 30min", diff --git a/packages/config-types/src/index.ts b/packages/config-types/src/index.ts index febff0221..4d989c127 100644 --- a/packages/config-types/src/index.ts +++ b/packages/config-types/src/index.ts @@ -11,6 +11,7 @@ export const completionOptionsSchema = z.object({ stop: z.array(z.string()).optional(), maxTokens: z.number().optional(), numThreads: z.number().optional(), + useMmap: z.boolean().optional(), keepAlive: z.number().optional(), raw: z.boolean().optional(), stream: z.boolean().optional(), From 400be9b47f0b8ab52b4e32ca77339497c63c8f96 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Mon, 4 Nov 2024 14:45:14 +0700 Subject: [PATCH 45/96] fix: add missing import --- core/autocomplete/templating/index.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/core/autocomplete/templating/index.ts b/core/autocomplete/templating/index.ts index 6ee99b862..05a10bbed 100644 --- a/core/autocomplete/templating/index.ts +++ b/core/autocomplete/templating/index.ts @@ -1,3 +1,4 @@ +import Handlebars from "handlebars"; import { CompletionOptions } from "../.."; import { getBasename, getLastNPathParts } from "../../util"; import { AutocompleteLanguageInfo } from "../constants/AutocompleteLanguageInfo"; From deea8f1f44403b6d7d7bb4236ff5acb8d38bca01 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Mon, 4 Nov 2024 17:46:12 +0700 Subject: [PATCH 46/96] fix: tests --- .../test/NEGATIVE_CASES_STARCODER.tsx | 51 -------- .../test/NEGATIVE_CASES_STARCODER.txt | 123 ++++++++++++++++++ 2 files changed, 123 insertions(+), 51 deletions(-) delete mode 100644 core/autocomplete/filtering/test/NEGATIVE_CASES_STARCODER.tsx create mode 100644 core/autocomplete/filtering/test/NEGATIVE_CASES_STARCODER.txt diff --git a/core/autocomplete/filtering/test/NEGATIVE_CASES_STARCODER.tsx b/core/autocomplete/filtering/test/NEGATIVE_CASES_STARCODER.tsx deleted file mode 100644 index 269d25f0f..000000000 --- a/core/autocomplete/filtering/test/NEGATIVE_CASES_STARCODER.tsx +++ /dev/null @@ -1,51 +0,0 @@ -##### Prompt ##### -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; - } -} -========================================================================== -========================================================================== -Completion: - - this.result /= number; - return this; - } -} - -module.exports = Calculator; \ No newline at end of file diff --git a/core/autocomplete/filtering/test/NEGATIVE_CASES_STARCODER.txt b/core/autocomplete/filtering/test/NEGATIVE_CASES_STARCODER.txt new file mode 100644 index 000000000..9a286d1de --- /dev/null +++ b/core/autocomplete/filtering/test/NEGATIVE_CASES_STARCODER.txt @@ -0,0 +1,123 @@ +##### Prompt ##### +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; + } +} +========================================================================== +========================================================================== +Completion: + + this.result /= number; + return this; + } +} + +module.exports = Calculator; + +------------------------------------------------------------------------ + +##### Prompt ##### +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; + } +} +========================================================================== +========================================================================== +Completion: + + getResult() { + return this.result; + } + + reset() { + this.result = 0; + return this; + } +} + +// Example usage: +const calculator = new Calculator(); +calculator.add(5).subtract(3).multiply(2).divide(4); +console.log(calculator.getResult()); // Output: 2 + +calculator.reset().add(10).divide(2); +console.log(calculator.getResult()); // Output: 5 + +calculator.reset().add(8).multiply(0); +console.log(calculator.getResult()); // Output: 0 + +calculator.reset().add(6).divide(0); // Throws an error: Cannot divide by zero \ No newline at end of file From fb1a75dcf33fa38863bda4f5b88c1a567aaf0269 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Mon, 4 Nov 2024 17:46:35 +0700 Subject: [PATCH 47/96] fix: naming --- ...ASES_STARCODER.txt => NEGATIVE_CASES_STARCODER_TYPESCRIPT.txt} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename core/autocomplete/filtering/test/{NEGATIVE_CASES_STARCODER.txt => NEGATIVE_CASES_STARCODER_TYPESCRIPT.txt} (100%) diff --git a/core/autocomplete/filtering/test/NEGATIVE_CASES_STARCODER.txt b/core/autocomplete/filtering/test/NEGATIVE_CASES_STARCODER_TYPESCRIPT.txt similarity index 100% rename from core/autocomplete/filtering/test/NEGATIVE_CASES_STARCODER.txt rename to core/autocomplete/filtering/test/NEGATIVE_CASES_STARCODER_TYPESCRIPT.txt From fe1af0156fc9db0640ef2d460ba5da289192aeb0 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Mon, 4 Nov 2024 17:58:59 +0700 Subject: [PATCH 48/96] improv: single responsibility in filter functions --- .../StreamTransformPipeline.ts | 6 ++-- .../streamTransforms/lineStream.test.ts | 27 ++++++++++++----- .../filtering/streamTransforms/lineStream.ts | 29 +++++++++++++++---- 3 files changed, 48 insertions(+), 14 deletions(-) diff --git a/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts b/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts index 42ab89829..543c9b7b8 100644 --- a/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts +++ b/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts @@ -3,7 +3,8 @@ import { HelperVars } from "../../util/HelperVars"; import { BracketMatchingService } from "../BracketMatchingService"; import { stopAtStopTokens } from "./charStream"; import { - avoidPathLineAndEmptyComments, + avoidEmptyComments, + avoidPathLine, showWhateverWeHaveAtXMs, skipPrefixes, stopAtLines, @@ -59,10 +60,11 @@ export class StreamTransformPipeline { lineGenerator = stopAtLines(lineGenerator, fullStop); lineGenerator = stopAtRepeatingLines(lineGenerator, fullStop); - lineGenerator = avoidPathLineAndEmptyComments( + lineGenerator = avoidEmptyComments( lineGenerator, helper.lang.singleLineComment, ); + lineGenerator = avoidPathLine(lineGenerator, helper.lang.singleLineComment); lineGenerator = skipPrefixes(lineGenerator); // lineGenerator = noTopLevelKeywordsMidline( diff --git a/core/autocomplete/filtering/streamTransforms/lineStream.test.ts b/core/autocomplete/filtering/streamTransforms/lineStream.test.ts index df8cd1263..810ab9eec 100644 --- a/core/autocomplete/filtering/streamTransforms/lineStream.test.ts +++ b/core/autocomplete/filtering/streamTransforms/lineStream.test.ts @@ -31,21 +31,34 @@ describe("lineStream", () => { }); describe("avoidPathLine", () => { - it("should filter out path lines and empty comments", async () => { + it("should filter out path lines", async () => { const linesGenerator = await getLineGenerator([ "// Path: src/index.ts", "const x = 5;", "//", "console.log(x);", ]); - - const result = lineStream.avoidPathLineAndEmptyComments( - linesGenerator, - "//", - ); + const result = lineStream.avoidPathLine(linesGenerator, "//"); const filteredLines = await getFilteredLines(result); + expect(filteredLines).toEqual(["const x = 5;", "//", "console.log(x);"]); + }); + }); - expect(filteredLines).toEqual(["const x = 5;", "console.log(x);"]); + describe("avoidEmptyComments", () => { + it("should filter out empty comments", async () => { + const linesGenerator = await getLineGenerator([ + "// Path: src/index.ts", + "const x = 5;", + "//", + "console.log(x);", + ]); + const result = lineStream.avoidEmptyComments(linesGenerator, "//"); + const filteredLines = await getFilteredLines(result); + expect(filteredLines).toEqual([ + "// Path: src/index.ts", + "const x = 5;", + "console.log(x);", + ]); }); }); diff --git a/core/autocomplete/filtering/streamTransforms/lineStream.ts b/core/autocomplete/filtering/streamTransforms/lineStream.ts index cd8363672..dffca36b9 100644 --- a/core/autocomplete/filtering/streamTransforms/lineStream.ts +++ b/core/autocomplete/filtering/streamTransforms/lineStream.ts @@ -122,21 +122,40 @@ export async function* noTopLevelKeywordsMidline( } /** - * Filters out unwanted lines from a LineStream, specifically those starting with '// Path: ' or empty comments. + * Filters out lines starting with '// Path: ' from a LineStream. * * @param {LineStream} stream - The input stream of lines to filter. * @param {string} comment - The comment syntax to filter (e.g., '//' for JavaScript-style comments). - * @yields {string} The filtered lines, excluding unwanted path lines and empty comments. + * @yields {string} The filtered lines, excluding unwanted path lines. */ -export async function* avoidPathLineAndEmptyComments( +export async function* avoidPathLine( stream: LineStream, comment: string, ): LineStream { // Snippets are inserted as comments with a line at the start '// Path: '. // Sometimes the model with copy this pattern, which is unwanted for await (const line of stream) { - // Also filter lines that are empty comments - if (line.startsWith(`${comment} Path: `) || line.trim() === comment) { + if (line.startsWith(`${comment} Path: `)) { + continue; + } + yield line; + } +} + +/** + * Filters out empty comment lines from a LineStream. + * + * @param {LineStream} stream - The input stream of lines to filter. + * @param {string} comment - The comment syntax to filter (e.g., '//' for JavaScript-style comments). + * @yields {string} The filtered lines, excluding empty comments. + */ +export async function* avoidEmptyComments( + stream: LineStream, + comment: string, +): LineStream { + // Filter lines that are empty comments + for await (const line of stream) { + if (line.trim() === comment) { continue; } yield line; From f82b867adbd1d4ac15113a8961e731ab638d2175 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Mon, 4 Nov 2024 18:08:14 +0700 Subject: [PATCH 49/96] improv: organization --- .../CODESTRAL_TYPESCRIPT.txt} | 53 ------------------- .../STARCODER_TYPESCRIPT.txt | 53 +++++++++++++++++++ 2 files changed, 53 insertions(+), 53 deletions(-) rename core/autocomplete/filtering/test/{NEGATIVE_CASES_STARCODER_TYPESCRIPT.txt => NEGATIVE_TEST_CASES/CODESTRAL_TYPESCRIPT.txt} (58%) create mode 100644 core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/STARCODER_TYPESCRIPT.txt diff --git a/core/autocomplete/filtering/test/NEGATIVE_CASES_STARCODER_TYPESCRIPT.txt b/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/CODESTRAL_TYPESCRIPT.txt similarity index 58% rename from core/autocomplete/filtering/test/NEGATIVE_CASES_STARCODER_TYPESCRIPT.txt rename to core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/CODESTRAL_TYPESCRIPT.txt index 9a286d1de..7ecc7003d 100644 --- a/core/autocomplete/filtering/test/NEGATIVE_CASES_STARCODER_TYPESCRIPT.txt +++ b/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/CODESTRAL_TYPESCRIPT.txt @@ -1,56 +1,3 @@ -##### Prompt ##### -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; - } -} -========================================================================== -========================================================================== -Completion: - - this.result /= number; - return this; - } -} - -module.exports = Calculator; - ------------------------------------------------------------------------- ##### Prompt ##### class Calculator { diff --git a/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/STARCODER_TYPESCRIPT.txt b/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/STARCODER_TYPESCRIPT.txt new file mode 100644 index 000000000..b2505a0bb --- /dev/null +++ b/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/STARCODER_TYPESCRIPT.txt @@ -0,0 +1,53 @@ +##### Prompt ##### +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; + } +} +========================================================================== +========================================================================== +Completion: + + this.result /= number; + return this; + } +} + +module.exports = Calculator; + +------------------------------------------------------------------------ From c3800fe13721d02eb338869ce7dfebfbf0dec4fc Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Tue, 5 Nov 2024 01:21:54 +0700 Subject: [PATCH 50/96] refactor: clean up code --- .../StreamTransformPipeline.ts | 63 +++++++++---------- 1 file changed, 29 insertions(+), 34 deletions(-) diff --git a/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts b/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts index 543c9b7b8..037059912 100644 --- a/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts +++ b/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts @@ -27,12 +27,6 @@ export class StreamTransformPipeline { ): AsyncGenerator { let charGenerator = generator; - // charGenerator = noFirstCharNewline(charGenerator); - // charGenerator = onlyWhitespaceAfterEndOfLine( - // charGenerator, - // lang.endOfLine, - // fullStop, - // ); charGenerator = stopAtStopTokens(generator, stopTokens); charGenerator = this.bracketMatchingService.stopOnUnmatchedClosingBracket( charGenerator, @@ -44,7 +38,34 @@ export class StreamTransformPipeline { let lineGenerator = streamLines(charGenerator); - // First non-whitespace line below the cursor + lineGenerator = stopAtLines(lineGenerator, fullStop); + lineGenerator = stopAtRepeatingLines(lineGenerator, fullStop); + lineGenerator = avoidEmptyComments( + lineGenerator, + helper.lang.singleLineComment, + ); + lineGenerator = avoidPathLine(lineGenerator, helper.lang.singleLineComment); + lineGenerator = skipPrefixes(lineGenerator); + + for (const lineFilter of helper.lang.lineFilters ?? []) { + lineGenerator = lineFilter({ lines: lineGenerator, fullStop }); + } + + lineGenerator = stopAtSimilarLine( + lineGenerator, + this.getLineBelowCursor(helper), + fullStop, + ); + + lineGenerator = showWhateverWeHaveAtXMs(lineGenerator, 250); + + const finalGenerator = streamWithNewLines(lineGenerator); + for await (const update of finalGenerator) { + yield update; + } + } + + private getLineBelowCursor(helper: HelperVars): string { let lineBelowCursor = ""; let i = 1; while ( @@ -57,32 +78,6 @@ export class StreamTransformPipeline { ]; i++; } - - lineGenerator = stopAtLines(lineGenerator, fullStop); - lineGenerator = stopAtRepeatingLines(lineGenerator, fullStop); - lineGenerator = avoidEmptyComments( - lineGenerator, - helper.lang.singleLineComment, - ); - lineGenerator = avoidPathLine(lineGenerator, helper.lang.singleLineComment); - lineGenerator = skipPrefixes(lineGenerator); - - // lineGenerator = noTopLevelKeywordsMidline( - // lineGenerator, - // lang.topLevelKeywords, - // fullStop, - // ); - for (const lineFilter of helper.lang.lineFilters ?? []) { - lineGenerator = lineFilter({ lines: lineGenerator, fullStop }); - } - - lineGenerator = stopAtSimilarLine(lineGenerator, lineBelowCursor, fullStop); - - lineGenerator = showWhateverWeHaveAtXMs(lineGenerator, 250); - - const finalGenerator = streamWithNewLines(lineGenerator); - for await (const update of finalGenerator) { - yield update; - } + return lineBelowCursor; } } From 4482ca1ac027430b1db44548b721f809eb147b2d Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Tue, 5 Nov 2024 10:45:30 +0700 Subject: [PATCH 51/96] refactor: clean up code --- core/autocomplete/test/filter.test.ts | 30 - core/autocomplete/test/testCases.ts | 2013 ------------------------- core/autocomplete/test/util.ts | 75 - 3 files changed, 2118 deletions(-) delete mode 100644 core/autocomplete/test/filter.test.ts delete mode 100644 core/autocomplete/test/testCases.ts delete mode 100644 core/autocomplete/test/util.ts diff --git a/core/autocomplete/test/filter.test.ts b/core/autocomplete/test/filter.test.ts deleted file mode 100644 index 171b1cb44..000000000 --- a/core/autocomplete/test/filter.test.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { - AutocompleteFileringTestInput, - testAutocompleteFiltering, -} from "./util"; -import { TEST_CASES } from "./testCases"; - -const filterTestCases = (tests: AutocompleteFileringTestInput[]) => { - if (tests.some((test) => test.options?.only)) { - return tests.filter((test) => test.options?.only); - } - - return tests; -}; - -describe("llms/Mock", () => { - describe("Autocomplete Filtering Tests", () => { - beforeEach(async () => { - await new Promise((resolve) => setTimeout(resolve, 50)); - }); - - describe("Should return unmodified LLM output", () => { - it.each(filterTestCases(TEST_CASES))("$description", async (testCase) => { - await testAutocompleteFiltering(testCase); - }); - }); - - // TODO: Add test cases where modifying LLM output is desirable - describe.skip("Should return modified LLM output", () => {}); - }); -}); diff --git a/core/autocomplete/test/testCases.ts b/core/autocomplete/test/testCases.ts deleted file mode 100644 index 2deeec9de..000000000 --- a/core/autocomplete/test/testCases.ts +++ /dev/null @@ -1,2013 +0,0 @@ -import { dedent } from "../../util"; -import { AutocompleteFileringTestInput } from "./util"; - -export const TEST_CASES: AutocompleteFileringTestInput[] = [ - { - description: "should pass", - filename: "test.js", - input: "console.log('Hello <|fim|>!');", - llmOutput: "World", - expectedCompletion: "World", - }, - { - description: - "Should preserve closing brackets when the opening bracket is not a part of the completion.", - filename: "test.js", - input: dedent` - 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) { - <|fim|> - - getResult() { - return this.result; - } - - reset() { - this.result = 0; - return this; - } - } - `, - llmOutput: dedent`if (number === 0) { - throw new Error("Cannot divide by zero"); - } - this.result /= number; - return this; - }`, - expectedCompletion: dedent`if (number === 0) { - throw new Error("Cannot divide by zero"); - } - this.result /= number; - return this; - }`, - }, - { - description: "Should multiline-autocomplete CSS blocks", - input: `body { - font-family: Arial, sans-serif; - font-size: 16px; - color: #333333; -} - -h1 { - font-size: 24px; - font-weight: bold; - color: #000000; -} - -h4<|fim|> - -a { - text-decoration: none; - color: #007bff; -} - -.container { - width: 100%; - max-width: 1200px; - margin: 0 auto; - padding: 20px; -} - -.button { - display: inline-block; - padding: 10px 20px; - background-color: #007bff; - color: #ffffff;`, - llmOutput: ` { - font-size: 18px; - font-weight: bold; - color: #000000; -}`, - expectedCompletion: ` { - font-size: 18px; - font-weight: bold; - color: #000000; -}`, - filename: "test.css", - }, - { - description: "Should complete CSS rules inside a nested selector", - filename: "styles.css", - input: ` -.container { - display: flex; - justify-content: center; - align-items: center; - width: 100%; - height: 100vh; - - .inner { - <|fim|> - } -} -`, - llmOutput: `width: 50%; - height: 50%; - background-color: #f0f0f0;`, - expectedCompletion: `width: 50%; - height: 50%; - background-color: #f0f0f0;`, - }, - - { - description: - "Should complete a CSS rule when the property is partially typed", - filename: "styles.css", - input: ` -button { - border: 2px solid #000; - border-radius<|fim|> -}`, - llmOutput: `: 5px;`, - expectedCompletion: `: 5px;`, - }, - - { - description: "Should handle CSS autocomplete with a single bracket present", - filename: "styles.css", - input: ` -.card { - box-shadow: 0 4px 8px rgba(0,0,0,0.2); - transition: 0.3s; - padding: 16px; - border-bottom-left-radius: <|fim|>px; - border-bottom-right-radius: 8px; -} -`, - llmOutput: `8`, - expectedCompletion: `8`, - }, - - { - description: "Should autocomplete CSS pseudoclass", - filename: "pseudoClass.css", - input: ` -input:focus { - outline: none; - border: 2px solid <|fim|>; -} -`, - llmOutput: `#4CAF50;`, - expectedCompletion: `#4CAF50;`, - }, - - { - description: "Should handle CSS variable syntax", - filename: "variables.css", - input: ` -:root { - --primary-color: #3498db; - --padding: 10px; -} - -.section { - background-color: var(<|fim|>); - padding: var(--padding); -} -`, - llmOutput: `--primary-color`, - expectedCompletion: `--primary-color`, - }, - { - description: "Should complete CSS grid template columns", - filename: "grid.css", - input: ` -.grid-container { - display: grid; - grid-template-columns: repeat(<|fim|>); - grid-gap: 10px; -} -`, - llmOutput: `3, 1fr`, - expectedCompletion: `3, 1fr`, - }, - - { - description: "Should complete PHP function inside a class with comments", - input: `name = $name; - $this->email = $email; - } - - public function <|fim|> - - public function setEmail($email) { - $this->email = $email; - } -}`, - llmOutput: `getDetails() { - return "Name: " . $this->name . ", Email: " . $this->email; - }`, - expectedCompletion: `getDetails() { - return "Name: " . $this->name . ", Email: " . $this->email; - }`, - filename: "User.php", - }, - - { - description: "Should autocomplete PHP function with inline logic", - input: ` -} - -echo calculateArea(5, 3);`, - llmOutput: `return $length * $width;`, - expectedCompletion: `return $length * $width;`, - filename: "areaCalculator.php", - }, - - { - description: "Should handle PHP completion in the middle of an array", - input: `); - -echo "First color is: " . $colors[0];`, - llmOutput: `"Blue"`, - expectedCompletion: `"Blue"`, - filename: "colors.php", - }, - { - description: "Should autocomplete React return statements (jsx)", - input: `import React from "react"; - -export const Button = ({ - onClick, - children, -}: { - children: React.ReactNode; - onClick: () => void; -}) => { - return ( -<|fim|> - ); -};`, - llmOutput: ``, - expectedCompletion: ``, - filename: "Button.tsx", - }, - { - description: "Should autocomplete React state initialization", - input: `import React, { useState } from "react"; - -export const Counter = () => { - const [count, setCount] = useState(<|fim|>); - - return ( -

- ); -};`, - llmOutput: `0`, - expectedCompletion: `0`, - filename: "Counter.tsx", - }, - - { - description: "Should autocomplete React effect hook", - input: `import React, { useState, useEffect } from "react"; - -export const Timer = () => { - const [seconds, setSeconds] = useState(0); - - useEffect(() => { - const interval = setInterval(() => { - setSeconds(seconds + 1); - }, 1000); - - <|fim|>; - - return () => clearInterval(interval); - }, [seconds]); - - return ( -
-

{seconds} seconds have passed.

-
- ); -};`, - llmOutput: `return () => clearInterval(interval);`, - expectedCompletion: `return () => clearInterval(interval);`, - filename: "Timer.tsx", - }, - - { - description: "Should autocomplete React component methods", - input: `import React from "react"; - -class Form extends React.Component { - constructor(props) { - super(props); - this.state = { name: '' }; - } - - handleChange = (event) => { - <|fim|> - } - - handleSubmit = (event) => { - event.preventDefault(); - alert('A name was submitted: ' + this.state.name); - } - - render() { - return ( -
- - -
- ); - } -}`, - llmOutput: `this.setState({ name: event.target.value });`, - expectedCompletion: `this.setState({ name: event.target.value });`, - filename: "Form.tsx", - }, - { - description: "Should autocomplete Python function definition", - filename: "test.py", - input: `def calculate_area(length, width): - area = length * width - return area - -def calculate_perimeter(length, width): - <|fim|> -`, - llmOutput: `perimeter = 2 * (length + width) - return perimeter`, - expectedCompletion: `perimeter = 2 * (length + width) - return perimeter`, - }, - { - description: "Should complete Python class method with self", - filename: "test.py", - input: `class BankAccount: - def __init__(self, owner, balance=0): - self.owner = owner - self.balance = balance - - def deposit(self, amount): - self.balance += amount - return self.balance - - def withdraw(self, amount): - <|fim|> -`, - llmOutput: `if amount > self.balance: - return "Insufficient funds" - self.balance -= amount - return self.balance`, - expectedCompletion: `if amount > self.balance: - return "Insufficient funds" - self.balance -= amount - return self.balance`, - }, - { - description: "Should autocomplete Python list comprehension", - filename: "test.py", - input: `squares = [x**2 for x in range(10)] -even_squares = [x for x in squares if x % 2 == 0] -print(even_squares) - -odd_squares = [<|fim|> -print(odd_squares) -`, - llmOutput: `x for x in squares if x % 2 != 0`, - expectedCompletion: `x for x in squares if x % 2 != 0`, - }, - { - description: "Should handle python multi-line string", - filename: "test.py", - input: `def create_greeting(name): - greeting = """Hello, """ + name + """! -Welcome to our community. We hope you have a great time here. -If you have any questions, feel free to reach out.""" - return greeting - -message = create_greeting("Alice") -print(message) - -multi_line_message = """<|fim|> -print(multi_line_message) -`, - llmOutput: `This is a multi-line message. -It continues across multiple lines, -which allows for easy reading and formatting. -""" -`, - expectedCompletion: `This is a multi-line message. -It continues across multiple lines, -which allows for easy reading and formatting. -""" -`, - }, - { - description: "Should autocomplete a simple Go function declaration", - filename: "simpleFunction.go", - input: `package main - -import ( - "fmt" -) - -func main() { - fmt.Println("Hello, World!") -} - -func calculateArea<|fim|>`, - llmOutput: `(length float64, width float64) float64 { - return length * width -}`, - expectedCompletion: `(length float64, width float64) float64 { - return length * width -}`, - }, - - { - description: - "Should handle autocomplete in the middle of a Go struct definition", - filename: "structDefinition.go", - input: `package main - -type Person struct { - FirstName string - LastName string - Age int - Address Address -} - -type Address struct { - Street string - City <|fim|> -} - -func main() {}`, - llmOutput: `string - State string - ZipCode string -}`, - expectedCompletion: `string - State string - ZipCode string -}`, - }, - - { - description: "Should autocomplete a missing Go function body bracket", - filename: "missingBracket.go", - input: `package main - -func add(a int, b int) int { - return a + b<|fim|> - -func multiply(a int, b int) int { - return a * b -} - -func main() { - result1 := add(2, 3) - result2 := multiply(4, 5) - println(result1, result2) -}`, - llmOutput: ` -}`, - expectedCompletion: ` -}`, - }, - { - description: - "Should autocomplete SQL query with subquery and alias in SELECT clause", - filename: "complex_query.sql", - input: `SELECT u.id, - u.name, - (SELECT COUNT(*) FROM orders o WHERE o.user_id = u.id) AS order_count - FROM users u - WHERE u.active = 1 - <|fim|>`, - llmOutput: ` AND EXISTS (SELECT 1 FROM transactions t WHERE t.user_id = u.id AND t.amount > 100)`, - expectedCompletion: ` AND EXISTS (SELECT 1 FROM transactions t WHERE t.user_id = u.id AND t.amount > 100)`, - }, - { - description: - "Should autocomplete SQL query with nested functions and missing bracket", - filename: "_nested_function.sql", - input: `SELECT name, ROUND(AVG(rating), 2) as avg_rating - FROM movies - WHERE release_year > 2000 AND director = 'Christopher Nolan' - GROUP BY name - HAVING avg_rating > <|fim|>`, - llmOutput: `8.5)`, - expectedCompletion: `8.5)`, - }, - { - description: - "Should autocomplete multi-line SQL query with CASE statements", - filename: "case_statement.sql", - input: `SELECT order_id, - order_date, - CASE - WHEN status = 'shipped' THEN 'Completed' - WHEN status = 'pending' THEN 'Pending Approval' - <|fim|> - ELSE 'Unknown' - END as order_status - FROM orders`, - llmOutput: `WHEN status = 'cancelled' THEN 'Cancelled'`, - expectedCompletion: `WHEN status = 'cancelled' THEN 'Cancelled'`, - }, - { - description: "Should autocomplete HTML paragraph content", - input: ` - - Document - - -

<|fim|>

- -`, - llmOutput: `This is a paragraph with some sample text.`, - expectedCompletion: `This is a paragraph with some sample text.`, - filename: "test.html", - }, - { - description: "Should autocomplete HTML attributes within a tag", - input: `
- > -
-

Title

-

Description text.

-
-
`, - llmOutput: `alt="Description of image"`, - expectedCompletion: `alt="Description of image"`, - filename: "test.html", - }, - { - description: "Should autocomplete HTML nested tags", - input: `
    -
  • Item 1
  • -
  • Item 2
  • -
  • Item 3
  • -
`, - llmOutput: `>Item 4`, - expectedCompletion: `>Item 4`, - filename: "test.html", - }, - - { - description: "Should complete a class method in Ruby", - input: ` -class Greeter - def initialize(name) - @name = name - end - - def greet - puts "Hello, <|fim|> - end -end - -g = Greeter.new("World") -g.greet -`, - llmOutput: "#{@name}!", - expectedCompletion: "#{@name}!", - filename: "greeter.rb", - }, - { - description: "Should complete Ruby if-else block", - input: ` -number = 10 - -if number > 5 - puts "Number is greater than 5" -<|fim|> -end -`, - llmOutput: `else - puts "Number is 5 or less"`, - expectedCompletion: `else - puts "Number is 5 or less"`, - filename: "conditional.rb", - }, - { - description: "Should complete Ruby array method", - input: ` -numbers = [1, 2, 3, 4, 5] -squared_numbers = numbers.<|fim|> -`, - llmOutput: `map { |n| n ** 2 }`, - expectedCompletion: `map { |n| n ** 2 }`, - filename: "array_methods.rb", - }, - { - description: "Should autocomplete a Java method within a class", - filename: "Calculator.java", - input: ` -public class Calculator { - private double result; - - public Calculator() { - this.result = 0.0; - } - - public void add(double number) { - result += number; -<|fim|>`, - llmOutput: ` - } - - public void subtract(double number) { - result -= number; - } -`, - expectedCompletion: ` - } - - public void subtract(double number) { - result -= number; - } -`, - }, - { - description: "Should autocomplete Java when inside a block", - filename: "Main.java", - input: ` -public class Main { - public static void main(String[] args) { - for (int i = 0; i < 10; i++) { - if (i % 2 == 0) { - System.out.println("Even: " + i); - } else { -<|fim|> - } - } - } -}`, - llmOutput: ` - System.out.println("Odd: " + i); -`, - expectedCompletion: ` - System.out.println("Odd: " + i); -`, - }, - { - description: "Should autocomplete Java within a string", - filename: "App.java", - input: ` -public class App { - public static void main(String[] args) { - String message = "Hello, <|fim|>"; - System.out.println(message); - } -}`, - llmOutput: `World`, - expectedCompletion: `World`, - }, - { - description: - "Should autocomplete a C++ class definition with a constructor", - filename: "test.cpp", - input: "class Vehicle { public: Vehicle(<|fim|>); };", - llmOutput: "int wheels, double weight", - expectedCompletion: "int wheels, double weight", - }, - { - description: "Should complete a C++ method declaration inside a class", - filename: "test.cpp", - input: - "class Calculator { public: int add(int a, int b); int subtract(int a, int b);<|fim|> };", - llmOutput: " int multiply(int a, int b);", - expectedCompletion: " int multiply(int a, int b);", - }, - - { - description: "Should autocomplete C++ for loop syntax", - filename: "test.cpp", - input: ` - int sum = 0; - for (int i = 0; i < 10; <|fim|>) { - sum += i; - } - `, - llmOutput: "i++", - expectedCompletion: "i++", - }, - { - description: "Should autocomplete a Markdown list with nested items", - filename: "test.md", - input: ` -- Item 1 -- Item 2 - - Subitem 1 - <|fim|> -- Item 3 -`, - llmOutput: ` - Subitem 2 - - Subitem 3 -`, - expectedCompletion: ` - Subitem 2 - - Subitem 3 -`, - }, - { - description: - "Should autocomplete a Markdown heading and preserve formatting", - filename: "test.md", - input: `# My Document - -## Introduction -This is a sample document for testing. - -## <|fim|> -### Conclusion -Thank you for reading. -`, - llmOutput: `Features -Here is a list of features: -- Feature 1 -- Feature 2 -`, - expectedCompletion: `Features -Here is a list of features: -- Feature 1 -- Feature 2 -`, - }, - { - description: "Should complete a Markdown code block", - filename: "test.md", - input: ` -Here is a sample JavaScript function: - -\`\`\`javascript -function sayHello() { - console.log("Hello, <|fim|> -} -\`\`\` -`, - llmOutput: `world!"); -`, - expectedCompletion: `world!"); -`, - }, - { - description: "Should autocomplete JSON object inside an array", - filename: "data.json", - input: `{ - "users": [ - { "id": 1, "name": "Alice" }, - { "id": 2, "name": "Bob" } - <|fim|> - ] -}`, - llmOutput: `, { "id": 3, "name": "Charlie" }`, - expectedCompletion: `, { "id": 3, "name": "Charlie" }`, - }, - { - description: "Should autocomplete nested JSON objects", - filename: "config.json", - input: `{ - "server": { - "host": "localhost", - "port": 8080, - "features": { - "enableLogging": true, - "maxConnections": 100 - <|fim|> - } -}`, - llmOutput: `, - "timeout": 5000 - }`, - expectedCompletion: `, - "timeout": 5000 - }`, - }, - { - description: "Should autocomplete JSON object with missing bracket", - filename: "settings.json", - input: `{ - "theme": "dark", - "language": "en"<|fim|> - `, - llmOutput: `, - "notifications": true - }`, - expectedCompletion: `, - "notifications": true - }`, - }, - { - description: "Should autocomplete within a CSV record", - filename: "test.csv", - input: `Name, Age, City -John Doe, 30, New York -Jane Smith<|fim|>`, - llmOutput: `, 25, Los Angeles`, - expectedCompletion: `, 25, Los Angeles`, - }, - { - description: - "Should complete CSV record when starting in the middle of a word", - filename: "test.csv", - input: `Product, Price, Quantity -Laptop, 1200, 5 -Smart<|fim|>`, - llmOutput: `phone, 800, 10`, - expectedCompletion: `phone, 800, 10`, - }, - { - description: "Should complete CSV structure adding closing brackets", - filename: "test.csv", - input: `ID, Name, JoiningDate -1, Alice, 2023-01-10 -2, B<|fim|>`, - llmOutput: `ob, 2023-02-10`, - expectedCompletion: `ob, 2023-02-10`, - }, - { - description: "Should complete YAML list item and preserve structure", - filename: "test.yaml", - input: ` - services: - - name: web - image: nginx - - name: app<|fim|> - volumes: - - volume1 - - volume2 - `, - llmOutput: ` - image: node - `, - expectedCompletion: ` - image: node - `, - }, - { - description: - "Should complete YAML key-value pair inside a nested structure", - filename: "test.yaml", - input: ` - version: '3' - services: - db: - image: postgres - environment: - POSTGRES_USER: user - POSTGRES_PASSWORD: pass - POSTGRES_DB: mydb<|fim|> - `, - llmOutput: ` - PGDATA: /var/lib/postgresql/data/pgdata - `, - expectedCompletion: ` - PGDATA: /var/lib/postgresql/data/pgdata - `, - }, - { - description: "Should complete YAML block within an existing block", - filename: "test.yaml", - input: ` - pipelines: - branches: - master: - - step: - name: Build and Test - script: - - npm install - - npm run test - - step: - name: Deploy<|fim|> - `, - llmOutput: ` - script: - - npm run deploy - `, - expectedCompletion: ` - script: - - npm run deploy - `, - }, - { - description: - "Should autocomplete a Rust function implementation inside a struct", - filename: "main.rs", - input: ` -struct Calculator { - result: f64, -} - -impl Calculator { - fn new() -> Self { - Calculator { result: 0.0 } - } - - fn add(&mut self, number: f64) { - self.result += number; - } - - fn subtract(&mut self, number: f64) { - self.result -= number; - } - - fn multiply(&mut self, number: f64) { - self.result *= number; - } - - fn divide(&mut self, number: f64) { - if number != 0.0 { - self.result /= number; - } else { - println!("Cannot divide by zero."); - } - } - - fn reset(&mut self) { - self.result = 0.0; - } - - fn get_result(&self) -> f64 { - self.result - } - - fn<|fim|> -} -`, - llmOutput: ` divide(&mut self, number: f64) { - if number != 0.0 { - self.result /= number; - } else { - println!("Cannot divide by zero."); - } -}`, - expectedCompletion: ` divide(&mut self, number: f64) { - if number != 0.0 { - self.result /= number; - } else { - println!("Cannot divide by zero."); - } -}`, - }, - { - description: "Should autocomplete Rust match arms", - filename: "main.rs", - input: ` -fn get_status_code_description(code: u16) -> &'static str { - match code { - 200 => "OK", - 404 => "Not Found", - 500 => "Internal Server Error", - <|fim|> - } -} -`, - llmOutput: `403 => "Forbidden", - 401 => "Unauthorized", - _ => "Unknown Status", -`, - expectedCompletion: `403 => "Forbidden", - 401 => "Unauthorized", - _ => "Unknown Status", -`, - }, - { - description: "Should autocomplete Rust struct definition", - filename: "main.rs", - input: ` -struct User { - id: u32, - username: String, - email: String, - is_active: bool, - <|fim|> -} - -impl User { - fn new(id: u32, username: String, email: String) -> Self { - User { - id, - username, - email, - is_active: true, - } - } -} -`, - llmOutput: `created_at: String, - updated_at: String,`, - expectedCompletion: `created_at: String, - updated_at: String,`, - }, - { - description: "Haskell: Nested pattern matching with let bindings", - filename: "NestedPattern.hs", - input: `module NestedPattern where - -data Tree a = Leaf a | Node (Tree a) (Tree a) - -sumTree :: Num a => Tree a -> a -sumTree (Leaf x) = x -sumTree (Node left right) = - let leftSum = <|fim|> - rightSum = sumTree right - in leftSum + rightSum`, - llmOutput: `sumTree left`, - expectedCompletion: `sumTree left`, - }, - { - description: "Haskell: Complex function with where clause and guards", - filename: "QuadraticSolver.hs", - input: `module QuadraticSolver where - -solveQuadratic :: (Ord a, Floating a) => a -> a -> a -> Maybe (a, a) -solveQuadratic a b c - | discriminant < 0 = Nothing - | otherwise = Just (x1, x2) - where - discriminant = b^2 - 4*a*c - sqrtD = sqrt discriminant - x1 = (-b + sqrtD) / (2*a) - <|fim|> = (-b - sqrtD) / (2*a)`, - llmOutput: `x2`, - expectedCompletion: `x2`, - }, - { - description: "Haskell: List comprehension with complex filter", - filename: "PrimeNumbers.hs", - input: `module PrimeNumbers where - -primesUpTo :: Int -> [Int] -primesUpTo n = [x | x <- [2..n], isPrime x] - where isPrime num = <|fim|> && all (\d -> num \`mod\` d /= 0) [2..(floor . sqrt $ fromIntegral num)]`, - llmOutput: `num > 1`, - expectedCompletion: `num > 1`, - }, - { - description: "Should autocomplete Dart class methods", - filename: "calculator.dart", - input: ` -class Calculator { - double result = 0.0; - - void add(double number) { - result += number; - } - - void multiply(double number) { - result *= number; - } - - <|fim|> - - double getResult() { - return result; - } -}`, - llmOutput: `void subtract(double number) { - result -= number; - }`, - expectedCompletion: `void subtract(double number) { - result -= number; - }`, - }, - { - description: "Should handle string interpolation in Dart", - filename: "greetings.dart", - input: ` -void main() { - var name = "World"; - print('Hello, <|fim|>!'); -}`, - llmOutput: `\${name}`, - expectedCompletion: `\${name}`, - }, - { - description: "Should autocomplete within a Dart function body", - filename: "counter.dart", - input: ` -class Counter { - int count = 0; - - void increment() { - count++; - } - - void decrement() { - <|fim|> - - void reset() { - count = 0; - } -}`, - llmOutput: `count--;`, - expectedCompletion: `count--;`, - }, - { - description: - "Should autocomplete Clojure function definition with missing closing parenthesis", - input: `(defn calculate-sum [a b] - (let [sum (+ a b)] - (println "The sum is" sum) - sum<|fim|>`, - llmOutput: `))`, - expectedCompletion: `))`, - filename: "test.clj", - }, - { - description: - "Should autocomplete missing part of a Clojure map within a function", - input: `(defn get-user [] - {:username "johndoe" - :email "johndoe@example.com" - :age 30 - <|fim|> - (println "User information loaded"))`, - llmOutput: `:location "Unknown"}`, - expectedCompletion: `:location "Unknown"}`, - filename: "test.clj", - }, - { - description: - "Should autocomplete inside a Clojure vector within a looping construct", - input: `(defn odd-numbers [] - (loop [nums [1 3 5<|fim|> 9 11]] - (when (seq nums) - (println (first nums)) - (recur (rest nums)))))`, - llmOutput: ` 7,`, - expectedCompletion: ` 7,`, - filename: "test.clj", - }, - { - description: "Should autocomplete R function definition", - filename: "calculate.R", - input: ` -calculate_mean <- function(numbers) { - total <- sum(numbers) - <|fim|> -}`, - llmOutput: `mean_value <- total / length(numbers) - return(mean_value)`, - expectedCompletion: `mean_value <- total / length(numbers) - return(mean_value)`, - }, - { - description: "Should complete R loop and print statement", - filename: "loopPrint.R", - input: ` -numbers <- c(1, 2, 3, 4, 5) -for (number in numbers) { - print(<|fim|>) -}`, - llmOutput: `number)`, - expectedCompletion: `number)`, - }, - { - description: "Should autocomplete R data frame creation", - filename: "dataFrame.R", - input: ` -data <- data.frame( - Name = c("Alice", "Bob", "Charlie"), - Age = c(25, 30, 35), - <|fim|> -)`, - llmOutput: `Height = c(165, 180, 175)`, - expectedCompletion: `Height = c(165, 180, 175)`, - }, - { - description: "Should autocomplete R if-else statement", - filename: "condition.R", - input: ` -grade <- 85 -if (grade >= 90) { - print("A") -} else if (grade >= 80) { - <|fim|> -} else { - print("C") -}`, - llmOutput: `print("B")`, - expectedCompletion: `print("B")`, - }, - { - description: "Should autocomplete R ggplot2 plot structure", - filename: "plot.R", - input: ` -library(ggplot2) - -ggplot(data=mtcars, aes(x=wt, y=mpg)) + - geom_point() + - <|fim|>`, - llmOutput: `geom_smooth(method='lm', se=FALSE)`, - expectedCompletion: `geom_smooth(method='lm', se=FALSE)`, - }, - { - description: "Should autocomplete Scala class with a method", - filename: "Person.scala", - input: `class Person(val name: String, val age: Int) { - def greet(): String = { - <|fim|> - } - }`, - llmOutput: `s"Hello, my name is $name and I am $age years old."`, - expectedCompletion: `s"Hello, my name is $name and I am $age years old."`, - }, - - { - description: "Should handle Scala case class with a missing field", - filename: "Person.scala", - input: `case class Address(city: String, postalCode: String) - case class Person(name: String, age: Int, address: Address) - - val alice = Person("Alice", 30, Address("Wonderland", <|fim|>))`, - llmOutput: `"12345")`, - expectedCompletion: `"12345")`, - }, - - { - description: "Should autocomplete Scala function with missing body bracket", - filename: "Math.scala", - input: `object MathUtils { - def add(a: Int, b: Int): Int = { - a + b<|fim|> - - def multiply(a: Int, b: Int): Int = { - a * b - } - } - - object Main extends App { - println(MathUtils.add(3, 5)) - println(MathUtils.multiply(4, 6)) - }`, - llmOutput: ` - }`, - expectedCompletion: ` - }`, - }, - { - description: "Should autocomplete C function definition", - filename: "math_utils.c", - input: `#include - -int add(int a, int b) { - return a + b; -} - -int multiply(int a, int b) { - return a * b; -} - -int subtract(int a, int b) { - <|fim|> -} - -int main() { - printf("Result: %d", add(2, 3)); - return 0; -}`, - llmOutput: `return a - b;`, - expectedCompletion: `return a - b;`, - }, - - { - description: "Should handle C struct with missing field initialization", - filename: "person.c", - input: `#include - -typedef struct { - char name[50]; - int age; - float height; -} Person; - -int main() { - Person alice = {"Alice", 30, <|fim|>}; - printf("Name: %s, Age: %d, Height: %.2f", alice.name, alice.age, alice.height); - return 0; -}`, - llmOutput: `5.5`, - expectedCompletion: `5.5`, - }, - - { - description: "Should autocomplete C function with missing body bracket", - filename: "area.c", - input: `#include - -double calculateCircleArea(double radius) { - const double pi = 3.14159; - return pi * radius * radius;<|fim|> - -double calculateRectangleArea(double length, double width) { - return length * width; -} - -int main() { - printf("Circle Area: %.2f", calculateCircleArea(5.0)); - printf("Rectangle Area: %.2f", calculateRectangleArea(4.0, 6.0)); - return 0; -}`, - llmOutput: ` -}`, - expectedCompletion: ` -}`, - }, - { - description: "Should autocomplete a simple Kotlin function declaration", - filename: "simpleFunction.kt", - input: ` -fun main() { - println("Hello, World!") -} - -fun calculateArea(length: Double, width: Double): Double <|fim|>`, - llmOutput: `{ - return length * width -}`, - expectedCompletion: `{ - return length * width -}`, - }, - { - description: "Should handle autocomplete inside a Kotlin data class", - filename: "dataClass.kt", - input: ` -data class User( - val id: Int, - val name: String, - val email: String, - <|fim|> -)`, - llmOutput: `val age: Int`, - expectedCompletion: `val age: Int`, - }, - { - description: - "Should complete Kotlin if-else structure with missing brackets", - filename: "controlStructure.kt", - input: ` -fun getMax(a: Int, b: Int): Int { - if (a > b<|fim|> - } else { - return b - } -}`, - llmOutput: `) { - return a`, - expectedCompletion: `) { - return a`, - }, - { - description: "Should autocomplete Solidity function definition", - filename: "SimpleStorage.sol", - input: ` -pragma solidity ^0.8.0; - -contract SimpleStorage { - uint private data; - - function set(uint x) public { - data = x; - } - - function get() public view returns (uint) { - <|fim|> - } -} - `, - llmOutput: `return data;`, - expectedCompletion: `return data;`, - }, - - { - description: "Should autocomplete Solidity event with parameters", - filename: "EventExample.sol", - input: ` -pragma solidity ^0.8.0; - -contract EventExample { - event DataStored(uint indexed id, string content); - - function storeData(uint id, string memory content) public { - emit DataStored(<|fim|>); - } -} - `, - llmOutput: `id, content`, - expectedCompletion: `id, content`, - }, - - { - description: "Should handle Solidity struct definition completion", - filename: "StructDefinition.sol", - input: ` -pragma solidity ^0.8.0; - -contract StructExample { - struct Person { - string name; - uint age; - address wallet; - } - - Person[] private people; - - function addPerson(string memory name, uint age, address wallet) public { - people.push(Person(name, age, wallet)); - } - - function getFirstPerson<|fim|> -} - `, - llmOutput: `() public view returns (string memory, uint, address) { - if (people.length > 0) { - Person storage person = people[0]; - return (person.name, person.age, person.wallet); - } - return ("", 0, address(0)); - }`, - expectedCompletion: `() public view returns (string memory, uint, address) { - if (people.length > 0) { - Person storage person = people[0]; - return (person.name, person.age, person.wallet); - } - return ("", 0, address(0)); - }`, - }, - { - description: "Should autocomplete TypeScript interface properties", - filename: "User.ts", - input: ` -interface User { - id: number; - name: string; - e<|fim|> -} -`, - llmOutput: `mail: string; - age: number; -}`, - expectedCompletion: `mail: string; - age: number; -}`, - }, - - { - description: - "Should autocomplete a TypeScript arrow function inside a variable assignment", - filename: "mathOperations.ts", - input: ` -const addNumbers = (a: number, b: number): number => { - return a + b; -}; - -const multiplyNumbers = (a: number, b: number): number => { - re<|fim|> -} - -console.log(multiplyNumbers(2, 3)); -`, - llmOutput: `turn a * b;`, - expectedCompletion: `turn a * b;`, - }, - - { - description: - "Should handle autocomplete inside a nested TypeScript class method", - filename: "Account.ts", - input: ` -class Account { - private balance: number = 0; - - deposit(amount: number) { - this.balance += amount; - return this.balance; - } - - withdraw(amount: number) { - if (amount > this.balance) { - throw new Error("Insufficient funds"); - } - this.balance -= amount; - return thi<|fim|> - } -} -`, - llmOutput: `s.balance;`, - expectedCompletion: `s.balance;`, - }, - - { - description: "Should autocomplete a TypeScript generic function", - filename: "GenericFunction.ts", - input: ` -function identity(arg: T): T { - return ar<|fim|> -} - -console.log(identity(5)); -`, - llmOutput: `g;`, - expectedCompletion: `g;`, - }, - - { - description: - "Should autocomplete a TypeScript promise within an asynchronous function", - filename: "asyncFunction.ts", - input: ` -async function fetchData(url: string): Promise { - const response = await fetch(url); - <|fim|> - return data; -} - -fetchData('https://api.example.com/data'); -`, - llmOutput: `const data = await response.json();`, - expectedCompletion: `const data = await response.json();`, - }, - - { - description: - "Should autocomplete a C# class with a constructor and property", - filename: "Person.cs", - input: `using System; - -public class Person -{ - public string Name { get; set; } - public int Age { get; set; } - - public Person(string name, int <|fim|> -}`, - llmOutput: `age) - { - Name = name; - Age = age; - }`, - expectedCompletion: `age) - { - Name = name; - Age = age; - }`, - }, - { - description: "Should autocomplete a C# interface method", - filename: "IGreetable.cs", - input: `public interface IGreetable -{ - void <|fim|> -}`, - llmOutput: `Greet();`, - expectedCompletion: `Greet();`, - }, - { - description: "Should autocomplete inside C# method with if condition", - filename: "Calculator.cs", - input: `using System; - -public class Calculator -{ - public int Add(int a, int b) - { - if(<|fim|>) - { - return a + b; - } - return 0; - } -}`, - llmOutput: `a > 0 && b > 0`, - expectedCompletion: `a > 0 && b > 0`, - }, - { - description: "Should complete a simple Julia function", - filename: "simpleFunction.jl", - input: `function calculate_area(length, width) - <|fim|> -end -`, - llmOutput: `return length * width`, - expectedCompletion: `return length * width`, - }, - { - description: "Should autocomplete Julia for loop", - filename: "loop.jl", - input: `numbers = [1, 2, 3, 4, 5] -squared_numbers = [] - -for num in numbers - <|fim|> -end - -println(squared_numbers) -`, - llmOutput: `push!(squared_numbers, num^2)`, - expectedCompletion: `push!(squared_numbers, num^2)`, - }, - { - description: "Should complete a Julia struct definition", - filename: "structDefinition.jl", - input: `struct Person - first_name::String - last_name::String - age::Int - address::Address -end - -struct Address - street::String - city::String - <|fim|> -end -`, - llmOutput: `state::String - zip_code::String`, - expectedCompletion: `state::String - zip_code::String`, - }, - { - description: "Should complete a Julia dictionary access", - filename: "dictionary.jl", - input: `grades = Dict("Alice" => 90, "Bob" => 85, "Eve" => 88) - -function get_grade(student_name) - return grades[<|fim|>] -end - -println(get_grade("Alice")) # Should print 90 -`, - llmOutput: `student_name`, - expectedCompletion: `student_name`, - }, - { - description: "Should complete a Julia module declaration", - filename: "moduleDeclaration.jl", - input: `module MathOperations - -export add, subtract - -function add(a, b) - return a + b -end - -function subtract(a, b) - return a - b -end - -<|fim|> -`, - llmOutput: `end`, - expectedCompletion: `end`, - }, - { - description: "Should complete F# let-binding with function definition", - filename: "mathModule.fs", - input: `module MathModule - -let calculateArea length width = - <|fim|>`, - llmOutput: `length * width`, - expectedCompletion: `length * width`, - }, - - { - description: "Should complete incomplete F# type definition", - filename: "personType.fs", - input: `type Person = { - FirstName: string - LastName: string - Age: int<|fim|> -} - -let john = { FirstName = "John"; LastName = "Doe"; Age = 30 }`, - llmOutput: ` - Address: string -}`, - expectedCompletion: ` - Address: string -}`, - }, - - { - description: "Should complete F# pattern matching expression", - filename: "patternMatching.fs", - input: `let describeNumber number = - match number with - | 0 -> "Zero" - | 1 -> "One" - | <|fim|>`, - llmOutput: `2 -> "Two" - | _ -> "Other"`, - expectedCompletion: `2 -> "Two" - | _ -> "Other"`, - }, - - { - description: "Should complete F# list comprehension expression", - filename: "listComprehension.fs", - input: `let squares = [ for x in 1..10 -> x * x ] -let evenSquares = [ for x in squares do if x % 2 = 0 then yield x ] -let oddSquares = [<|fim|>]`, - llmOutput: ` for x in squares do if x % 2 <> 0 then yield x ]`, - expectedCompletion: ` for x in squares do if x % 2 <> 0 then yield x ]`, - }, - - { - description: "Should complete an F# recursive function", - filename: "recursiveFunctions.fs", - input: `let rec factorial n = - if n <= 1 then 1 - else n <|fim|> factorial (n - 1)`, - llmOutput: ` * `, - expectedCompletion: ` * `, - }, - - { - description: "Should complete F# member method inside a class type", - filename: "bankAccount.fs", - input: `type BankAccount(owner: string, initialBalance: float) = - let mutable balance = initialBalance - - member this.Deposit amount = - balance <- balance + amount - this - <|fim|>`, - llmOutput: ` - member this.Withdraw amount = - if amount > balance then - failwith "Insufficient funds" - balance <- balance - amount - this`, - expectedCompletion: ` - member this.Withdraw amount = - if amount > balance then - failwith "Insufficient funds" - balance <- balance - amount - this`, - }, - - { - description: "Should complete F# async workflow function", - filename: "asyncWorkflow.fs", - input: `let fetchDataAsync url = - async { - use client = new System.Net.Http.HttpClient() - <|fim|> - }`, - llmOutput: `let! response = client.GetStringAsync(url) - return response`, - expectedCompletion: `let! response = client.GetStringAsync(url) - return response`, - }, - { - description: "Should autocomplete SCSS nested class starting inside a rule", - filename: "styles.scss", - input: `nav { - display: flex; - justify-content: space-between; - .logo { - font-size: 1.5rem; - color: #333; - - .brand<|fim|> - } - - ul { - list-style: none; - display: flex; - gap: 1rem; - } -}`, - llmOutput: `-name { - font-weight: bold; - text-transform: uppercase; -}`, - expectedCompletion: `-name { - font-weight: bold; - text-transform: uppercase; -}`, - }, - - { - description: "Should handle SCSS mixin within a class", - filename: "styles.scss", - input: `.card { - border: 1px solid #ccc; - padding: 10px; - - @include<|fim|> - - &:hover { - box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); - } -}`, - llmOutput: ` transition(all 0.3s ease);`, - expectedCompletion: ` transition(all 0.3s ease);`, - }, - - { - description: - "Should autocomplete SCSS variable in the middle of a statement", - filename: "styles.scss", - input: `$primary-color: #007bff; -$secondary-color: #6c757d; - -.button { - background-color: <|fim|> color; - padding: 10px 15px; - border: none; - color: #fff; - border-radius: 4px; -}`, - llmOutput: `$primary-`, - expectedCompletion: `$primary-`, - }, - { - description: "Should autocomplete Vue component method", - filename: "MyComponent.vue", - input: ` - - -`, - llmOutput: `() { - this.count = 0; - }`, - expectedCompletion: `() { - this.count = 0; - }`, - }, - { - description: "Should autocomplete Vue computed property", - filename: "UserComponent.vue", - input: ` - - -`, - llmOutput: `() { - return this.firstName + ' ' + this.lastName; - }`, - expectedCompletion: `() { - return this.firstName + ' ' + this.lastName; - }`, - }, - { - description: "Should autocomplete Vue method using props", - filename: "TodoItem.vue", - input: ` - - -`, - llmOutput: `this.completed`, - expectedCompletion: `this.completed`, - }, - { - description: "Should autocomplete Svelte reactive statement", - filename: "Counter.svelte", - input: ` - - - -`, - llmOutput: `doubledCount = count * 2`, - expectedCompletion: `doubledCount = count * 2`, - }, - - { - description: "Should autocomplete Svelte component inside HTML", - filename: "NestedComponent.svelte", - input: ` - - -
-

Hello Svelte

- /> -
-`, - llmOutput: `name="World"`, - expectedCompletion: `name="World"`, - }, - - { - description: "Should handle autocomplete in Svelte each block", - filename: "List.svelte", - input: ` - - -
    - {#each items as item} -
  • {item}
  • - {/each<|fim|> -
-`, - llmOutput: `}`, - expectedCompletion: `}`, - }, -]; diff --git a/core/autocomplete/test/util.ts b/core/autocomplete/test/util.ts deleted file mode 100644 index bfcf31885..000000000 --- a/core/autocomplete/test/util.ts +++ /dev/null @@ -1,75 +0,0 @@ -import fs from "node:fs"; -import path from "node:path"; -import Mock from "../../llm/llms/Mock"; -import { testConfigHandler, testIde } from "../../test/util/fixtures"; -import { CompletionProvider } from "../CompletionProvider"; -import { AutocompleteInput } from "../util/types"; - -const FIM_DELIMITER = "<|fim|>"; - -function parseFimExample(text: string): { prefix: string; suffix: string } { - const [prefix, suffix] = text.split(FIM_DELIMITER); - return { prefix, suffix }; -} - -export interface AutocompleteFileringTestInput { - description: string; - filename: string; - input: string; - llmOutput: string; - expectedCompletion: string | null; - options?: { - only?: boolean; - }; -} - -export async function testAutocompleteFiltering( - test: AutocompleteFileringTestInput, -) { - const { prefix, suffix } = parseFimExample(test.input); - - // Setup necessary objects - const llm = new Mock({ - model: "mock", - }); - llm.completion = test.llmOutput; - const ide = testIde; - const configHandler = testConfigHandler; - - // Create a real file - const [workspaceDir] = await ide.getWorkspaceDirs(); - const filepath = path.join(workspaceDir, test.filename); - fs.writeFileSync(filepath, test.input.replace(FIM_DELIMITER, "")); - - // Prepare completion input and provider - const completionProvider = new CompletionProvider( - configHandler, - ide, - async () => llm, - () => {}, - async () => [], - ); - - const line = prefix.split("\n").length - 1; - const character = prefix.split("\n")[line].length; - const autocompleteInput: AutocompleteInput = { - clipboardText: "", - completionId: "test-completion-id", - filepath, - pos: { - line, - character, - }, - recentlyEditedFiles: [], - recentlyEditedRanges: [], - }; - - // Generate a completion - const result = await completionProvider.provideInlineCompletionItems( - autocompleteInput, - undefined, - ); - - // Ensure that we return the text that is wanted to be displayed - expect(result?.completion).toEqual(test.expectedCompletion); -} From 9404ba5171b75cf90d3038adb00624da0ebeeab8 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Tue, 5 Nov 2024 11:12:21 +0700 Subject: [PATCH 52/96] test: set up and tear down test dir --- core/autocomplete/filtering/test/filter.test.ts | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/core/autocomplete/filtering/test/filter.test.ts b/core/autocomplete/filtering/test/filter.test.ts index 171b1cb44..04b5a193a 100644 --- a/core/autocomplete/filtering/test/filter.test.ts +++ b/core/autocomplete/filtering/test/filter.test.ts @@ -3,6 +3,7 @@ import { testAutocompleteFiltering, } from "./util"; import { TEST_CASES } from "./testCases"; +import { setUpTestDir, tearDownTestDir } from "../../../test/util/testDir"; const filterTestCases = (tests: AutocompleteFileringTestInput[]) => { if (tests.some((test) => test.options?.only)) { @@ -13,6 +14,15 @@ const filterTestCases = (tests: AutocompleteFileringTestInput[]) => { }; describe("llms/Mock", () => { + beforeAll(async () => { + tearDownTestDir(); + setUpTestDir(); + }); + + afterAll(async () => { + tearDownTestDir(); + }); + describe("Autocomplete Filtering Tests", () => { beforeEach(async () => { await new Promise((resolve) => setTimeout(resolve, 50)); From f88f28b8551e95e4eb346fafa68d6223f9017d5a Mon Sep 17 00:00:00 2001 From: Test Date: Mon, 4 Nov 2024 21:55:08 -0800 Subject: [PATCH 53/96] feat: impl /multifile-edit --- core/commands/slash/index.ts | 4 +- core/commands/slash/multifileEdit.ts | 67 +++++++++++++++++++ core/protocol/ideWebview.ts | 14 ++-- .../continue/IdeProtocolClient.kt | 2 +- extensions/vscode/package-lock.json | 4 +- extensions/vscode/package.json | 2 +- extensions/vscode/src/VsCodeIde.ts | 2 +- .../vscode/src/diff/vertical/manager.ts | 24 ------- .../vscode/src/extension/VsCodeMessenger.ts | 33 ++++++++- extensions/vscode/src/util/ideUtils.ts | 6 +- extensions/vscode/src/util/util.ts | 20 +++--- .../components/markdown/CodeBlockToolbar.tsx | 29 ++++---- 12 files changed, 146 insertions(+), 61 deletions(-) create mode 100644 core/commands/slash/multifileEdit.ts diff --git a/core/commands/slash/index.ts b/core/commands/slash/index.ts index f94c6ee05..472684a7e 100644 --- a/core/commands/slash/index.ts +++ b/core/commands/slash/index.ts @@ -4,9 +4,10 @@ import CommitMessageCommand from "./commit"; import DraftIssueCommand from "./draftIssue"; import EditSlashCommand from "./edit"; import HttpSlashCommand from "./http"; +import MultiFileEditSlashCommand from "./multifileEdit"; +import OnboardSlashCommand from "./onboard"; import ReviewMessageCommand from "./review"; import ShareSlashCommand from "./share"; -import OnboardSlashCommand from "./onboard"; export default [ DraftIssueCommand, @@ -18,4 +19,5 @@ export default [ CommitMessageCommand, ReviewMessageCommand, OnboardSlashCommand, + MultiFileEditSlashCommand, ]; diff --git a/core/commands/slash/multifileEdit.ts b/core/commands/slash/multifileEdit.ts new file mode 100644 index 000000000..d045e0a2f --- /dev/null +++ b/core/commands/slash/multifileEdit.ts @@ -0,0 +1,67 @@ +import { SlashCommand } from "../.."; +import { stripImages } from "../../llm/images"; + +const MultiFileEditSlashCommand: SlashCommand = { + name: "multifile-edit", + description: "Edit multiple files in the codebase at once", + run: async function* ({ llm, contextItems, input }) { + const filesToEditStr = contextItems.map((item) => item.content).join("\n"); + + const content = createPrompt(filesToEditStr, input); + + for await (const chunk of llm.streamChat([{ role: "user", content }])) { + yield stripImages(chunk.content); + } + }, +}; + +function createPrompt(filesToEditStr: string, input: string): string { + return ` +You are an AI assistant designed to help software engineers make multi-file edits in their codebase. Your task is to generate the necessary code changes for multiple files based on the engineer's request. Follow these guidelines: + +1. Start with a brief introduction of the task you're about to perform. Do not start with any other preamble, such as "Certainly!" +2. When providing instructions, if a user needs to interact with a CLI, walk them through each step +2. Perform file edits in a logical, sequential ordering +3. For each file edit, provide a brief explanation of the changes +4. 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. + a. When creating new files, also inlcude the filname in the language specifier of the code block. +6. After providing all file changes, include a brief, sequential overview of the most important 3-5 edits + +Remember to be concise and focus on the code changes and their impact. + +Here's an example of how your response should be structured: + + +I'll make the following changes to implement feature X: + +1. First, I'll modify file1.js to add a new function: +\`\`\`javascript /path/to/file1.js +// Entire content of file1.js or changes to be made +\`\`\` + +2. Next, let's create a new test file: +\`\`\`javascript /path/to/file1.test.js +# Entire content of file2.py or changes to be made +\`\`\` + +Summary: +- [Sequential overview of the most important 3-5 edits] + + +Now, let's make the changes based on the engineer's request: + + +${input} + + +Here are the files to edit: + + +${filesToEditStr} + + +Please provide the multi-file edit details based on the engineer's request. + `; +} + +export default MultiFileEditSlashCommand; diff --git a/core/protocol/ideWebview.ts b/core/protocol/ideWebview.ts index 0526fb499..cce7c6cb0 100644 --- a/core/protocol/ideWebview.ts +++ b/core/protocol/ideWebview.ts @@ -1,8 +1,9 @@ -import type { RangeInFileWithContents } from "../commands/util.js"; -import type { ContextSubmenuItem, MessageContent } from "../index.js"; import { ToIdeFromWebviewOrCoreProtocol } from "./ide.js"; import { ToWebviewFromIdeOrCoreProtocol } from "./webview.js"; +import type { RangeInFileWithContents } from "../commands/util.js"; +import type { ContextSubmenuItem, MessageContent } from "../index.js"; + export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & { onLoad: [ undefined, @@ -17,8 +18,13 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & { openUrl: [string, void]; // We pass the `curSelectedModel` because we currently cannot access the // default model title in the GUI from JB - applyToCurrentFile: [ - { text: string; streamId: string; curSelectedModelTitle: string }, + applyToFile: [ + { + text: string; + streamId: string; + curSelectedModelTitle: string; + filepath: string; + }, void, ]; showTutorial: [undefined, void]; diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt index 1295d0002..17c89ec85 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt @@ -632,7 +632,7 @@ class IdeProtocolClient( } } - "applyToCurrentFile" -> { + "applyToFile" -> { val msg = data as Map; val text = msg["text"] as String val curSelectedModelTitle = msg["curSelectedModelTitle"] as String diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 44ade3c05..c39c6391c 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "0.9.225", + "version": "0.9.227", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "0.9.225", + "version": "0.9.227", "license": "Apache-2.0", "dependencies": { "@electron/rebuild": "^3.2.10", diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index cc2a41fb6..231f856c1 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -2,7 +2,7 @@ "name": "continue", "icon": "media/icon.png", "author": "Continue Dev, Inc", - "version": "0.9.225", + "version": "0.9.227", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" diff --git a/extensions/vscode/src/VsCodeIde.ts b/extensions/vscode/src/VsCodeIde.ts index 43911c6f8..c36516018 100644 --- a/extensions/vscode/src/VsCodeIde.ts +++ b/extensions/vscode/src/VsCodeIde.ts @@ -384,7 +384,7 @@ class VsCodeIde implements IDE { } async openFile(path: string): Promise { - this.ideUtils.openFile(path); + await this.ideUtils.openFile(path); } async showLines( diff --git a/extensions/vscode/src/diff/vertical/manager.ts b/extensions/vscode/src/diff/vertical/manager.ts index c6f3c2aa7..88ed3831f 100644 --- a/extensions/vscode/src/diff/vertical/manager.ts +++ b/extensions/vscode/src/diff/vertical/manager.ts @@ -257,30 +257,6 @@ export class VerticalDiffManager { } } - /** - * Streams an edit to the current document based on user input and model output. - * - * @param input - The user's input or instruction for the edit. - * @param modelTitle - The title of the language model to be used. - * @param [onlyOneInsertion] - Optional flag to limit the edit to a single insertion. - * @param [quickEdit] - Optional string indicating if this is a quick edit. - * @param [range] - Optional range to use instead of the highlighted text. Note that the `quickEdit` - * property currently can't be passed with `range` since it assumes there is an - * active selection. - * - * This method performs the following steps: - * 1. Sets up the editor context for the diff. - * 2. Determines the range of text to be edited. - * 3. Clears any existing diff handlers for the file. - * 4. Creates a new vertical diff handler. - * 5. Prepares the context (prefix and suffix) for the language model. - * 6. Streams the diff lines from the language model. - * 7. Applies the changes to the document. - * 8. Sets up a listener for subsequent user edits. - * - * The method handles various edge cases, such as quick edits and existing diffs, - * and manages the lifecycle of diff handlers and document change listeners. - */ async streamEdit( input: string, modelTitle: string | undefined, diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index 483ff1603..954f30349 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -29,6 +29,7 @@ import { import { getExtensionUri } from "../util/vscode"; import { VsCodeIde } from "../VsCodeIde"; import { VsCodeWebviewProtocol } from "../webviewProtocol"; +import { getFullyQualifiedPath } from "../util/util"; /** * A shared messenger class between Core and Webview @@ -85,7 +86,11 @@ export class VsCodeMessenger { ) { /** WEBVIEW ONLY LISTENERS **/ this.onWebview("showFile", (msg) => { - this.ide.openFile(msg.data.filepath); + const fullPath = getFullyQualifiedPath(msg.data.filepath); + + if (fullPath) { + this.ide.openFile(fullPath); + } }); this.onWebview("vscode/openMoveRightMarkdown", (msg) => { @@ -153,9 +158,33 @@ export class VsCodeMessenger { await vscode.commands.executeCommand("continue.rejectDiff", filepath); }); - this.onWebview("applyToCurrentFile", async ({ data }) => { + this.onWebview("applyToFile", async ({ data }) => { + const fullPath = getFullyQualifiedPath(data.filepath); + + if (!fullPath) { + return; + } + + const fileExists = await this.ide.fileExists(fullPath); + + // If it's a new file, no need to apply, just write directly + if (!fileExists) { + await this.ide.writeFile(fullPath, data.text); + await this.ide.openFile(fullPath); + + await webviewProtocol.request("updateApplyState", { + streamId: data.streamId, + status: "done", + }); + + return; + } + + await this.ide.openFile(fullPath); + // Get active text editor const editor = vscode.window.activeTextEditor; + if (!editor) { vscode.window.showErrorMessage("No active editor to apply edits to"); return; diff --git a/extensions/vscode/src/util/ideUtils.ts b/extensions/vscode/src/util/ideUtils.ts index 14ebd9ed2..6ebb9c1a1 100644 --- a/extensions/vscode/src/util/ideUtils.ts +++ b/extensions/vscode/src/util/ideUtils.ts @@ -136,9 +136,7 @@ export class VsCodeIdeUtils { ); } - private async resolveAbsFilepathInWorkspace( - filepath: string, - ): Promise { + async resolveAbsFilepathInWorkspace(filepath: string): Promise { // If the filepath is already absolute, return it as is if (this.path.isAbsolute(filepath)) { return filepath; @@ -158,7 +156,7 @@ export class VsCodeIdeUtils { async openFile(filepath: string, range?: vscode.Range) { // vscode has a builtin open/get open files - return openEditorAndRevealRange( + return await openEditorAndRevealRange( await this.resolveAbsFilepathInWorkspace(filepath), range, vscode.ViewColumn.One, diff --git a/extensions/vscode/src/util/util.ts b/extensions/vscode/src/util/util.ts index 2d0ae72a7..4ac832455 100644 --- a/extensions/vscode/src/util/util.ts +++ b/extensions/vscode/src/util/util.ts @@ -124,14 +124,16 @@ export function getExtensionVersion(): string { } export function getFullyQualifiedPath(filepath?: string) { - if (filepath && !path.isAbsolute(filepath)) { - const workspaceFolders = vscode.workspace.workspaceFolders; - if (workspaceFolders && workspaceFolders.length > 0) { - return path.join(workspaceFolders[0].uri.fsPath, filepath); - } else { - vscode.window.showErrorMessage( - "Unable to resolve filepath: no workspace folder found", - ); - } + if (!filepath) return; + if (path.isAbsolute(filepath)) return filepath; + + const workspaceFolders = vscode.workspace.workspaceFolders; + + if (workspaceFolders && workspaceFolders.length > 0) { + return path.join(workspaceFolders[0].uri.fsPath, filepath); + } else { + vscode.window.showErrorMessage( + "Unable to resolve filepath: no workspace folder found", + ); } } diff --git a/gui/src/components/markdown/CodeBlockToolbar.tsx b/gui/src/components/markdown/CodeBlockToolbar.tsx index b5380e26d..a01dd78d2 100644 --- a/gui/src/components/markdown/CodeBlockToolbar.tsx +++ b/gui/src/components/markdown/CodeBlockToolbar.tsx @@ -176,19 +176,24 @@ function CodeBlockToolBar(props: CodeBlockToolBarProps) { if (isTerminal) { await ideMessenger.ide.runCommand(getTerminalCommand(props.text)); - } else { - ideMessenger.post("applyToCurrentFile", { - curSelectedModelTitle: defaultModel.title, - text: props.text, - streamId: streamIdRef.current, - }); - dispatch( - updateApplyState({ - streamId: streamIdRef.current, - status: "streaming", - }), - ); + return; } + + if (!props.filepath) return; + + dispatch( + updateApplyState({ + streamId: streamIdRef.current, + status: "streaming", + }), + ); + + ideMessenger.post("applyToFile", { + curSelectedModelTitle: defaultModel.title, + text: props.text, + streamId: streamIdRef.current, + filepath: props.filepath, + }); } function onClickHeader() { From dca5927bcfdd22fddd853909bb145cfc5d27ac01 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Tue, 5 Nov 2024 11:27:55 +0700 Subject: [PATCH 54/96] improv: fix failing autocomplete test cases --- core/autocomplete/CompletionProvider.ts | 19 +- .../classification/shouldCompleteMultiline.ts | 28 +- .../constants/AutocompleteLanguageInfo.ts | 23 +- .../StreamTransformPipeline.ts | 14 +- .../filtering/streamTransforms/lineStream.ts | 37 +- .../filtering/test/filter.test.ts | 21 +- core/autocomplete/filtering/test/testCases.ts | 365 +++++++++--------- core/autocomplete/postprocessing/index.ts | 29 +- core/autocomplete/prefiltering/index.ts | 12 +- core/util/ranges.ts | 2 +- 10 files changed, 277 insertions(+), 273 deletions(-) diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts index 2c7950288..cb162043a 100644 --- a/core/autocomplete/CompletionProvider.ts +++ b/core/autocomplete/CompletionProvider.ts @@ -180,12 +180,11 @@ export class CompletionProvider { this.contextRetrievalService, ); - const { - prompt, - prefix: finalPrefix, - suffix: finalSuffix, - completionOptions, - } = renderPrompt(snippets, await this.ide.getWorkspaceDirs(), helper); + const { prompt, prefix, suffix, completionOptions } = renderPrompt( + snippets, + await this.ide.getWorkspaceDirs(), + helper, + ); // Completion let completion: string | undefined = ""; @@ -207,8 +206,8 @@ export class CompletionProvider { this.completionStreamer.streamCompletionWithFilters( token, llm, - finalPrefix, - finalSuffix, + prefix, + suffix, prompt, multiline, completionOptions, @@ -243,8 +242,8 @@ export class CompletionProvider { const outcome: AutocompleteOutcome = { time: Date.now() - startTime, completion, - prefix: finalPrefix, - suffix: finalSuffix, + prefix, + suffix, prompt, modelProvider: llm.providerName, modelName: llm.model, diff --git a/core/autocomplete/classification/shouldCompleteMultiline.ts b/core/autocomplete/classification/shouldCompleteMultiline.ts index 16d2a6c47..75cfdcd70 100644 --- a/core/autocomplete/classification/shouldCompleteMultiline.ts +++ b/core/autocomplete/classification/shouldCompleteMultiline.ts @@ -10,8 +10,7 @@ function shouldCompleteMultilineBasedOnLanguage( prefix: string, suffix: string, ) { - let langMultilineDecision = language.useMultiline?.({ prefix, suffix }); - return langMultilineDecision; + return language.useMultiline?.({ prefix, suffix }) ?? true; } export function shouldCompleteMultiline(helper: HelperVars) { @@ -29,13 +28,14 @@ export function shouldCompleteMultiline(helper: HelperVars) { return true; } - // Don't complete multi-line if you are mid-line - if (isMidlineCompletion(helper.fullPrefix, helper.fullSuffix)) { - return false; - } + // // Don't complete multi-line if you are mid-line + // if (isMidlineCompletion(helper.fullPrefix, helper.fullSuffix)) { + // return false; + // } // Don't complete multi-line for single-line comments if ( + helper.lang.singleLineComment && helper.fullPrefix .split("\n") .slice(-1)[0] @@ -45,15 +45,9 @@ export function shouldCompleteMultiline(helper: HelperVars) { return false; } - if ( - shouldCompleteMultilineBasedOnLanguage( - helper.lang, - helper.prunedPrefix, - helper.prunedSuffix, - ) - ) { - return true; - } - - return false; + return shouldCompleteMultilineBasedOnLanguage( + helper.lang, + helper.prunedPrefix, + helper.prunedSuffix, + ); } diff --git a/core/autocomplete/constants/AutocompleteLanguageInfo.ts b/core/autocomplete/constants/AutocompleteLanguageInfo.ts index 397d32ed6..88ba93aa9 100644 --- a/core/autocomplete/constants/AutocompleteLanguageInfo.ts +++ b/core/autocomplete/constants/AutocompleteLanguageInfo.ts @@ -3,14 +3,11 @@ import { LineFilter } from "../filtering/streamTransforms/lineStream"; export interface AutocompleteLanguageInfo { name: string; topLevelKeywords: string[]; - singleLineComment: string; + singleLineComment?: string; endOfLine: string[]; stopWords?: string[]; lineFilters?: LineFilter[]; - useMultiline?: (args: { - prefix: string; - suffix: string; - }) => boolean | undefined; + useMultiline?: (args: { prefix: string; suffix: string }) => boolean; } // TypeScript @@ -256,10 +253,8 @@ export const YAML: AutocompleteLanguageInfo = { } else { seenListItem = true; } - yield line; - } else { - yield line; } + yield line; } }, // Don't allow consecutive lines of same key @@ -268,12 +263,14 @@ export const YAML: AutocompleteLanguageInfo = { for await (const line of lines) { if (line.includes(":")) { const key = line.split(":")[0]; - if (key !== lastKey) { + if (key === lastKey) { + break; + } else { yield line; lastKey = key; - } else { - break; } + } else { + yield line; } } }, @@ -289,7 +286,7 @@ export const Markdown: AutocompleteLanguageInfo = { const singleLineStarters = ["- ", "* ", /^\d+\. /, "> ", "```", /^#{1,6} /]; let currentLine = prefix.split("\n").pop(); if (!currentLine) { - return undefined; + return true; } currentLine = currentLine.trim(); for (const starter of singleLineStarters) { @@ -301,7 +298,7 @@ export const Markdown: AutocompleteLanguageInfo = { return false; } } - return undefined; + return true; }, }; diff --git a/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts b/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts index 037059912..6b3262192 100644 --- a/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts +++ b/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts @@ -28,13 +28,13 @@ export class StreamTransformPipeline { let charGenerator = generator; charGenerator = stopAtStopTokens(generator, stopTokens); - charGenerator = this.bracketMatchingService.stopOnUnmatchedClosingBracket( - charGenerator, - prefix, - suffix, - helper.filepath, - multiline, - ); + // charGenerator = this.bracketMatchingService.stopOnUnmatchedClosingBracket( + // charGenerator, + // prefix, + // suffix, + // helper.filepath, + // multiline, + // ); let lineGenerator = streamLines(charGenerator); diff --git a/core/autocomplete/filtering/streamTransforms/lineStream.ts b/core/autocomplete/filtering/streamTransforms/lineStream.ts index dffca36b9..e305062cf 100644 --- a/core/autocomplete/filtering/streamTransforms/lineStream.ts +++ b/core/autocomplete/filtering/streamTransforms/lineStream.ts @@ -14,14 +14,6 @@ function isBracketEnding(line: string): boolean { .some((char) => BRACKET_ENDING_CHARS.includes(char)); } -function commonPrefixLength(a: string, b: string): number { - let i = 0; - while (i < a.length && i < b.length && a[i] === b[i]) { - i++; - } - return i; -} - function isEnglishFirstLine(line: string) { line = line.trim().toLowerCase(); @@ -130,7 +122,7 @@ export async function* noTopLevelKeywordsMidline( */ export async function* avoidPathLine( stream: LineStream, - comment: string, + comment?: string, ): LineStream { // Snippets are inserted as comments with a line at the start '// Path: '. // Sometimes the model with copy this pattern, which is unwanted @@ -151,14 +143,13 @@ export async function* avoidPathLine( */ export async function* avoidEmptyComments( stream: LineStream, - comment: string, + comment?: string, ): LineStream { // Filter lines that are empty comments for await (const line of stream) { - if (line.trim() === comment) { - continue; + if (!comment || line.trim() !== comment) { + yield line; } - yield line; } } @@ -187,9 +178,7 @@ export async function* streamWithNewLines(stream: LineStream): LineStream { * @returns {boolean} True if the lines are considered repeated, false otherwise. * * @description - * This function checks if two lines are repeated or very similar based on two criteria: - * 1. They have a common prefix longer than 12 characters. - * 2. The Levenshtein distance between them is less than 10% of the length of the second line. + * This function checks if the Levenshtein distance between them is less than 10% of the length of the second line. * Lines shorter than 5 characters are never considered repeated. */ export function lineIsRepeated(a: string, b: string): boolean { @@ -199,10 +188,7 @@ export function lineIsRepeated(a: string, b: string): boolean { const aTrim = a.trim(); const bTrim = b.trim(); - return ( - commonPrefixLength(aTrim, bTrim) > 12 || - distance(aTrim, bTrim) / bTrim.length < 0.1 - ); + return distance(aTrim, bTrim) / bTrim.length < 0.05; } /** @@ -229,9 +215,9 @@ export async function* stopAtSimilarLine( const lineIsBracketEnding = isBracketEnding(trimmedLine); for await (const nextLine of stream) { - if (nextLine === line) { - fullStop(); - break; + if (trimmedLine === "") { + yield nextLine; + continue; } if (lineIsBracketEnding && trimmedLine.trim() === nextLine.trim()) { @@ -239,6 +225,11 @@ export async function* stopAtSimilarLine( continue; } + if (nextLine === line) { + fullStop(); + break; + } + if (lineIsRepeated(nextLine, trimmedLine)) { fullStop(); break; diff --git a/core/autocomplete/filtering/test/filter.test.ts b/core/autocomplete/filtering/test/filter.test.ts index 04b5a193a..62ef65512 100644 --- a/core/autocomplete/filtering/test/filter.test.ts +++ b/core/autocomplete/filtering/test/filter.test.ts @@ -2,7 +2,7 @@ import { AutocompleteFileringTestInput, testAutocompleteFiltering, } from "./util"; -import { TEST_CASES } from "./testCases"; +import { TEST_CASES_WITH_DIFF, TEST_CASES_WITHOUT_DIFF } from "./testCases"; import { setUpTestDir, tearDownTestDir } from "../../../test/util/testDir"; const filterTestCases = (tests: AutocompleteFileringTestInput[]) => { @@ -29,12 +29,21 @@ describe("llms/Mock", () => { }); describe("Should return unmodified LLM output", () => { - it.each(filterTestCases(TEST_CASES))("$description", async (testCase) => { - await testAutocompleteFiltering(testCase); - }); + it.each(filterTestCases(TEST_CASES_WITHOUT_DIFF))( + "$description", + async (testCase) => { + await testAutocompleteFiltering(testCase); + }, + ); }); - // TODO: Add test cases where modifying LLM output is desirable - describe.skip("Should return modified LLM output", () => {}); + describe("Should return modified LLM output", () => { + it.each(filterTestCases(TEST_CASES_WITH_DIFF))( + "$description", + async (testCase) => { + await testAutocompleteFiltering(testCase); + }, + ); + }); }); }); diff --git a/core/autocomplete/filtering/test/testCases.ts b/core/autocomplete/filtering/test/testCases.ts index c3c19dfea..1f0397363 100644 --- a/core/autocomplete/filtering/test/testCases.ts +++ b/core/autocomplete/filtering/test/testCases.ts @@ -1,7 +1,180 @@ import { dedent } from "../../../util"; import { AutocompleteFileringTestInput } from "./util"; -export const TEST_CASES: AutocompleteFileringTestInput[] = [ +export const TEST_CASES_WITH_DIFF: AutocompleteFileringTestInput[] = [ + { + description: "Should handle python multi-line string", + filename: "test.py", + input: `def create_greeting(name): + greeting = """Hello, """ + name + """! +Welcome to our community. We hope you have a great time here. +If you have any questions, feel free to reach out.""" + return greeting + +message = create_greeting("Alice") +print(message) + +multi_line_message = """<|fim|> +print(multi_line_message) +`, + llmOutput: `This is a multi-line message. +It continues across multiple lines, +which allows for easy reading and formatting. +""" +`, + expectedCompletion: `This is a multi-line message. +It continues across multiple lines, +which allows for easy reading and formatting. +"""`, + }, + { + description: "Should autocomplete Rust match arms", + filename: "main.rs", + input: ` +fn get_status_code_description(code: u16) -> &'static str { + match code { + 200 => "OK", + 404 => "Not Found", + 500 => "Internal Server Error", + <|fim|> + } +} +`, + llmOutput: `403 => "Forbidden", + 401 => "Unauthorized", + _ => "Unknown Status", +`, + expectedCompletion: `403 => "Forbidden", + 401 => "Unauthorized", + _ => "Unknown Status",`, + }, + { + description: "Should complete a Markdown code block", + filename: "test.md", + input: ` +Here is a sample JavaScript function: + +\`\`\`javascript +function sayHello() { + console.log("Hello, <|fim|> +} +\`\`\` +`, + llmOutput: `world!"); +`, + expectedCompletion: `world!");`, + }, + { + description: "Should autocomplete Java when inside a block", + filename: "Main.java", + input: ` +public class Main { + public static void main(String[] args) { + for (int i = 0; i < 10; i++) { + if (i % 2 == 0) { + System.out.println("Even: " + i); + } else { +<|fim|> + } + } + } +}`, + llmOutput: ` + System.out.println("Odd: " + i); +`, + expectedCompletion: ` + System.out.println("Odd: " + i);`, + }, + { + description: + "Should autocomplete a Markdown heading and preserve formatting", + filename: "test.md", + input: `# My Document + +## Introduction +This is a sample document for testing. + +## <|fim|> +### Conclusion +Thank you for reading. +`, + llmOutput: `Features +Here is a list of features: +- Feature 1 +- Feature 2 +`, + expectedCompletion: `Features +Here is a list of features: +- Feature 1 +- Feature 2`, + }, + { + description: "Should autocomplete a Java method within a class", + filename: "Calculator.java", + input: ` +public class Calculator { + private double result; + + public Calculator() { + this.result = 0.0; + } + + public void add(double number) { + result += number; +<|fim|>`, + llmOutput: ` + } + + public void subtract(double number) { + result -= number; + } +`, + expectedCompletion: ` + } + + public void subtract(double number) { + result -= number; + }`, + }, + { + description: "Should filter out consecutive, repeated YAML keys", + filename: "test.yaml", + input: ` + version: '3' + services: + db: + image: postgres + environment: + POSTGRES_USER: user + POSTGRES_PASSWORD: pass<|fim|> + `, + llmOutput: ` + POSTGRES_DB: mydb + POSTGRES_DB: mydb + `, + expectedCompletion: ` + POSTGRES_DB: mydb + `, + }, + { + description: "Should autocomplete a Markdown list with nested items", + filename: "test.md", + input: ` +- Item 1 +- Item 2 + - Subitem 1 + <|fim|> +- Item 3 +`, + llmOutput: ` - Subitem 2 + - Subitem 3 +`, + expectedCompletion: ` - Subitem 2 + - Subitem 3`, + }, +]; + +export const TEST_CASES_WITHOUT_DIFF: AutocompleteFileringTestInput[] = [ { description: "should pass", filename: "test.js", @@ -412,32 +585,6 @@ print(odd_squares) llmOutput: `x for x in squares if x % 2 != 0`, expectedCompletion: `x for x in squares if x % 2 != 0`, }, - { - description: "Should handle python multi-line string", - filename: "test.py", - input: `def create_greeting(name): - greeting = """Hello, """ + name + """! -Welcome to our community. We hope you have a great time here. -If you have any questions, feel free to reach out.""" - return greeting - -message = create_greeting("Alice") -print(message) - -multi_line_message = """<|fim|> -print(multi_line_message) -`, - llmOutput: `This is a multi-line message. -It continues across multiple lines, -which allows for easy reading and formatting. -""" -`, - expectedCompletion: `This is a multi-line message. -It continues across multiple lines, -which allows for easy reading and formatting. -""" -`, - }, { description: "Should autocomplete a simple Go function declaration", filename: "simpleFunction.go", @@ -511,19 +658,6 @@ func main() { expectedCompletion: ` }`, }, - { - description: - "Should autocomplete SQL query with subquery and alias in SELECT clause", - filename: "complex_query.sql", - input: `SELECT u.id, - u.name, - (SELECT COUNT(*) FROM orders o WHERE o.user_id = u.id) AS order_count - FROM users u - WHERE u.active = 1 - <|fim|>`, - llmOutput: ` AND EXISTS (SELECT 1 FROM transactions t WHERE t.user_id = u.id AND t.amount > 100)`, - expectedCompletion: ` AND EXISTS (SELECT 1 FROM transactions t WHERE t.user_id = u.id AND t.amount > 100)`, - }, { description: "Should autocomplete SQL query with nested functions and missing bracket", @@ -536,6 +670,19 @@ func main() { llmOutput: `8.5)`, expectedCompletion: `8.5)`, }, + { + description: + "Should autocomplete SQL query with subquery and alias in SELECT clause", + filename: "complex_query.sql", + input: `SELECT u.id, + u.name, + (SELECT COUNT(*) FROM orders o WHERE o.user_id = u.id) AS order_count + FROM users u + WHERE u.active = 1 + <|fim|>`, + llmOutput: ` AND EXISTS (SELECT 1 FROM transactions t WHERE t.user_id = u.id AND t.amount > 100)`, + expectedCompletion: ` AND EXISTS (SELECT 1 FROM transactions t WHERE t.user_id = u.id AND t.amount > 100)`, + }, { description: "Should autocomplete multi-line SQL query with CASE statements", @@ -637,57 +784,6 @@ squared_numbers = numbers.<|fim|> expectedCompletion: `map { |n| n ** 2 }`, filename: "array_methods.rb", }, - { - description: "Should autocomplete a Java method within a class", - filename: "Calculator.java", - input: ` -public class Calculator { - private double result; - - public Calculator() { - this.result = 0.0; - } - - public void add(double number) { - result += number; -<|fim|>`, - llmOutput: ` - } - - public void subtract(double number) { - result -= number; - } -`, - expectedCompletion: ` - } - - public void subtract(double number) { - result -= number; - } -`, - }, - { - description: "Should autocomplete Java when inside a block", - filename: "Main.java", - input: ` -public class Main { - public static void main(String[] args) { - for (int i = 0; i < 10; i++) { - if (i % 2 == 0) { - System.out.println("Even: " + i); - } else { -<|fim|> - } - } - } -}`, - llmOutput: ` - System.out.println("Odd: " + i); -`, - expectedCompletion: ` - System.out.println("Odd: " + i); -`, - }, { description: "Should autocomplete Java within a string", filename: "App.java", @@ -717,7 +813,6 @@ public class App { llmOutput: " int multiply(int a, int b);", expectedCompletion: " int multiply(int a, int b);", }, - { description: "Should autocomplete C++ for loop syntax", filename: "test.cpp", @@ -730,64 +825,6 @@ public class App { llmOutput: "i++", expectedCompletion: "i++", }, - { - description: "Should autocomplete a Markdown list with nested items", - filename: "test.md", - input: ` -- Item 1 -- Item 2 - - Subitem 1 - <|fim|> -- Item 3 -`, - llmOutput: ` - Subitem 2 - - Subitem 3 -`, - expectedCompletion: ` - Subitem 2 - - Subitem 3 -`, - }, - { - description: - "Should autocomplete a Markdown heading and preserve formatting", - filename: "test.md", - input: `# My Document - -## Introduction -This is a sample document for testing. - -## <|fim|> -### Conclusion -Thank you for reading. -`, - llmOutput: `Features -Here is a list of features: -- Feature 1 -- Feature 2 -`, - expectedCompletion: `Features -Here is a list of features: -- Feature 1 -- Feature 2 -`, - }, - { - description: "Should complete a Markdown code block", - filename: "test.md", - input: ` -Here is a sample JavaScript function: - -\`\`\`javascript -function sayHello() { - console.log("Hello, <|fim|> -} -\`\`\` -`, - llmOutput: `world!"); -`, - expectedCompletion: `world!"); -`, - }, { description: "Should autocomplete JSON object inside an array", filename: "data.json", @@ -986,28 +1023,6 @@ impl Calculator { println!("Cannot divide by zero."); } }`, - }, - { - description: "Should autocomplete Rust match arms", - filename: "main.rs", - input: ` -fn get_status_code_description(code: u16) -> &'static str { - match code { - 200 => "OK", - 404 => "Not Found", - 500 => "Internal Server Error", - <|fim|> - } -} -`, - llmOutput: `403 => "Forbidden", - 401 => "Unauthorized", - _ => "Unknown Status", -`, - expectedCompletion: `403 => "Forbidden", - 401 => "Unauthorized", - _ => "Unknown Status", -`, }, { description: "Should autocomplete Rust struct definition", @@ -1753,17 +1768,15 @@ let oddSquares = [<|fim|>]`, llmOutput: ` for x in squares do if x % 2 <> 0 then yield x ]`, expectedCompletion: ` for x in squares do if x % 2 <> 0 then yield x ]`, }, - { description: "Should complete an F# recursive function", filename: "recursiveFunctions.fs", input: `let rec factorial n = if n <= 1 then 1 else n <|fim|> factorial (n - 1)`, - llmOutput: ` * `, - expectedCompletion: ` * `, + llmOutput: `*`, + expectedCompletion: `*`, }, - { description: "Should complete F# member method inside a class type", filename: "bankAccount.fs", diff --git a/core/autocomplete/postprocessing/index.ts b/core/autocomplete/postprocessing/index.ts index 001642573..127874d68 100644 --- a/core/autocomplete/postprocessing/index.ts +++ b/core/autocomplete/postprocessing/index.ts @@ -73,9 +73,6 @@ export function postprocessCompletion({ return undefined; } - // Remove trailing whitespace - completion = completion.trimEnd(); - if (llm.model.includes("codestral")) { // Codestral sometimes starts with an extra space if (completion[0] === " " && completion[1] !== " ") { @@ -85,19 +82,23 @@ export function postprocessCompletion({ } } - // If completion starts with multiple whitespaces, but the cursor is at the end of the line - // then it should probably be on a new line - if ( - (completion.startsWith(" ") || completion.startsWith("\t")) && - !prefix.endsWith("\n") && - (suffix.startsWith("\n") || suffix.trim().length === 0) - ) { - // completion = "\n" + completion; - return undefined; - } + // // If completion starts with multiple whitespaces, but the cursor is at the end of the line + // // then it should probably be on a new line + // if ( + // (completion.startsWith(" ") || completion.startsWith("\t")) && + // !prefix.endsWith("\n") && + // (suffix.startsWith("\n") || suffix.trim().length === 0) + // ) { + // completion = "\n" + completion; + // } // If prefix ends with space and so does completion, then remove the space from completion - if (prefix.endsWith(" ") && completion.startsWith(" ")) { + if ( + prefix.split("\n").pop()?.trim() !== "" && + prefix.endsWith(" ") && + completion.startsWith(" ") + ) { + const test = prefix.split("\n").pop()?.trim() !== ""; completion = completion.slice(1); } diff --git a/core/autocomplete/prefiltering/index.ts b/core/autocomplete/prefiltering/index.ts index c844696ac..a7343817d 100644 --- a/core/autocomplete/prefiltering/index.ts +++ b/core/autocomplete/prefiltering/index.ts @@ -67,12 +67,12 @@ export async function shouldPrefilter( return true; } - if ( - helper.options.transform && - (await shouldLanguageSpecificPrefilter(helper)) - ) { - return true; - } + // if ( + // helper.options.transform && + // (await shouldLanguageSpecificPrefilter(helper)) + // ) { + // return true; + // } return false; } diff --git a/core/util/ranges.ts b/core/util/ranges.ts index 345933f03..3fb5b609e 100644 --- a/core/util/ranges.ts +++ b/core/util/ranges.ts @@ -7,7 +7,7 @@ export function getRangeInString(content: string, range: Range): string { return ( lines[range.start.line]?.substring( range.start.character, - range.end.character + 1, + range.end.character, ) ?? "" ); } From 2593a4e3e619130ed214f20d5fa7e181ae76a297 Mon Sep 17 00:00:00 2001 From: Test Date: Tue, 5 Nov 2024 10:35:42 -0800 Subject: [PATCH 55/96] Update multifileEdit.ts --- core/commands/slash/multifileEdit.ts | 50 +++++++++++++++++++++++++--- 1 file changed, 45 insertions(+), 5 deletions(-) diff --git a/core/commands/slash/multifileEdit.ts b/core/commands/slash/multifileEdit.ts index d045e0a2f..797f27bf2 100644 --- a/core/commands/slash/multifileEdit.ts +++ b/core/commands/slash/multifileEdit.ts @@ -1,13 +1,43 @@ import { SlashCommand } from "../.."; +import { getFullyQualifiedPath } from "../../../extensions/vscode/src/util/util"; import { stripImages } from "../../llm/images"; const MultiFileEditSlashCommand: SlashCommand = { name: "multifile-edit", description: "Edit multiple files in the codebase at once", - run: async function* ({ llm, contextItems, input }) { - const filesToEditStr = contextItems.map((item) => item.content).join("\n"); + run: async function* ({ llm, contextItems, selectedCode, input, ide }) { + const selectedCodeStr = ( + await Promise.all( + selectedCode.map(async (item) => { + // Split the range string from the filename, e.g. `filename.ts (1-2) -> [filename.ts, (1-2)]` + const [filepath, rangeStr] = item.filepath.split(" "); + const fullPath = getFullyQualifiedPath(filepath); - const content = createPrompt(filesToEditStr, input); + if (!fullPath) { + return ""; + } + + const codeStr = await ide.readRangeInFile(fullPath, item.range); + + // Include the filepath so the model can map it correctly with codeblock outputs + return `\`\`\`${fullPath} ${rangeStr}\n${codeStr}\`\`\``; + }), + ) + ).join("\n"); + + const fileContextItemsStr = contextItems + .filter((item) => item.uri?.type === "file") + .map((item) => item.content) + .join("\n"); + + const filesToEditStr = fileContextItemsStr + "\n" + selectedCodeStr; + + const additionalContextStr = contextItems + .filter((item) => item.uri?.type !== "file") + .map((item) => `${item.description}: ${item.content}`) + .join("\n"); + + const content = createPrompt(filesToEditStr, additionalContextStr, input); for await (const chunk of llm.streamChat([{ role: "user", content }])) { yield stripImages(chunk.content); @@ -15,7 +45,11 @@ const MultiFileEditSlashCommand: SlashCommand = { }, }; -function createPrompt(filesToEditStr: string, input: string): string { +function createPrompt( + filesToEditStr: string, + additionalContextStr: string, + input: string, +): string { return ` You are an AI assistant designed to help software engineers make multi-file edits in their codebase. Your task is to generate the necessary code changes for multiple files based on the engineer's request. Follow these guidelines: @@ -54,12 +88,18 @@ Now, let's make the changes based on the engineer's request: ${input} -Here are the files to edit: +Here are the files to base your edits on: ${filesToEditStr} +And here is any additional context the engineer has provided: + + +${additionalContextStr} + + Please provide the multi-file edit details based on the engineer's request. `; } From 17081dfa77caa704489cca82ad5b92bd08379f80 Mon Sep 17 00:00:00 2001 From: Test Date: Tue, 5 Nov 2024 21:25:58 -0800 Subject: [PATCH 56/96] update `getFullyQualifiedPath` to use ide --- core/commands/slash/multifileEdit.ts | 3 ++- extensions/vscode/src/commands.ts | 14 ++++++++++---- extensions/vscode/src/extension/VsCodeMessenger.ts | 4 ++-- extensions/vscode/src/util/util.ts | 12 ++++-------- 4 files changed, 18 insertions(+), 15 deletions(-) diff --git a/core/commands/slash/multifileEdit.ts b/core/commands/slash/multifileEdit.ts index 797f27bf2..ffda6b703 100644 --- a/core/commands/slash/multifileEdit.ts +++ b/core/commands/slash/multifileEdit.ts @@ -1,5 +1,6 @@ import { SlashCommand } from "../.."; import { getFullyQualifiedPath } from "../../../extensions/vscode/src/util/util"; +import { VsCodeIde } from "../../../extensions/vscode/src/VsCodeIde"; import { stripImages } from "../../llm/images"; const MultiFileEditSlashCommand: SlashCommand = { @@ -11,7 +12,7 @@ const MultiFileEditSlashCommand: SlashCommand = { selectedCode.map(async (item) => { // Split the range string from the filename, e.g. `filename.ts (1-2) -> [filename.ts, (1-2)]` const [filepath, rangeStr] = item.filepath.split(" "); - const fullPath = getFullyQualifiedPath(filepath); + const fullPath = getFullyQualifiedPath(ide as VsCodeIde, filepath); if (!fullPath) { return ""; diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index bb020c302..41d047730 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -34,6 +34,7 @@ import { Battery } from "./util/battery"; import { getFullyQualifiedPath } from "./util/util"; import { uriFromFilePath } from "./util/vscode"; import type { VsCodeWebviewProtocol } from "./webviewProtocol"; +import { VsCodeIde } from "./VsCodeIde"; let fullScreenPanel: vscode.WebviewPanel | undefined; @@ -188,7 +189,7 @@ function focusGUI() { // Copy everything over from extension.ts const commandsMap: ( - ide: IDE, + ide: VsCodeIde, extensionContext: vscode.ExtensionContext, sidebar: ContinueGUIWebviewViewProvider, configHandler: ConfigHandler, @@ -261,8 +262,10 @@ const commandsMap: ( if (fullPath instanceof vscode.Uri) { fullPath = fullPath.fsPath; + } else if (fullPath) { + fullPath = getFullyQualifiedPath(ide, fullPath); } else { - fullPath = getFullyQualifiedPath(fullPath); + console.warn(`Unable to resolve filepath: ${newFilepath}`); } verticalDiffManager.clearForFilepath(fullPath, true); @@ -278,8 +281,11 @@ const commandsMap: ( if (fullPath instanceof vscode.Uri) { fullPath = fullPath.fsPath; + } else if (fullPath) { + fullPath = getFullyQualifiedPath(ide, fullPath); } else { - fullPath = getFullyQualifiedPath(fullPath); + console.warn(`Unable to resolve filepath: ${newFilepath}`); + return; } verticalDiffManager.clearForFilepath(fullPath, false); @@ -807,7 +813,7 @@ const commandsMap: ( export function registerAllCommands( context: vscode.ExtensionContext, - ide: IDE, + ide: VsCodeIde, extensionContext: vscode.ExtensionContext, sidebar: ContinueGUIWebviewViewProvider, configHandler: ConfigHandler, diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index 954f30349..d7ed63a5f 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -86,7 +86,7 @@ export class VsCodeMessenger { ) { /** WEBVIEW ONLY LISTENERS **/ this.onWebview("showFile", (msg) => { - const fullPath = getFullyQualifiedPath(msg.data.filepath); + const fullPath = getFullyQualifiedPath(this.ide, msg.data.filepath); if (fullPath) { this.ide.openFile(fullPath); @@ -159,7 +159,7 @@ export class VsCodeMessenger { }); this.onWebview("applyToFile", async ({ data }) => { - const fullPath = getFullyQualifiedPath(data.filepath); + const fullPath = getFullyQualifiedPath(ide, data.filepath); if (!fullPath) { return; diff --git a/extensions/vscode/src/util/util.ts b/extensions/vscode/src/util/util.ts index 4ac832455..9b5c11bfe 100644 --- a/extensions/vscode/src/util/util.ts +++ b/extensions/vscode/src/util/util.ts @@ -1,6 +1,7 @@ const os = require("node:os"); import path from "node:path"; import * as vscode from "vscode"; +import { VsCodeIde } from "../VsCodeIde"; function charIsEscapedAtIndex(index: number, str: string): boolean { if (index === 0) { @@ -123,17 +124,12 @@ export function getExtensionVersion(): string { return extension?.packageJSON.version || "0.1.0"; } -export function getFullyQualifiedPath(filepath?: string) { - if (!filepath) return; - if (path.isAbsolute(filepath)) return filepath; +export function getFullyQualifiedPath(ide: VsCodeIde, filepath: string) { + if (ide.ideUtils.path.isAbsolute(filepath)) return filepath; const workspaceFolders = vscode.workspace.workspaceFolders; if (workspaceFolders && workspaceFolders.length > 0) { - return path.join(workspaceFolders[0].uri.fsPath, filepath); - } else { - vscode.window.showErrorMessage( - "Unable to resolve filepath: no workspace folder found", - ); + return ide.ideUtils.path.join(workspaceFolders[0].uri.fsPath, filepath); } } From aa6cebe9f0c96d36d208c9653be1ae1ace3acbce Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Wed, 6 Nov 2024 13:51:07 +0700 Subject: [PATCH 57/96] improv: transform autocomplete edge cases --- .../constants/AutocompleteLanguageInfo.ts | 27 +++- .../StreamTransformPipeline.ts | 20 +-- .../filtering/streamTransforms/lineStream.ts | 8 ++ .../CODESTRAL_TYPESCRIPT.txt | 70 ---------- .../test/NEGATIVE_TEST_CASES/QWEN_JSON.txt | 60 ++++++++ .../NEGATIVE_TEST_CASES/QWEN_TYPESCRIPT.txt | 128 ++++++++++++++++++ .../NEGATIVE_TEST_CASES/STARCODER_JSON.txt | 20 +++ .../NEGATIVE_TEST_CASES/STARCODER_PYTHON.TXT | 29 ++++ .../NEGATIVE_TEST_CASES/STARCODER_RUBY.TXT | 41 ++++++ .../NEGATIVE_TEST_CASES/STARCODER_RUST.TXT | 73 ++++++++++ .../STARCODER_TYPESCRIPT.txt | 53 -------- core/autocomplete/filtering/test/testCases.ts | 127 ++++++++++++----- manual-testing-sandbox/AdvancedPage.tsx | 64 +++++++++ manual-testing-sandbox/Button.tsx | 15 -- manual-testing-sandbox/data.json | 83 +++++++++++- manual-testing-sandbox/test.html | 5 + 16 files changed, 636 insertions(+), 187 deletions(-) delete mode 100644 core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/CODESTRAL_TYPESCRIPT.txt create mode 100644 core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/QWEN_JSON.txt create mode 100644 core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/QWEN_TYPESCRIPT.txt create mode 100644 core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/STARCODER_JSON.txt create mode 100644 core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/STARCODER_PYTHON.TXT create mode 100644 core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/STARCODER_RUBY.TXT create mode 100644 core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/STARCODER_RUST.TXT delete mode 100644 core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/STARCODER_TYPESCRIPT.txt create mode 100644 manual-testing-sandbox/AdvancedPage.tsx delete mode 100644 manual-testing-sandbox/Button.tsx diff --git a/core/autocomplete/constants/AutocompleteLanguageInfo.ts b/core/autocomplete/constants/AutocompleteLanguageInfo.ts index 88ba93aa9..18bbf2ff9 100644 --- a/core/autocomplete/constants/AutocompleteLanguageInfo.ts +++ b/core/autocomplete/constants/AutocompleteLanguageInfo.ts @@ -1,4 +1,8 @@ -import { LineFilter } from "../filtering/streamTransforms/lineStream"; +import { BracketMatchingService } from "../filtering/BracketMatchingService"; +import { + CharacterFilter, + LineFilter, +} from "../filtering/streamTransforms/lineStream"; export interface AutocompleteLanguageInfo { name: string; @@ -7,6 +11,7 @@ export interface AutocompleteLanguageInfo { endOfLine: string[]; stopWords?: string[]; lineFilters?: LineFilter[]; + charFilters?: CharacterFilter[]; useMultiline?: (args: { prefix: string; suffix: string }) => boolean; } @@ -277,6 +282,25 @@ export const YAML: AutocompleteLanguageInfo = { ], }; +export const Json: AutocompleteLanguageInfo = { + name: "JSON", + topLevelKeywords: [], + singleLineComment: "//", + endOfLine: [",", "}", "]"], + charFilters: [ + function matchBrackets({ chars, prefix, suffix, filepath, multiline }) { + const bracketMatchingService = new BracketMatchingService(); + return bracketMatchingService.stopOnUnmatchedClosingBracket( + chars, + prefix, + suffix, + filepath, + multiline, + ); + }, + ], +}; + export const Markdown: AutocompleteLanguageInfo = { name: "Markdown", topLevelKeywords: [], @@ -306,6 +330,7 @@ export const LANGUAGES: { [extension: string]: AutocompleteLanguageInfo } = { ts: Typescript, js: Typescript, tsx: Typescript, + json: Json, jsx: Typescript, ipynb: Python, py: Python, diff --git a/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts b/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts index 6b3262192..08a318a59 100644 --- a/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts +++ b/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts @@ -1,6 +1,5 @@ import { streamLines } from "../../../diff/util"; import { HelperVars } from "../../util/HelperVars"; -import { BracketMatchingService } from "../BracketMatchingService"; import { stopAtStopTokens } from "./charStream"; import { avoidEmptyComments, @@ -14,8 +13,6 @@ import { } from "./lineStream"; export class StreamTransformPipeline { - private bracketMatchingService = new BracketMatchingService(); - async *transform( generator: AsyncGenerator, prefix: string, @@ -28,13 +25,16 @@ export class StreamTransformPipeline { let charGenerator = generator; charGenerator = stopAtStopTokens(generator, stopTokens); - // charGenerator = this.bracketMatchingService.stopOnUnmatchedClosingBracket( - // charGenerator, - // prefix, - // suffix, - // helper.filepath, - // multiline, - // ); + for (const charFilter of helper.lang.charFilters ?? []) { + debugger; + charGenerator = charFilter({ + chars: charGenerator, + prefix, + suffix, + filepath: helper.filepath, + multiline, + }); + } let lineGenerator = streamLines(charGenerator); diff --git a/core/autocomplete/filtering/streamTransforms/lineStream.ts b/core/autocomplete/filtering/streamTransforms/lineStream.ts index e305062cf..0f49cea55 100644 --- a/core/autocomplete/filtering/streamTransforms/lineStream.ts +++ b/core/autocomplete/filtering/streamTransforms/lineStream.ts @@ -7,6 +7,14 @@ export type LineFilter = (args: { fullStop: () => void; }) => LineStream; +export type CharacterFilter = (args: { + chars: AsyncGenerator; + prefix: string; + suffix: string; + filepath: string; + multiline: boolean; +}) => AsyncGenerator; + function isBracketEnding(line: string): boolean { return line .trim() diff --git a/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/CODESTRAL_TYPESCRIPT.txt b/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/CODESTRAL_TYPESCRIPT.txt deleted file mode 100644 index 7ecc7003d..000000000 --- a/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/CODESTRAL_TYPESCRIPT.txt +++ /dev/null @@ -1,70 +0,0 @@ - -##### Prompt ##### -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; - } -} -========================================================================== -========================================================================== -Completion: - - getResult() { - return this.result; - } - - reset() { - this.result = 0; - return this; - } -} - -// Example usage: -const calculator = new Calculator(); -calculator.add(5).subtract(3).multiply(2).divide(4); -console.log(calculator.getResult()); // Output: 2 - -calculator.reset().add(10).divide(2); -console.log(calculator.getResult()); // Output: 5 - -calculator.reset().add(8).multiply(0); -console.log(calculator.getResult()); // Output: 0 - -calculator.reset().add(6).divide(0); // Throws an error: Cannot divide by zero \ No newline at end of file diff --git a/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/QWEN_JSON.txt b/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/QWEN_JSON.txt new file mode 100644 index 000000000..ff0ba3cb3 --- /dev/null +++ b/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/QWEN_JSON.txt @@ -0,0 +1,60 @@ +##### Prompt ##### +{ + "active": true, + "department": "Product Development", + "location": { + "country": "USA", + "state": "California", + "city": "San BERNARDINO", + "coordinates": { + + } + }, + "employees": [ + { + "name": "John Doe", + "age": 30, + "position": "Developer", + "skills": ["JavaScript", "React", "Node.js"], + "remote": false, + "salary": { + "currency": "USD", + "amount": 95000 + } + }, + { + "name": "Jane Smith", + "age": 25, + "position": "Designer", + "skills": ["Photoshop", "Illustrator"], + "remote": true, + "salary": { + "currency": "USD", + "amount": 70000 + } + }, + { + "name": "Emily Johnson", + "age": 35, + "position": "Manager", + "teamSize": 8, + "remote": true, + "skills": ["Leadership", "Project Management"],========================================================================== +========================================================================== +Completion: + + "latitude": 34.10834, + "longitude": -117.28977 + } + }, + "employeeCount": 2, + "averageAge": 30, + "remoteFriendly": true, + "salaryRange": { + "min": 70000, + "max": 95000, + "currency": "USD" + }, + "skills": { + "required": ["JavaScript", "React", "Node.js", "Leadership", "Project Management"], + "optional": ["Photoshop", "Illustrator"] \ No newline at end of file diff --git a/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/QWEN_TYPESCRIPT.txt b/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/QWEN_TYPESCRIPT.txt new file mode 100644 index 000000000..241d141f2 --- /dev/null +++ b/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/QWEN_TYPESCRIPT.txt @@ -0,0 +1,128 @@ +##### Prompt ##### + }`, + }, + { + description: "Should autocomplete Vue computed property", + filename: "UserComponent.vue", + input: ` + + +`, + llmOutput: `() { + return this.firstName + ' ' + this.lastName; + }`, + expectedCompletion: `() { + return this.firstName + ' ' + this.lastName; + }`, + }, + { + description: "Should autocomplete Vue method using props", + filename: "TodoItem.vue", + input: ` + + +`, + llmOutput: `this.completed`, + expectedCompletion: `this.completed`, + }, + { + description: "Should autocomplete Svelte reactive statement", + filename: "Counter.svelte", + input: ` + + + +`, + llmOutput: `doubledCount = count * 2`, + expectedCompletion: `doubledCount = count * 2`, + }, + + { + description: "Should autocomplete Svelte component inside HTML", + filename: "NestedComponent.svelte", + input: ` + + +
+

Hello Svelte

+ /> +
+`, + llmOutput: `name="World"`, + expectedCompletion: `name="World"`, + }, + + { + description: "Should handle autocomplete in Svelte each block", + filename: "List.svelte", + input: ` + + +
    + {#each items as item} +
  • {item}
  • + {/each<|fim|> +
+`, + llmOutput: `}`, + expectedCompletion: `}`, + }, + +]; +========================================================================== +========================================================================== +Completion: + + + +export default { + components: { + ChildComponent, + }, \ No newline at end of file diff --git a/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/STARCODER_JSON.txt b/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/STARCODER_JSON.txt new file mode 100644 index 000000000..a50bd2fb4 --- /dev/null +++ b/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/STARCODER_JSON.txt @@ -0,0 +1,20 @@ +##### Prompt ##### +{ + "employees": [ + { "name": "John Doe", "age": 30, "position": "Developer" }, + { "name": "Jane Smith", "age": 25, "position": "Designer" }, + { "name": "Emily Johnson", "age": 35, "position": "Manager" } + ], + "active": true +} +========================================================================== +========================================================================== +Completion: + + +} + +{ + "employees": [ + { "name": "John Doe", "age": 30 }, + { "name": "Jane Smith", "age": 25 } \ No newline at end of file diff --git a/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/STARCODER_PYTHON.TXT b/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/STARCODER_PYTHON.TXT new file mode 100644 index 000000000..c4aaf43ec --- /dev/null +++ b/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/STARCODER_PYTHON.TXT @@ -0,0 +1,29 @@ +##### Prompt ##### +class Calculator: + def __init__(self): + self.result = 0 + + def add(self, number): + self.result += number + return self + + def divid + + def subtract(self, number): + self.result -= number + return self + + def reset(self): + self.result = 0 + return self + + def get_result(self): + return self.result + + +========================================================================== +========================================================================== +Completion: + +self.result /= number + return self \ No newline at end of file diff --git a/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/STARCODER_RUBY.TXT b/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/STARCODER_RUBY.TXT new file mode 100644 index 000000000..df8c2011f --- /dev/null +++ b/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/STARCODER_RUBY.TXT @@ -0,0 +1,41 @@ +##### Prompt ##### +class Calculator + attr_accessor :result + + def initialize + @result = 0 + end + + def add(number) + @result += number + self + end + + def subtract(number) + @result -= number + self + end + + def power(ne + + def get_result + @result + end + + def reset + @result = 0 + self + end +end + +calc = Calculator.new +calc.add(5).subtract(3) +puts "Result: #{calc.get_result}" +========================================================================== +========================================================================== +Completion: + + + @result ** number + self + end \ No newline at end of file diff --git a/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/STARCODER_RUST.TXT b/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/STARCODER_RUST.TXT new file mode 100644 index 000000000..582ae5f36 --- /dev/null +++ b/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/STARCODER_RUST.TXT @@ -0,0 +1,73 @@ +##### Prompt ##### +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() +} +========================================================================== +========================================================================== +Completion: + + => { + println!("Invalid operator. Please try again."); + continue; + } + }; + + println!("Result: {}", result); + } + + println!("Goodbye!"); +} + + +fn main2() { + println!("Welcome to the Calculator!"); + + loop { + println!("Please enter an operator (+, -, *, /) or 'q' to quit:"); + let operator = read_input(); + + if operator == "q" { + break; + } + + match operator.as_str() { + "+" | "-" | "*" | "/" => (), \ No newline at end of file diff --git a/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/STARCODER_TYPESCRIPT.txt b/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/STARCODER_TYPESCRIPT.txt deleted file mode 100644 index b2505a0bb..000000000 --- a/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/STARCODER_TYPESCRIPT.txt +++ /dev/null @@ -1,53 +0,0 @@ -##### Prompt ##### -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; - } -} -========================================================================== -========================================================================== -Completion: - - this.result /= number; - return this; - } -} - -module.exports = Calculator; - ------------------------------------------------------------------------- diff --git a/core/autocomplete/filtering/test/testCases.ts b/core/autocomplete/filtering/test/testCases.ts index 1f0397363..683dbc7bc 100644 --- a/core/autocomplete/filtering/test/testCases.ts +++ b/core/autocomplete/filtering/test/testCases.ts @@ -172,6 +172,69 @@ public class Calculator { expectedCompletion: ` - Subitem 2 - Subitem 3`, }, + { + description: "Should enforce bracket matching in JSON files", + filename: "test.json", + input: `{ + "active": true, + "department": "Product Development", + "location": { + "country": "USA", + "state": "California", + "city": "San BERNARDINO", + "coordinates": { + + } + }, + "employees": [ + { + "name": "John Doe", + "age": 30, + "position": "Developer", + "skills": ["JavaScript", "React", "Node.js"], + "remote": false, + "salary": { + "currency": "USD", + "amount": 95000 + } + }, + { + "name": "Jane Smith", + "age": 25, + "position": "Designer", + "skills": ["Photoshop", "Illustrator"], + "remote": true, + "salary": { + "currency": "USD", + "amount": 70000 + } + }, + { + "name": "Emily Johnson", + "age": 35, + "position": "Manager", + "teamSize": 8, + "remote": true, + "skills": ["Leadership", "Project Management"],`, + llmOutput: `"latitude": 34.10834, + "longitude": -117.28977 + } + }, + "employeeCount": 2, + "averageAge": 30, + "remoteFriendly": true, + "salaryRange": { + "min": 70000, + "max": 95000, + "currency": "USD" + }, + "skills": { + "required": ["JavaScript", "React", "Node.js", "Leadership", "Project Management"], + "optional": ["Photoshop", "Illustrator"]`, + expectedCompletion: `"latitude": 34.10834, + "longitude": -117.28977 + `, + }, ]; export const TEST_CASES_WITHOUT_DIFF: AutocompleteFileringTestInput[] = [ @@ -670,6 +733,36 @@ func main() { llmOutput: `8.5)`, expectedCompletion: `8.5)`, }, + { + description: + "Should autocomplete SQL script with employee and product tables", + filename: "database.sql", + input: ` + CREATE TABLE employees ( + id INT AUTO_INCREMENT PRIMARY KEY, + name VARCHAR(100) NOT NULL, + age INT NOT NULL, + position VARCHAR(100) + ); + + CREATE TABLE products ( + id INT AUTO_INCREMENT PRIMARY KEY, + name VARCHAR(100), + price DECIMAL(8,2) NOT NULL '0.00', + quantity INT NOT NULL DEFAULT '0' + ); + + INSERT INTO employees (name, age, position) VALUES ('John Doe', 30, 'Developer'); + INSERT INTO products (name, price, quantity) VALUES ('Apple', '1.99', '47'); + + SELECT * FROM products ORDER BY name DESC LIMIT 3; + SELECT * FROM products WHERE price > '0'; + SELECT * FROM products WHERE quantity > '100'; + SELECT * FROM employees WHERE age > 25; + `, + llmOutput: " DEFAULT", + expectedCompletion: " DEFAULT", + }, { description: "Should autocomplete SQL query with subquery and alias in SELECT clause", @@ -838,40 +931,6 @@ public class App { llmOutput: `, { "id": 3, "name": "Charlie" }`, expectedCompletion: `, { "id": 3, "name": "Charlie" }`, }, - { - description: "Should autocomplete nested JSON objects", - filename: "config.json", - input: `{ - "server": { - "host": "localhost", - "port": 8080, - "features": { - "enableLogging": true, - "maxConnections": 100 - <|fim|> - } -}`, - llmOutput: `, - "timeout": 5000 - }`, - expectedCompletion: `, - "timeout": 5000 - }`, - }, - { - description: "Should autocomplete JSON object with missing bracket", - filename: "settings.json", - input: `{ - "theme": "dark", - "language": "en"<|fim|> - `, - llmOutput: `, - "notifications": true - }`, - expectedCompletion: `, - "notifications": true - }`, - }, { description: "Should autocomplete within a CSV record", filename: "test.csv", diff --git a/manual-testing-sandbox/AdvancedPage.tsx b/manual-testing-sandbox/AdvancedPage.tsx new file mode 100644 index 000000000..6d17ef463 --- /dev/null +++ b/manual-testing-sandbox/AdvancedPage.tsx @@ -0,0 +1,64 @@ +import React, { useState } from "react"; + +const AdvancedPage = () => { + const [isDarkMode, setIsDarkMode] = useState(false); + const [counter, setCounter] = useState(0); + + const toggleDarkMode = () => { + setIsDarkMode((prevMode) => !prevMode); + }; + + return ( +
+
+

Welcome to the Advanced Page

+ +
+ +
+
+

+ Counter: {counter} +

+ +
+ +
+

Some other interactive elements:

+ +
+ +
+
+
+ +
+

+ © 2023 Advanced Page. All rights reserved. +

+
+
+ ); +}; + +export default AdvancedPage; diff --git a/manual-testing-sandbox/Button.tsx b/manual-testing-sandbox/Button.tsx deleted file mode 100644 index 4d6f8f91b..000000000 --- a/manual-testing-sandbox/Button.tsx +++ /dev/null @@ -1,15 +0,0 @@ -import React from "react"; - -export const Button = ({ - onClick, - children, -}: { - children: React.ReactNode; - onClick: () => void; -}) => { - return ( - - ); -}; diff --git a/manual-testing-sandbox/data.json b/manual-testing-sandbox/data.json index 7a187514a..6003f4bc2 100644 --- a/manual-testing-sandbox/data.json +++ b/manual-testing-sandbox/data.json @@ -1,8 +1,83 @@ { + "active": true, + "department": "Product Development", + "location": { + "country": "USA", + "state": "California", + "city": "San Francisco", + "coordinates": { + "latitude": 37.7749, + "longitude": -122.4194 + } + }, "employees": [ - { "name": "John Doe", "age": 30, "position": "Developer" }, - { "name": "Jane Smith", "age": 25, "position": "Designer" }, - { "name": "Emily Johnson", "age": 35, "position": "Manager" } + { + "name": "John Doe", + "age": 30, + "position": "Developer", + "skills": ["JavaScript", "React", "Node.js"], + "remote": false, + "salary": { + "currency": "USD", + "amount": 95000 + } + }, + { + "name": "Jane Smith", + "age": 25, + "position": "Designer", + "skills": ["Photoshop", "Illustrator"], + "remote": true, + "salary": { + "currency": "USD", + "amount": 70000 + } + }, + { + "name": "Emily Johnson", + "age": 35, + "position": "Manager", + "teamSize": 8, + "remote": true, + "skills": ["Leadership", "Project Management"], + "salary": { + "currency": "USD", + "amount": 120000 + }, + "contact": { + "email": "emily.johnson@company.com", + "phone": "+1-202-555-0163" + } + } ], - "active": true + "projects": [ + { + "name": "Project Alpha", + "deadline": "2023-12-31", + "budget": 150000, + "teamMembers": ["John Doe", "Jane Smith"] + }, + { + "name": "Project Beta", + "deadline": "2024-06-30", + "budget": 200000, + "teamMembers": ["Emily Johnson"] + } + ], + "companyStats": { + "founded": 2010, + "annualRevenue": 2500000, + "clients": [ + { + "name": "Client A", + "industry": "Technology", + "engagements": ["Consulting", "Development"] + }, + { + "name": "Client B", + "industry": "Finance", + "engagements": ["Design"] + } + ] + } } diff --git a/manual-testing-sandbox/test.html b/manual-testing-sandbox/test.html index 6c19f414b..8ed2c4792 100644 --- a/manual-testing-sandbox/test.html +++ b/manual-testing-sandbox/test.html @@ -19,6 +19,11 @@

This is a sample paragraph.

+
    +
  1. Item 1
  2. +
  3. Item 2
  4. +
  5. Item 3
  6. +
From f60009c2ea7c1c1a980152e5aa3cda17c3f6e64d Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Wed, 6 Nov 2024 20:34:53 +0700 Subject: [PATCH 58/96] fix: broken imports --- extensions/vscode/src/autocomplete/lsp.ts | 2 +- extensions/vscode/src/commands.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/extensions/vscode/src/autocomplete/lsp.ts b/extensions/vscode/src/autocomplete/lsp.ts index c3382dd99..41ae1d973 100644 --- a/extensions/vscode/src/autocomplete/lsp.ts +++ b/extensions/vscode/src/autocomplete/lsp.ts @@ -1,5 +1,5 @@ import type { IDE, Range, RangeInFile } from "core"; -import { GetLspDefinitionsFunction } from "core/autocomplete/completionProvider"; +import { GetLspDefinitionsFunction } from "core/autocomplete/CompletionProvider"; import { AutocompleteLanguageInfo } from "core/autocomplete/constants/AutocompleteLanguageInfo"; import { AutocompleteSnippet } from "core/autocomplete/context/ranking"; import { getAst, getTreePathAtCursor } from "core/autocomplete/util/ast"; diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index bb020c302..06601187e 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -1,6 +1,6 @@ /* eslint-disable @typescript-eslint/naming-convention */ import { ContextMenuConfig, IDE } from "core"; -import { CompletionProvider } from "core/autocomplete/completionProvider"; +import { CompletionProvider } from "core/autocomplete/CompletionProvider"; import { RangeInFileWithContents } from "core/commands/util"; import { ConfigHandler } from "core/config/ConfigHandler"; import { getModelByRole } from "core/config/util"; From f9325b36baf4f2d1fbace6fc1133e8dae7c24176 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Wed, 6 Nov 2024 09:05:56 -0800 Subject: [PATCH 59/96] hideGUI command and first take on cmd L and cmd shift L --- gui/src/components/mainInput/TipTapEditor.tsx | 103 +++++++++++------- 1 file changed, 65 insertions(+), 38 deletions(-) diff --git a/gui/src/components/mainInput/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor.tsx index f801aa348..55ff9db39 100644 --- a/gui/src/components/mainInput/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor.tsx @@ -245,8 +245,8 @@ function TipTapEditor(props: TipTapEditorProps) { const timer = setTimeout(() => { setHasDefaultModel( !!defaultModel && - defaultModel.apiKey !== undefined && - defaultModel.apiKey !== "", + defaultModel.apiKey !== undefined && + defaultModel.apiKey !== "", ); }, 3500); @@ -311,6 +311,10 @@ function TipTapEditor(props: TipTapEditorProps) { : "Ask a follow-up"; } + const hideGUI = useCallback(() => { + ideMessenger.post("hideGUI", undefined); + }, [ideMessenger]); + const editor: Editor = useEditor({ extensions: [ Document, @@ -397,6 +401,29 @@ function TipTapEditor(props: TipTapEditorProps) { return true; } }, + "Mod-L": () => { + if (!editorFocusedRef.current) { + if (historyLength === 0) { + hideGUI(); + } else { + saveSession(); + + setTimeout(() => { + editor?.commands.blur(); + editor?.commands.focus("end"); + }, 20); + } + return true; + } + return false; + }, + "Mod-Shift-L": () => { + if (!editorFocusedRef.current) { + hideGUI(); + return true; + } + return false; + }, "Shift-Enter": () => this.editor.commands.first(({ commands }) => [ () => commands.newlineInCode(), @@ -449,38 +476,38 @@ function TipTapEditor(props: TipTapEditorProps) { Text, props.availableContextProviders.length ? Mention.configure({ - HTMLAttributes: { - class: "mention", - }, - suggestion: getContextProviderDropdownOptions( - availableContextProvidersRef, - getSubmenuContextItemsRef, - enterSubmenu, - onClose, - onOpen, - inSubmenuRef, - ideMessenger, - ), - renderHTML: (props) => { - return `@${props.node.attrs.label || props.node.attrs.id}`; - }, - }) + HTMLAttributes: { + class: "mention", + }, + suggestion: getContextProviderDropdownOptions( + availableContextProvidersRef, + getSubmenuContextItemsRef, + enterSubmenu, + onClose, + onOpen, + inSubmenuRef, + ideMessenger, + ), + renderHTML: (props) => { + return `@${props.node.attrs.label || props.node.attrs.id}`; + }, + }) : undefined, props.availableSlashCommands.length ? SlashCommand.configure({ - HTMLAttributes: { - class: "mention", - }, - suggestion: getSlashCommandDropdownOptions( - availableSlashCommandsRef, - onClose, - onOpen, - ideMessenger, - ), - renderText: (props) => { - return props.node.attrs.label; - }, - }) + HTMLAttributes: { + class: "mention", + }, + suggestion: getSlashCommandDropdownOptions( + availableSlashCommandsRef, + onClose, + onOpen, + ideMessenger, + ), + renderText: (props) => { + return props.node.attrs.label; + }, + }) : undefined, CodeBlockExtension, ], @@ -573,6 +600,7 @@ function TipTapEditor(props: TipTapEditorProps) { if (isMetaEquivalentKeyPressed(e)) { const { key, code } = e; + const isWebEnv = isWebEnvironment(); const text = editor.state.doc.textBetween( editor.state.selection.from, @@ -705,7 +733,7 @@ function TipTapEditor(props: TipTapEditorProps) { return; } if (historyLength > 0) { - saveSession(); + await saveSession(); } setTimeout(() => { editor?.commands.blur(); @@ -734,12 +762,12 @@ function TipTapEditor(props: TipTapEditorProps) { if (!props.isMainInput) { return; } - saveSession(); + await saveSession(); setTimeout(() => { editor?.commands.focus("end"); }, 20); }, - [editor, props.isMainInput], + [editor, props.isMainInput, saveSession], ); useWebviewListener( @@ -756,9 +784,8 @@ function TipTapEditor(props: TipTapEditorProps) { rif.filepath, await ideMessenger.ide.getWorkspaceDirs(), ); - const rangeStr = `(${rif.range.start.line + 1}-${ - rif.range.end.line + 1 - })`; + const rangeStr = `(${rif.range.start.line + 1}-${rif.range.end.line + 1 + })`; const item: ContextItemWithId = { content: rif.contents, name: `${basename} ${rangeStr}`, @@ -881,7 +908,7 @@ function TipTapEditor(props: TipTapEditorProps) { return ( { From 9f1ea9a04c1de6d4088ec605ed791e8a1f9e65cd Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Wed, 6 Nov 2024 09:06:36 -0800 Subject: [PATCH 60/96] hide GUI and cmd L first take p2 --- core/protocol/ide.ts | 1 + core/util/messageIde.ts | 6 +- extensions/vscode/src/commands.ts | 1122 ++++++++--------- .../vscode/src/extension/VsCodeMessenger.ts | 3 + 4 files changed, 564 insertions(+), 568 deletions(-) diff --git a/core/protocol/ide.ts b/core/protocol/ide.ts index eda6bebfb..6a9f177d0 100644 --- a/core/protocol/ide.ts +++ b/core/protocol/ide.ts @@ -89,6 +89,7 @@ export type ToIdeFromWebviewOrCoreProtocol = { ]; logoutOfControlPlane: [undefined, void]; pathSep: [undefined, string]; + hideGUI: [undefined, void]; }; export type ToWebviewOrCoreFromIdeProtocol = { diff --git a/core/util/messageIde.ts b/core/util/messageIde.ts index 0ed9f63d2..15ecc019f 100644 --- a/core/util/messageIde.ts +++ b/core/util/messageIde.ts @@ -27,7 +27,7 @@ export class MessageIde implements IDE { messageType: T, callback: (data: FromIdeProtocol[T][0]) => FromIdeProtocol[T][1], ) => void, - ) {} + ) { } pathSep(): Promise { return this.request("pathSep", undefined); @@ -200,4 +200,8 @@ export class MessageIde implements IDE { async getBranch(dir: string): Promise { return this.request("getBranch", { dir }); } + + async hideGUI(): Promise { + await this.request("hideGUI", undefined); + } } diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index bb020c302..8dd057445 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -212,598 +212,586 @@ const commandsMap: ( core, editDecorationManager, ) => { - /** - * Streams an inline edit to the vertical diff manager. - * - * This function retrieves the configuration, determines the appropriate model title, - * increments the FTC count, and then streams an edit to the - * vertical diff manager. - * - * @param promptName - The key for the prompt in the context menu configuration. - * @param fallbackPrompt - The prompt to use if the configured prompt is not available. - * @param [onlyOneInsertion] - Optional. If true, only one insertion will be made. - * @param [range] - Optional. The range to edit if provided. - * @returns - */ - async function streamInlineEdit( - promptName: keyof ContextMenuConfig, - fallbackPrompt: string, - onlyOneInsertion?: boolean, - range?: vscode.Range, - ) { - const config = await configHandler.loadConfig(); + /** + * Streams an inline edit to the vertical diff manager. + * + * This function retrieves the configuration, determines the appropriate model title, + * increments the FTC count, and then streams an edit to the + * vertical diff manager. + * + * @param promptName - The key for the prompt in the context menu configuration. + * @param fallbackPrompt - The prompt to use if the configured prompt is not available. + * @param [onlyOneInsertion] - Optional. If true, only one insertion will be made. + * @param [range] - Optional. The range to edit if provided. + * @returns + */ + async function streamInlineEdit( + promptName: keyof ContextMenuConfig, + fallbackPrompt: string, + onlyOneInsertion?: boolean, + range?: vscode.Range, + ) { + const config = await configHandler.loadConfig(); - const defaultModelTitle = await sidebar.webviewProtocol.request( - "getDefaultModelTitle", - undefined, - ); - - const modelTitle = - getModelByRole(config, "inlineEdit")?.title ?? defaultModelTitle; - - sidebar.webviewProtocol.request("incrementFtc", undefined); - - await verticalDiffManager.streamEdit( - config.experimental?.contextMenuPrompts?.[promptName] ?? fallbackPrompt, - modelTitle, - undefined, - onlyOneInsertion, - undefined, - range, - ); - } - - return { - "continue.acceptDiff": async (newFilepath?: string | vscode.Uri) => { - captureCommandTelemetry("acceptDiff"); - - let fullPath = newFilepath; - - if (fullPath instanceof vscode.Uri) { - fullPath = fullPath.fsPath; - } else { - fullPath = getFullyQualifiedPath(fullPath); - } - - verticalDiffManager.clearForFilepath(fullPath, true); - await diffManager.acceptDiff(fullPath); - await sidebar.webviewProtocol.request("setEditStatus", { - status: "done", - }); - }, - "continue.rejectDiff": async (newFilepath?: string | vscode.Uri) => { - captureCommandTelemetry("rejectDiff"); - - let fullPath = newFilepath; - - if (fullPath instanceof vscode.Uri) { - fullPath = fullPath.fsPath; - } else { - fullPath = getFullyQualifiedPath(fullPath); - } - - verticalDiffManager.clearForFilepath(fullPath, false); - await diffManager.rejectDiff(fullPath); - await sidebar.webviewProtocol.request("setEditStatus", { - status: "done", - }); - }, - "continue.acceptVerticalDiffBlock": (filepath?: string, index?: number) => { - captureCommandTelemetry("acceptVerticalDiffBlock"); - verticalDiffManager.acceptRejectVerticalDiffBlock(true, filepath, index); - }, - "continue.rejectVerticalDiffBlock": (filepath?: string, index?: number) => { - captureCommandTelemetry("rejectVerticalDiffBlock"); - verticalDiffManager.acceptRejectVerticalDiffBlock(false, filepath, index); - }, - "continue.quickFix": async ( - range: vscode.Range, - diagnosticMessage: string, - ) => { - captureCommandTelemetry("quickFix"); - - const prompt = `Please explain the cause of this error and how to solve it: ${diagnosticMessage}`; - - addCodeToContextFromRange(range, sidebar.webviewProtocol, prompt); - - vscode.commands.executeCommand("continue.continueGUIView.focus"); - }, - // Passthrough for telemetry purposes - "continue.defaultQuickAction": async (args: QuickEditShowParams) => { - captureCommandTelemetry("defaultQuickAction"); - vscode.commands.executeCommand("continue.quickEdit", args); - }, - "continue.customQuickActionSendToChat": async ( - prompt: string, - range: vscode.Range, - ) => { - captureCommandTelemetry("customQuickActionSendToChat"); - - addCodeToContextFromRange(range, sidebar.webviewProtocol, prompt); - - vscode.commands.executeCommand("continue.continueGUIView.focus"); - }, - "continue.customQuickActionStreamInlineEdit": async ( - prompt: string, - range: vscode.Range, - ) => { - captureCommandTelemetry("customQuickActionStreamInlineEdit"); - - streamInlineEdit("docstring", prompt, false, range); - }, - "continue.codebaseForceReIndex": async () => { - core.invoke("index/forceReIndex", undefined); - }, - "continue.rebuildCodebaseIndex": async () => { - core.invoke("index/forceReIndex", { shouldClearIndexes: true }); - }, - "continue.docsIndex": async () => { - core.invoke("context/indexDocs", { reIndex: false }); - }, - "continue.docsReIndex": async () => { - core.invoke("context/indexDocs", { reIndex: true }); - }, - "continue.focusContinueInput": async () => { - focusGUI(); - sidebar.webviewProtocol?.request("focusContinueInput", undefined); - await addHighlightedCodeToContext(sidebar.webviewProtocol); - }, - "continue.focusContinueInputWithoutClear": async () => { - const fullScreenTab = getFullScreenTab(); - - const isContinueInputFocused = await sidebar.webviewProtocol.request( - "isContinueInputFocused", + const defaultModelTitle = await sidebar.webviewProtocol.request( + "getDefaultModelTitle", undefined, ); - if (isContinueInputFocused) { - // Handle closing the GUI only if we are focused on the input - if (fullScreenTab) { - fullScreenPanel?.dispose(); - } - } else { - // Handle opening the GUI otherwise - if (!fullScreenTab) { - // focus sidebar - vscode.commands.executeCommand("continue.continueGUIView.focus"); + const modelTitle = + getModelByRole(config, "inlineEdit")?.title ?? defaultModelTitle; + + sidebar.webviewProtocol.request("incrementFtc", undefined); + + await verticalDiffManager.streamEdit( + config.experimental?.contextMenuPrompts?.[promptName] ?? fallbackPrompt, + modelTitle, + undefined, + onlyOneInsertion, + undefined, + range, + ); + } + + return { + "continue.acceptDiff": async (newFilepath?: string | vscode.Uri) => { + captureCommandTelemetry("acceptDiff"); + + let fullPath = newFilepath; + + if (fullPath instanceof vscode.Uri) { + fullPath = fullPath.fsPath; } else { - // focus fullscreen - fullScreenPanel?.reveal(); + fullPath = getFullyQualifiedPath(fullPath); } - sidebar.webviewProtocol?.request( - "focusContinueInputWithoutClear", + verticalDiffManager.clearForFilepath(fullPath, true); + await diffManager.acceptDiff(fullPath); + await sidebar.webviewProtocol.request("setEditStatus", { + status: "done", + }); + }, + "continue.rejectDiff": async (newFilepath?: string | vscode.Uri) => { + captureCommandTelemetry("rejectDiff"); + + let fullPath = newFilepath; + + if (fullPath instanceof vscode.Uri) { + fullPath = fullPath.fsPath; + } else { + fullPath = getFullyQualifiedPath(fullPath); + } + + verticalDiffManager.clearForFilepath(fullPath, false); + await diffManager.rejectDiff(fullPath); + await sidebar.webviewProtocol.request("setEditStatus", { + status: "done", + }); + }, + "continue.acceptVerticalDiffBlock": (filepath?: string, index?: number) => { + captureCommandTelemetry("acceptVerticalDiffBlock"); + verticalDiffManager.acceptRejectVerticalDiffBlock(true, filepath, index); + }, + "continue.rejectVerticalDiffBlock": (filepath?: string, index?: number) => { + captureCommandTelemetry("rejectVerticalDiffBlock"); + verticalDiffManager.acceptRejectVerticalDiffBlock(false, filepath, index); + }, + "continue.quickFix": async ( + range: vscode.Range, + diagnosticMessage: string, + ) => { + captureCommandTelemetry("quickFix"); + + const prompt = `Please explain the cause of this error and how to solve it: ${diagnosticMessage}`; + + addCodeToContextFromRange(range, sidebar.webviewProtocol, prompt); + + vscode.commands.executeCommand("continue.continueGUIView.focus"); + }, + // Passthrough for telemetry purposes + "continue.defaultQuickAction": async (args: QuickEditShowParams) => { + captureCommandTelemetry("defaultQuickAction"); + vscode.commands.executeCommand("continue.quickEdit", args); + }, + "continue.customQuickActionSendToChat": async ( + prompt: string, + range: vscode.Range, + ) => { + captureCommandTelemetry("customQuickActionSendToChat"); + + addCodeToContextFromRange(range, sidebar.webviewProtocol, prompt); + + vscode.commands.executeCommand("continue.continueGUIView.focus"); + }, + "continue.customQuickActionStreamInlineEdit": async ( + prompt: string, + range: vscode.Range, + ) => { + captureCommandTelemetry("customQuickActionStreamInlineEdit"); + + streamInlineEdit("docstring", prompt, false, range); + }, + "continue.codebaseForceReIndex": async () => { + core.invoke("index/forceReIndex", undefined); + }, + "continue.rebuildCodebaseIndex": async () => { + core.invoke("index/forceReIndex", { shouldClearIndexes: true }); + }, + "continue.docsIndex": async () => { + core.invoke("context/indexDocs", { reIndex: false }); + }, + "continue.docsReIndex": async () => { + core.invoke("context/indexDocs", { reIndex: true }); + }, + "continue.focusContinueInput": async () => { + focusGUI(); + sidebar.webviewProtocol?.request("focusContinueInput", undefined); + await addHighlightedCodeToContext(sidebar.webviewProtocol); + }, + "continue.focusContinueInputWithoutClear": async () => { + const isContinueInputFocused = await sidebar.webviewProtocol.request( + "isContinueInputFocused", undefined, ); - await addHighlightedCodeToContext(sidebar.webviewProtocol); - } - }, - "continue.edit": async () => { - captureCommandTelemetry("edit"); - const fullScreenTab = getFullScreenTab(); - if (!fullScreenTab) { - // focus sidebar - vscode.commands.executeCommand("continue.continueGUIView.focus"); - } else { - // focus fullscreen - fullScreenPanel?.reveal(); - } - - const editor = vscode.window.activeTextEditor; - if (!editor) { - return; - } - - editDecorationManager.setDecoration( - editor, - new vscode.Range(editor.selection.start, editor.selection.end), - ); - - const highlightedCode = getCurrentlyHighlightedCode(true)!; - await sidebar.webviewProtocol?.request("startEditMode", { - highlightedCode, - }); - - // Un-select the current selection - editor.selection = new vscode.Selection( - editor.selection.anchor, - editor.selection.anchor, - ); - - setTimeout(() => { - sidebar.webviewProtocol?.request("focusContinueInput", undefined); - }, 30); - }, - "continue.exitEditMode": async () => { - captureCommandTelemetry("exitEditMode"); - await sidebar.webviewProtocol?.request("exitEditMode", undefined); - }, - "continue.quickEdit": async (args: QuickEditShowParams) => { - let linesOfCode = undefined; - if (args.range) { - linesOfCode = args.range.end.line - args.range.start.line; - } - captureCommandTelemetry("quickEdit", { - linesOfCode, - }); - quickEdit.show(args); - }, - "continue.writeCommentsForCode": async () => { - captureCommandTelemetry("writeCommentsForCode"); - - streamInlineEdit( - "comment", - "Write comments for this code. Do not change anything about the code itself.", - ); - }, - "continue.writeDocstringForCode": async () => { - captureCommandTelemetry("writeDocstringForCode"); - - streamInlineEdit( - "docstring", - "Write a docstring for this code. Do not change anything about the code itself.", - true, - ); - }, - "continue.fixCode": async () => { - captureCommandTelemetry("fixCode"); - - streamInlineEdit( - "fix", - "Fix this code. If it is already 100% correct, simply rewrite the code.", - ); - }, - "continue.optimizeCode": async () => { - captureCommandTelemetry("optimizeCode"); - streamInlineEdit("optimize", "Optimize this code"); - }, - "continue.fixGrammar": async () => { - captureCommandTelemetry("fixGrammar"); - streamInlineEdit( - "fixGrammar", - "If there are any grammar or spelling mistakes in this writing, fix them. Do not make other large changes to the writing.", - ); - }, - "continue.viewLogs": async () => { - captureCommandTelemetry("viewLogs"); - - // Open ~/.continue/continue.log - const logFile = path.join(os.homedir(), ".continue", "continue.log"); - // Make sure the file/directory exist - if (!fs.existsSync(logFile)) { - fs.mkdirSync(path.dirname(logFile), { recursive: true }); - fs.writeFileSync(logFile, ""); - } - - const uri = vscode.Uri.file(logFile); - await vscode.window.showTextDocument(uri); - }, - "continue.debugTerminal": async () => { - captureCommandTelemetry("debugTerminal"); - - const terminalContents = await ide.getTerminalContents(); - - vscode.commands.executeCommand("continue.continueGUIView.focus"); - - sidebar.webviewProtocol?.request("userInput", { - input: `I got the following error, can you please help explain how to fix it?\n\n${terminalContents.trim()}`, - }); - }, - "continue.hideInlineTip": () => { - vscode.workspace - .getConfiguration(EXTENSION_NAME) - .update("showInlineTip", false, vscode.ConfigurationTarget.Global); - }, - - // Commands without keyboard shortcuts - "continue.addModel": () => { - captureCommandTelemetry("addModel"); - - vscode.commands.executeCommand("continue.continueGUIView.focus"); - sidebar.webviewProtocol?.request("addModel", undefined); - }, - "continue.openSettingsUI": () => { - vscode.commands.executeCommand("continue.continueGUIView.focus"); - sidebar.webviewProtocol?.request("openSettings", undefined); - }, - "continue.sendMainUserInput": (text: string) => { - sidebar.webviewProtocol?.request("userInput", { - input: text, - }); - }, - "continue.selectRange": (startLine: number, endLine: number) => { - if (!vscode.window.activeTextEditor) { - return; - } - vscode.window.activeTextEditor.selection = new vscode.Selection( - startLine, - 0, - endLine, - 0, - ); - }, - "continue.foldAndUnfold": ( - foldSelectionLines: number[], - unfoldSelectionLines: number[], - ) => { - vscode.commands.executeCommand("editor.unfold", { - selectionLines: unfoldSelectionLines, - }); - vscode.commands.executeCommand("editor.fold", { - selectionLines: foldSelectionLines, - }); - }, - "continue.sendToTerminal": (text: string) => { - captureCommandTelemetry("sendToTerminal"); - ide.runCommand(text); - }, - "continue.newSession": () => { - sidebar.webviewProtocol?.request("newSession", undefined); - }, - "continue.viewHistory": () => { - sidebar.webviewProtocol?.request("viewHistory", undefined); - }, - "continue.focusContinueSessionId": async ( - sessionId: string | undefined, - ) => { - if (!sessionId) { - sessionId = await vscode.window.showInputBox({ - prompt: "Enter the Session ID", - }); - } - sidebar.webviewProtocol?.request("focusContinueSessionId", { sessionId }); - }, - "continue.applyCodeFromChat": () => { - sidebar.webviewProtocol.request("applyCodeFromChat", undefined); - }, - "continue.toggleFullScreen": () => { - focusGUI(); - - // Check if full screen is already open by checking open tabs - const fullScreenTab = getFullScreenTab(); - - if (fullScreenTab && fullScreenPanel) { - //Full screen open, but not focused - focus it - fullScreenPanel.reveal(); - return; - } - - //Full screen not open - open it - captureCommandTelemetry("openFullScreen"); - - //create the full screen panel - let panel = vscode.window.createWebviewPanel( - "continue.continueGUIView", - "Continue", - vscode.ViewColumn.One, - { - retainContextWhenHidden: true, - }, - ); - fullScreenPanel = panel; - - //Add content to the panel - panel.webview.html = sidebar.getSidebarContent( - extensionContext, - panel, - undefined, - undefined, - true, - ); - - //When panel closes, reset the webview and focus - panel.onDidDispose( - () => { - sidebar.resetWebviewProtocolWebview(); - vscode.commands.executeCommand("continue.focusContinueInput"); - }, - null, - extensionContext.subscriptions, - ); - - vscode.commands.executeCommand("workbench.action.copyEditorToNewWindow"); - }, - "continue.openConfigJson": () => { - ide.openFile(getConfigJsonPath()); - }, - "continue.selectFilesAsContext": async ( - firstUri: vscode.Uri, - uris: vscode.Uri[], - ) => { - if (uris === undefined) { - throw new Error("No files were selected"); - } - - vscode.commands.executeCommand("continue.continueGUIView.focus"); - - for (const uri of uris) { - // If it's a folder, add the entire folder contents recursively by using walkDir (to ignore ignored files) - const isDirectory = await vscode.workspace.fs - .stat(uri) - ?.then((stat) => stat.type === vscode.FileType.Directory); - if (isDirectory) { - for await (const filepath of walkDirAsync(uri.fsPath, ide)) { - addEntireFileToContext( - uriFromFilePath(filepath), - false, - sidebar.webviewProtocol, - ); + if (isContinueInputFocused) { + // Handle closing the GUI only if we are focused on the input + const fullScreenTab = getFullScreenTab(); + if (fullScreenTab) { + fullScreenPanel?.dispose(); } } else { - addEntireFileToContext(uri, false, sidebar.webviewProtocol); - } - } - }, - "continue.logAutocompleteOutcome": ( - completionId: string, - completionProvider: CompletionProvider, - ) => { - completionProvider.accept(completionId); - }, - "continue.toggleTabAutocompleteEnabled": () => { - captureCommandTelemetry("toggleTabAutocompleteEnabled"); + focusGUI(); - const config = vscode.workspace.getConfiguration(EXTENSION_NAME); - const enabled = config.get("enableTabAutocomplete"); - const pauseOnBattery = config.get( - "pauseTabAutocompleteOnBattery", - ); - if (!pauseOnBattery || battery.isACConnected()) { - config.update( - "enableTabAutocomplete", - !enabled, - vscode.ConfigurationTarget.Global, + sidebar.webviewProtocol?.request( + "focusContinueInputWithoutClear", + undefined, + ); + + await addHighlightedCodeToContext(sidebar.webviewProtocol); + } + }, + "continue.hideGUI": async () => { + vscode.commands.executeCommand("workbench.action.toggleAuxiliaryBar"); + }, + "continue.edit": async () => { + captureCommandTelemetry("edit"); + focusGUI(); + + const editor = vscode.window.activeTextEditor; + if (!editor) { + return; + } + + editDecorationManager.setDecoration( + editor, + new vscode.Range(editor.selection.start, editor.selection.end), ); - } else { - if (enabled) { - const paused = getStatusBarStatus() === StatusBarStatus.Paused; - if (paused) { - setupStatusBar(StatusBarStatus.Enabled); + + const highlightedCode = getCurrentlyHighlightedCode(true)!; + await sidebar.webviewProtocol?.request("startEditMode", { + highlightedCode, + }); + + // Un-select the current selection + editor.selection = new vscode.Selection( + editor.selection.anchor, + editor.selection.anchor, + ); + + setTimeout(() => { + sidebar.webviewProtocol?.request("focusContinueInput", undefined); + }, 30); + }, + "continue.exitEditMode": async () => { + captureCommandTelemetry("exitEditMode"); + await sidebar.webviewProtocol?.request("exitEditMode", undefined); + }, + "continue.quickEdit": async (args: QuickEditShowParams) => { + let linesOfCode = undefined; + if (args.range) { + linesOfCode = args.range.end.line - args.range.start.line; + } + captureCommandTelemetry("quickEdit", { + linesOfCode, + }); + quickEdit.show(args); + }, + "continue.writeCommentsForCode": async () => { + captureCommandTelemetry("writeCommentsForCode"); + + streamInlineEdit( + "comment", + "Write comments for this code. Do not change anything about the code itself.", + ); + }, + "continue.writeDocstringForCode": async () => { + captureCommandTelemetry("writeDocstringForCode"); + + streamInlineEdit( + "docstring", + "Write a docstring for this code. Do not change anything about the code itself.", + true, + ); + }, + "continue.fixCode": async () => { + captureCommandTelemetry("fixCode"); + + streamInlineEdit( + "fix", + "Fix this code. If it is already 100% correct, simply rewrite the code.", + ); + }, + "continue.optimizeCode": async () => { + captureCommandTelemetry("optimizeCode"); + streamInlineEdit("optimize", "Optimize this code"); + }, + "continue.fixGrammar": async () => { + captureCommandTelemetry("fixGrammar"); + streamInlineEdit( + "fixGrammar", + "If there are any grammar or spelling mistakes in this writing, fix them. Do not make other large changes to the writing.", + ); + }, + "continue.viewLogs": async () => { + captureCommandTelemetry("viewLogs"); + + // Open ~/.continue/continue.log + const logFile = path.join(os.homedir(), ".continue", "continue.log"); + // Make sure the file/directory exist + if (!fs.existsSync(logFile)) { + fs.mkdirSync(path.dirname(logFile), { recursive: true }); + fs.writeFileSync(logFile, ""); + } + + const uri = vscode.Uri.file(logFile); + await vscode.window.showTextDocument(uri); + }, + "continue.debugTerminal": async () => { + captureCommandTelemetry("debugTerminal"); + + const terminalContents = await ide.getTerminalContents(); + + vscode.commands.executeCommand("continue.continueGUIView.focus"); + + sidebar.webviewProtocol?.request("userInput", { + input: `I got the following error, can you please help explain how to fix it?\n\n${terminalContents.trim()}`, + }); + }, + "continue.hideInlineTip": () => { + vscode.workspace + .getConfiguration(EXTENSION_NAME) + .update("showInlineTip", false, vscode.ConfigurationTarget.Global); + }, + + // Commands without keyboard shortcuts + "continue.addModel": () => { + captureCommandTelemetry("addModel"); + + vscode.commands.executeCommand("continue.continueGUIView.focus"); + sidebar.webviewProtocol?.request("addModel", undefined); + }, + "continue.openSettingsUI": () => { + vscode.commands.executeCommand("continue.continueGUIView.focus"); + sidebar.webviewProtocol?.request("openSettings", undefined); + }, + "continue.sendMainUserInput": (text: string) => { + sidebar.webviewProtocol?.request("userInput", { + input: text, + }); + }, + "continue.selectRange": (startLine: number, endLine: number) => { + if (!vscode.window.activeTextEditor) { + return; + } + vscode.window.activeTextEditor.selection = new vscode.Selection( + startLine, + 0, + endLine, + 0, + ); + }, + "continue.foldAndUnfold": ( + foldSelectionLines: number[], + unfoldSelectionLines: number[], + ) => { + vscode.commands.executeCommand("editor.unfold", { + selectionLines: unfoldSelectionLines, + }); + vscode.commands.executeCommand("editor.fold", { + selectionLines: foldSelectionLines, + }); + }, + "continue.sendToTerminal": (text: string) => { + captureCommandTelemetry("sendToTerminal"); + ide.runCommand(text); + }, + "continue.newSession": () => { + sidebar.webviewProtocol?.request("newSession", undefined); + }, + "continue.viewHistory": () => { + sidebar.webviewProtocol?.request("viewHistory", undefined); + }, + "continue.focusContinueSessionId": async ( + sessionId: string | undefined, + ) => { + if (!sessionId) { + sessionId = await vscode.window.showInputBox({ + prompt: "Enter the Session ID", + }); + } + sidebar.webviewProtocol?.request("focusContinueSessionId", { sessionId }); + }, + "continue.applyCodeFromChat": () => { + sidebar.webviewProtocol.request("applyCodeFromChat", undefined); + }, + "continue.toggleFullScreen": () => { + focusGUI(); + + // Check if full screen is already open by checking open tabs + const fullScreenTab = getFullScreenTab(); + + if (fullScreenTab && fullScreenPanel) { + // Full screen open, but not focused - focus it + fullScreenPanel.reveal(); + return; + } + + // Full screen not open - open it + captureCommandTelemetry("openFullScreen"); + + // Create the full screen panel + let panel = vscode.window.createWebviewPanel( + "continue.continueGUIView", + "Continue", + vscode.ViewColumn.One, + { + retainContextWhenHidden: true, + }, + ); + fullScreenPanel = panel; + + // Add content to the panel + panel.webview.html = sidebar.getSidebarContent( + extensionContext, + panel, + undefined, + undefined, + true, + ); + + // When panel closes, reset the webview and focus + panel.onDidDispose( + () => { + sidebar.resetWebviewProtocolWebview(); + vscode.commands.executeCommand("continue.focusContinueInput"); + }, + null, + extensionContext.subscriptions, + ); + + vscode.commands.executeCommand("workbench.action.copyEditorToNewWindow"); + }, + "continue.openConfigJson": () => { + ide.openFile(getConfigJsonPath()); + }, + "continue.selectFilesAsContext": async ( + firstUri: vscode.Uri, + uris: vscode.Uri[], + ) => { + if (uris === undefined) { + throw new Error("No files were selected"); + } + + vscode.commands.executeCommand("continue.continueGUIView.focus"); + + for (const uri of uris) { + // If it's a folder, add the entire folder contents recursively by using walkDir (to ignore ignored files) + const isDirectory = await vscode.workspace.fs + .stat(uri) + ?.then((stat) => stat.type === vscode.FileType.Directory); + if (isDirectory) { + for await (const filepath of walkDirAsync(uri.fsPath, ide)) { + addEntireFileToContext( + uriFromFilePath(filepath), + false, + sidebar.webviewProtocol, + ); + } } else { + addEntireFileToContext(uri, false, sidebar.webviewProtocol); + } + } + }, + "continue.logAutocompleteOutcome": ( + completionId: string, + completionProvider: CompletionProvider, + ) => { + completionProvider.accept(completionId); + }, + "continue.toggleTabAutocompleteEnabled": () => { + captureCommandTelemetry("toggleTabAutocompleteEnabled"); + + const config = vscode.workspace.getConfiguration(EXTENSION_NAME); + const enabled = config.get("enableTabAutocomplete"); + const pauseOnBattery = config.get( + "pauseTabAutocompleteOnBattery", + ); + if (!pauseOnBattery || battery.isACConnected()) { + config.update( + "enableTabAutocomplete", + !enabled, + vscode.ConfigurationTarget.Global, + ); + } else { + if (enabled) { + const paused = getStatusBarStatus() === StatusBarStatus.Paused; + if (paused) { + setupStatusBar(StatusBarStatus.Enabled); + } else { + config.update( + "enableTabAutocomplete", + false, + vscode.ConfigurationTarget.Global, + ); + } + } else { + setupStatusBar(StatusBarStatus.Paused); config.update( "enableTabAutocomplete", - false, + true, vscode.ConfigurationTarget.Global, ); } + } + }, + "continue.openTabAutocompleteConfigMenu": async () => { + captureCommandTelemetry("openTabAutocompleteConfigMenu"); + + const config = vscode.workspace.getConfiguration(EXTENSION_NAME); + const quickPick = vscode.window.createQuickPick(); + const autocompleteModels = + (await configHandler.loadConfig())?.tabAutocompleteModels ?? []; + + let selected = new GlobalContext().get("selectedTabAutocompleteModel"); + if ( + !selected || + !autocompleteModels.some((model) => model.title === selected) + ) { + selected = autocompleteModels[0].title; + } + + // Toggle between Disabled, Paused, and Enabled + const pauseOnBattery = + config.get("pauseTabAutocompleteOnBattery") && + !battery.isACConnected(); + const currentStatus = getStatusBarStatus(); + + let targetStatus: StatusBarStatus | undefined; + if (pauseOnBattery) { + // Cycle from Disabled -> Paused -> Enabled + targetStatus = + currentStatus === StatusBarStatus.Paused + ? StatusBarStatus.Enabled + : currentStatus === StatusBarStatus.Disabled + ? StatusBarStatus.Paused + : StatusBarStatus.Disabled; } else { - setupStatusBar(StatusBarStatus.Paused); - config.update( - "enableTabAutocomplete", - true, - vscode.ConfigurationTarget.Global, - ); - } - } - }, - "continue.openTabAutocompleteConfigMenu": async () => { - captureCommandTelemetry("openTabAutocompleteConfigMenu"); - - const config = vscode.workspace.getConfiguration(EXTENSION_NAME); - const quickPick = vscode.window.createQuickPick(); - const autocompleteModels = - (await configHandler.loadConfig())?.tabAutocompleteModels ?? []; - - let selected = new GlobalContext().get("selectedTabAutocompleteModel"); - if ( - !selected || - !autocompleteModels.some((model) => model.title === selected) - ) { - selected = autocompleteModels[0].title; - } - - // Toggle between Disabled, Paused, and Enabled - const pauseOnBattery = - config.get("pauseTabAutocompleteOnBattery") && - !battery.isACConnected(); - const currentStatus = getStatusBarStatus(); - - let targetStatus: StatusBarStatus | undefined; - if (pauseOnBattery) { - // Cycle from Disabled -> Paused -> Enabled - targetStatus = - currentStatus === StatusBarStatus.Paused - ? StatusBarStatus.Enabled - : currentStatus === StatusBarStatus.Disabled - ? StatusBarStatus.Paused + // Toggle between Disabled and Enabled + targetStatus = + currentStatus === StatusBarStatus.Disabled + ? StatusBarStatus.Enabled : StatusBarStatus.Disabled; - } else { - // Toggle between Disabled and Enabled - targetStatus = - currentStatus === StatusBarStatus.Disabled - ? StatusBarStatus.Enabled - : StatusBarStatus.Disabled; - } - quickPick.items = [ - { - label: "$(question) Open help center", - }, - { - label: "$(comment) Open chat (Cmd+L)", - }, - { - label: "$(screen-full) Open full screen chat (Cmd+K Cmd+M)", - }, - { - label: quickPickStatusText(targetStatus), - }, - { - label: "$(gear) Configure autocomplete options", - }, - { - label: "$(feedback) Give feedback", - }, - { - kind: vscode.QuickPickItemKind.Separator, - label: "Switch model", - }, - ...autocompleteModels.map((model) => ({ - label: getAutocompleteStatusBarTitle(selected, model), - description: getAutocompleteStatusBarDescription(selected, model), - })), - ]; - quickPick.onDidAccept(() => { - const selectedOption = quickPick.selectedItems[0].label; - const targetStatus = - getStatusBarStatusFromQuickPickItemLabel(selectedOption); - - if (targetStatus !== undefined) { - setupStatusBar(targetStatus); - config.update( - "enableTabAutocomplete", - targetStatus === StatusBarStatus.Enabled, - vscode.ConfigurationTarget.Global, - ); - } else if ( - selectedOption === "$(gear) Configure autocomplete options" - ) { - ide.openFile(getConfigJsonPath()); - } else if ( - autocompleteModels.some((model) => model.title === selectedOption) - ) { - new GlobalContext().update( - "selectedTabAutocompleteModel", - selectedOption, - ); - configHandler.reloadConfig(); - } else if (selectedOption === "$(feedback) Give feedback") { - vscode.commands.executeCommand("continue.giveAutocompleteFeedback"); - } else if (selectedOption === "$(comment) Open chat (Cmd+L)") { - vscode.commands.executeCommand("continue.focusContinueInput"); - } else if ( - selectedOption === - "$(screen-full) Open full screen chat (Cmd+K Cmd+M)" - ) { - vscode.commands.executeCommand("continue.toggleFullScreen"); - } else if (selectedOption === "$(question) Open help center") { - focusGUI(); - vscode.commands.executeCommand("continue.navigateTo", "/more"); } - quickPick.dispose(); - }); - quickPick.show(); - }, - "continue.giveAutocompleteFeedback": async () => { - const feedback = await vscode.window.showInputBox({ - ignoreFocusOut: true, - prompt: - "Please share what went wrong with the last completion. The details of the completion as well as this message will be sent to the Continue team in order to improve.", - }); - if (feedback) { - const client = await continueServerClientPromise; - const completionsPath = getDevDataFilePath("autocomplete"); + quickPick.items = [ + { + label: "$(question) Open help center", + }, + { + label: "$(comment) Open chat (Cmd+L)", + }, + { + label: "$(screen-full) Open full screen chat (Cmd+K Cmd+M)", + }, + { + label: quickPickStatusText(targetStatus), + }, + { + label: "$(gear) Configure autocomplete options", + }, + { + label: "$(feedback) Give feedback", + }, + { + kind: vscode.QuickPickItemKind.Separator, + label: "Switch model", + }, + ...autocompleteModels.map((model) => ({ + label: getAutocompleteStatusBarTitle(selected, model), + description: getAutocompleteStatusBarDescription(selected, model), + })), + ]; + quickPick.onDidAccept(() => { + const selectedOption = quickPick.selectedItems[0].label; + const targetStatus = + getStatusBarStatusFromQuickPickItemLabel(selectedOption); - const lastLines = await readLastLines.read(completionsPath, 2); - client.sendFeedback(feedback, lastLines); - } - }, - "continue.navigateTo": (path: string) => { - sidebar.webviewProtocol?.request("navigateTo", { path }); - focusGUI(); - }, + if (targetStatus !== undefined) { + setupStatusBar(targetStatus); + config.update( + "enableTabAutocomplete", + targetStatus === StatusBarStatus.Enabled, + vscode.ConfigurationTarget.Global, + ); + } else if ( + selectedOption === "$(gear) Configure autocomplete options" + ) { + ide.openFile(getConfigJsonPath()); + } else if ( + autocompleteModels.some((model) => model.title === selectedOption) + ) { + new GlobalContext().update( + "selectedTabAutocompleteModel", + selectedOption, + ); + configHandler.reloadConfig(); + } else if (selectedOption === "$(feedback) Give feedback") { + vscode.commands.executeCommand("continue.giveAutocompleteFeedback"); + } else if (selectedOption === "$(comment) Open chat (Cmd+L)") { + vscode.commands.executeCommand("continue.focusContinueInput"); + } else if ( + selectedOption === + "$(screen-full) Open full screen chat (Cmd+K Cmd+M)" + ) { + vscode.commands.executeCommand("continue.toggleFullScreen"); + } else if (selectedOption === "$(question) Open help center") { + focusGUI(); + vscode.commands.executeCommand("continue.navigateTo", "/more"); + } + quickPick.dispose(); + }); + quickPick.show(); + }, + "continue.giveAutocompleteFeedback": async () => { + const feedback = await vscode.window.showInputBox({ + ignoreFocusOut: true, + prompt: + "Please share what went wrong with the last completion. The details of the completion as well as this message will be sent to the Continue team in order to improve.", + }); + if (feedback) { + const client = await continueServerClientPromise; + const completionsPath = getDevDataFilePath("autocomplete"); + + const lastLines = await readLastLines.read(completionsPath, 2); + client.sendFeedback(feedback, lastLines); + } + }, + "continue.navigateTo": (path: string) => { + sidebar.webviewProtocol?.request("navigateTo", { path }); + focusGUI(); + }, + }; }; -}; export function registerAllCommands( context: vscode.ExtensionContext, diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index 483ff1603..952a57e54 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -130,6 +130,9 @@ export class VsCodeMessenger { this.onWebview("toggleFullScreen", (msg) => { vscode.commands.executeCommand("continue.toggleFullScreen"); }); + this.onWebview("hideGUI", (msg) => { + vscode.commands.executeCommand("continue.hideGUI"); + }); // History this.onWebview("saveFile", async (msg) => { return await ide.saveFile(msg.data.filepath); From 219b2c1569cc7e0ad555d87cc3a1e1e6699ccc6f Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Wed, 6 Nov 2024 09:32:56 -0800 Subject: [PATCH 61/96] keyboard shortcuts --- gui/src/components/mainInput/TipTapEditor.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gui/src/components/mainInput/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor.tsx index 55ff9db39..3bae41942 100644 --- a/gui/src/components/mainInput/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor.tsx @@ -908,7 +908,7 @@ function TipTapEditor(props: TipTapEditorProps) { return ( { From 707d32ebc2e24cf0107255d37d43dc33acc3a6cc Mon Sep 17 00:00:00 2001 From: Sherman Boyd Date: Wed, 6 Nov 2024 10:53:03 -0800 Subject: [PATCH 62/96] NPM audit and fix --- docs/package-lock.json | 661 ++++++++++++++++++++++++----------------- 1 file changed, 389 insertions(+), 272 deletions(-) diff --git a/docs/package-lock.json b/docs/package-lock.json index 5062e2353..756266105 100644 --- a/docs/package-lock.json +++ b/docs/package-lock.json @@ -3475,9 +3475,10 @@ } }, "node_modules/@types/estree": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.5.tgz", - "integrity": "sha512-/kYRxGDLWzHOB7q+wtSUQlFrtcdUccpfy+X+9iMBpHK8QLLhx2wIPYuS5DYtR9Wa/YlZAbIovy7qVdB1Aq6Lyw==" + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.6.tgz", + "integrity": "sha512-AYnb1nQyY49te+VRAVgmzfcgjYS91mY5P0TKUDCLEM+gNnA+3T6rWITXRLYCpahpqSQbN5cE+gHpnPyXjHWxcw==", + "license": "MIT" }, "node_modules/@types/estree-jsx": { "version": "1.0.3", @@ -3764,145 +3765,162 @@ "integrity": "sha512-zuVdFrMJiuCDQUMCzQaD6KL28MjnqqN8XnAqiEq9PNm/hCPTSGfrXCOfwj1ow4LFb/tNymJPwsNbVePc1xFqrQ==" }, "node_modules/@webassemblyjs/ast": { - "version": "1.11.6", - "resolved": "https://registry.npmjs.org/@webassemblyjs/ast/-/ast-1.11.6.tgz", - "integrity": "sha512-IN1xI7PwOvLPgjcf180gC1bqn3q/QaOCwYUahIOhbYUu8KA/3tw2RT/T0Gidi1l7Hhj5D/INhJxiICObqpMu4Q==", + "version": "1.13.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/ast/-/ast-1.13.1.tgz", + "integrity": "sha512-+Zp/YJMBws+tg2Nuy5jiFhwvPiSeIB0gPp1Ie/TyqFg69qJ/vRrOKQ7AsFLn3solq5/9ubkBjrGd0UcvFjFsYA==", + "license": "MIT", "dependencies": { - "@webassemblyjs/helper-numbers": "1.11.6", - "@webassemblyjs/helper-wasm-bytecode": "1.11.6" + "@webassemblyjs/helper-numbers": "1.12.1", + "@webassemblyjs/helper-wasm-bytecode": "1.12.1" } }, "node_modules/@webassemblyjs/floating-point-hex-parser": { - "version": "1.11.6", - "resolved": "https://registry.npmjs.org/@webassemblyjs/floating-point-hex-parser/-/floating-point-hex-parser-1.11.6.tgz", - "integrity": "sha512-ejAj9hfRJ2XMsNHk/v6Fu2dGS+i4UaXBXGemOfQ/JfQ6mdQg/WXtwleQRLLS4OvfDhv8rYnVwH27YJLMyYsxhw==" + "version": "1.12.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/floating-point-hex-parser/-/floating-point-hex-parser-1.12.1.tgz", + "integrity": "sha512-0vqwjuCO3Sa6pO3nfplawORkL1GUgza/H1A62SdXHSFCmAHoRcrtX/yVG3f1LuMYW951cvYRcRt6hThhz4FnCQ==", + "license": "MIT" }, "node_modules/@webassemblyjs/helper-api-error": { - "version": "1.11.6", - "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-api-error/-/helper-api-error-1.11.6.tgz", - "integrity": "sha512-o0YkoP4pVu4rN8aTJgAyj9hC2Sv5UlkzCHhxqWj8butaLvnpdc2jOwh4ewE6CX0txSfLn/UYaV/pheS2Txg//Q==" + "version": "1.12.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-api-error/-/helper-api-error-1.12.1.tgz", + "integrity": "sha512-czovmKZdRk4rYauCOuMV/EImC3qyfcqyJuOYyDRYR6PZSOW37VWe26fAZQznbvKjlwJdyxLl6mIfx47Cfz8ykw==", + "license": "MIT" }, "node_modules/@webassemblyjs/helper-buffer": { - "version": "1.11.6", - "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-buffer/-/helper-buffer-1.11.6.tgz", - "integrity": "sha512-z3nFzdcp1mb8nEOFFk8DrYLpHvhKC3grJD2ardfKOzmbmJvEf/tPIqCY+sNcwZIY8ZD7IkB2l7/pqhUhqm7hLA==" + "version": "1.13.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-buffer/-/helper-buffer-1.13.1.tgz", + "integrity": "sha512-J0gf97+D3CavG7aO5XmtwxRWMiMEuxQ6t8Aov8areSnyI5P5fM0HV0m8bE3iLfDQZBhxLCc15tRsFVOGyAJ0ng==", + "license": "MIT" }, "node_modules/@webassemblyjs/helper-numbers": { - "version": "1.11.6", - "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-numbers/-/helper-numbers-1.11.6.tgz", - "integrity": "sha512-vUIhZ8LZoIWHBohiEObxVm6hwP034jwmc9kuq5GdHZH0wiLVLIPcMCdpJzG4C11cHoQ25TFIQj9kaVADVX7N3g==", + "version": "1.12.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-numbers/-/helper-numbers-1.12.1.tgz", + "integrity": "sha512-Vp6k5nXOMvI9dWJqDGCMvwAc8+G6tI2YziuYWqxk7XYnWHdxEJo19CGpqm/kRh86rJxwYANLGuyreARhM+C9lQ==", + "license": "MIT", "dependencies": { - "@webassemblyjs/floating-point-hex-parser": "1.11.6", - "@webassemblyjs/helper-api-error": "1.11.6", + "@webassemblyjs/floating-point-hex-parser": "1.12.1", + "@webassemblyjs/helper-api-error": "1.12.1", "@xtuc/long": "4.2.2" } }, "node_modules/@webassemblyjs/helper-wasm-bytecode": { - "version": "1.11.6", - "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-wasm-bytecode/-/helper-wasm-bytecode-1.11.6.tgz", - "integrity": "sha512-sFFHKwcmBprO9e7Icf0+gddyWYDViL8bpPjJJl0WHxCdETktXdmtWLGVzoHbqUcY4Be1LkNfwTmXOJUFZYSJdA==" + "version": "1.12.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-wasm-bytecode/-/helper-wasm-bytecode-1.12.1.tgz", + "integrity": "sha512-flsRYmCqN2ZJmvAyNxZXPPFkwKoezeTUczytfBovql8cOjYTr6OTcZvku4UzyKFW0Kj+PgD+UaG8/IdX31EYWg==", + "license": "MIT" }, "node_modules/@webassemblyjs/helper-wasm-section": { - "version": "1.11.6", - "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-wasm-section/-/helper-wasm-section-1.11.6.tgz", - "integrity": "sha512-LPpZbSOwTpEC2cgn4hTydySy1Ke+XEu+ETXuoyvuyezHO3Kjdu90KK95Sh9xTbmjrCsUwvWwCOQQNta37VrS9g==", + "version": "1.13.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-wasm-section/-/helper-wasm-section-1.13.1.tgz", + "integrity": "sha512-lcVNbrM5Wm7867lmbU61l+R4dU7emD2X70f9V0PuicvsdVUS5vvXODAxRYGVGBAJ6rWmXMuZKjM0PoeBjAcm2A==", + "license": "MIT", "dependencies": { - "@webassemblyjs/ast": "1.11.6", - "@webassemblyjs/helper-buffer": "1.11.6", - "@webassemblyjs/helper-wasm-bytecode": "1.11.6", - "@webassemblyjs/wasm-gen": "1.11.6" + "@webassemblyjs/ast": "1.13.1", + "@webassemblyjs/helper-buffer": "1.13.1", + "@webassemblyjs/helper-wasm-bytecode": "1.12.1", + "@webassemblyjs/wasm-gen": "1.13.1" } }, "node_modules/@webassemblyjs/ieee754": { - "version": "1.11.6", - "resolved": "https://registry.npmjs.org/@webassemblyjs/ieee754/-/ieee754-1.11.6.tgz", - "integrity": "sha512-LM4p2csPNvbij6U1f19v6WR56QZ8JcHg3QIJTlSwzFcmx6WSORicYj6I63f9yU1kEUtrpG+kjkiIAkevHpDXrg==", + "version": "1.12.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/ieee754/-/ieee754-1.12.1.tgz", + "integrity": "sha512-fcrUCqE2dVldeVAHTWFiTiKMS9ivc5jOgB2c30zYOZnm3O54SWeMJWS/HXYK862we2AYHtf6GYuP9xG9J+5zyQ==", + "license": "MIT", "dependencies": { "@xtuc/ieee754": "^1.2.0" } }, "node_modules/@webassemblyjs/leb128": { - "version": "1.11.6", - "resolved": "https://registry.npmjs.org/@webassemblyjs/leb128/-/leb128-1.11.6.tgz", - "integrity": "sha512-m7a0FhE67DQXgouf1tbN5XQcdWoNgaAuoULHIfGFIEVKA6tu/edls6XnIlkmS6FrXAquJRPni3ZZKjw6FSPjPQ==", + "version": "1.12.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/leb128/-/leb128-1.12.1.tgz", + "integrity": "sha512-jOU6pTFNf7aGm46NCrEU7Gj6cVuP55T7+kyo5TU/rCduZ5EdwMPBZwSwwzjPZ3eFXYFCmC5wZdPZN0ZWio6n4Q==", + "license": "Apache-2.0", "dependencies": { "@xtuc/long": "4.2.2" } }, "node_modules/@webassemblyjs/utf8": { - "version": "1.11.6", - "resolved": "https://registry.npmjs.org/@webassemblyjs/utf8/-/utf8-1.11.6.tgz", - "integrity": "sha512-vtXf2wTQ3+up9Zsg8sa2yWiQpzSsMyXj0qViVP6xKGCUT8p8YJ6HqI7l5eCnWx1T/FYdsv07HQs2wTFbbof/RA==" + "version": "1.12.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/utf8/-/utf8-1.12.1.tgz", + "integrity": "sha512-zcZvnAY3/M28Of012dksIfC26qZQJlj2PQCCvxqlsRJHOYtasp+OvK8nRcg11TKzAAv3ja7Y0NEBMKAjH6ljnw==", + "license": "MIT" }, "node_modules/@webassemblyjs/wasm-edit": { - "version": "1.11.6", - "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-edit/-/wasm-edit-1.11.6.tgz", - "integrity": "sha512-Ybn2I6fnfIGuCR+Faaz7YcvtBKxvoLV3Lebn1tM4o/IAJzmi9AWYIPWpyBfU8cC+JxAO57bk4+zdsTjJR+VTOw==", + "version": "1.13.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-edit/-/wasm-edit-1.13.1.tgz", + "integrity": "sha512-YHnh/f4P4ggjPB+pcri8Pb2HHwCGK+B8qBE+NeEp/WTMQ7dAjgWTnLhXxUqb6WLOT25TK5m0VTCAKTYw8AKxcg==", + "license": "MIT", "dependencies": { - "@webassemblyjs/ast": "1.11.6", - "@webassemblyjs/helper-buffer": "1.11.6", - "@webassemblyjs/helper-wasm-bytecode": "1.11.6", - "@webassemblyjs/helper-wasm-section": "1.11.6", - "@webassemblyjs/wasm-gen": "1.11.6", - "@webassemblyjs/wasm-opt": "1.11.6", - "@webassemblyjs/wasm-parser": "1.11.6", - "@webassemblyjs/wast-printer": "1.11.6" + "@webassemblyjs/ast": "1.13.1", + "@webassemblyjs/helper-buffer": "1.13.1", + "@webassemblyjs/helper-wasm-bytecode": "1.12.1", + "@webassemblyjs/helper-wasm-section": "1.13.1", + "@webassemblyjs/wasm-gen": "1.13.1", + "@webassemblyjs/wasm-opt": "1.13.1", + "@webassemblyjs/wasm-parser": "1.13.1", + "@webassemblyjs/wast-printer": "1.13.1" } }, "node_modules/@webassemblyjs/wasm-gen": { - "version": "1.11.6", - "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-gen/-/wasm-gen-1.11.6.tgz", - "integrity": "sha512-3XOqkZP/y6B4F0PBAXvI1/bky7GryoogUtfwExeP/v7Nzwo1QLcq5oQmpKlftZLbT+ERUOAZVQjuNVak6UXjPA==", + "version": "1.13.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-gen/-/wasm-gen-1.13.1.tgz", + "integrity": "sha512-AxWiaqIeLh3c1H+8d1gPgVNXHyKP7jDu2G828Of9/E0/ovVEsh6LjX1QZ6g1tFBHocCwuUHK9O4w35kgojZRqA==", + "license": "MIT", "dependencies": { - "@webassemblyjs/ast": "1.11.6", - "@webassemblyjs/helper-wasm-bytecode": "1.11.6", - "@webassemblyjs/ieee754": "1.11.6", - "@webassemblyjs/leb128": "1.11.6", - "@webassemblyjs/utf8": "1.11.6" + "@webassemblyjs/ast": "1.13.1", + "@webassemblyjs/helper-wasm-bytecode": "1.12.1", + "@webassemblyjs/ieee754": "1.12.1", + "@webassemblyjs/leb128": "1.12.1", + "@webassemblyjs/utf8": "1.12.1" } }, "node_modules/@webassemblyjs/wasm-opt": { - "version": "1.11.6", - "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-opt/-/wasm-opt-1.11.6.tgz", - "integrity": "sha512-cOrKuLRE7PCe6AsOVl7WasYf3wbSo4CeOk6PkrjS7g57MFfVUF9u6ysQBBODX0LdgSvQqRiGz3CXvIDKcPNy4g==", + "version": "1.13.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-opt/-/wasm-opt-1.13.1.tgz", + "integrity": "sha512-SUMlvCrfykC7dtWX5g4TSuMmWi9w9tK5kGIdvQMnLuvJfnFLsnAaF86FNbSBSAL33VhM/hOhx4t9o66N37IqSg==", + "license": "MIT", "dependencies": { - "@webassemblyjs/ast": "1.11.6", - "@webassemblyjs/helper-buffer": "1.11.6", - "@webassemblyjs/wasm-gen": "1.11.6", - "@webassemblyjs/wasm-parser": "1.11.6" + "@webassemblyjs/ast": "1.13.1", + "@webassemblyjs/helper-buffer": "1.13.1", + "@webassemblyjs/wasm-gen": "1.13.1", + "@webassemblyjs/wasm-parser": "1.13.1" } }, "node_modules/@webassemblyjs/wasm-parser": { - "version": "1.11.6", - "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-parser/-/wasm-parser-1.11.6.tgz", - "integrity": "sha512-6ZwPeGzMJM3Dqp3hCsLgESxBGtT/OeCvCZ4TA1JUPYgmhAx38tTPR9JaKy0S5H3evQpO/h2uWs2j6Yc/fjkpTQ==", + "version": "1.13.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-parser/-/wasm-parser-1.13.1.tgz", + "integrity": "sha512-8SPOcbqSb7vXHG+B0PTsJrvT/HilwV3WkJgxw34lmhWvO+7qM9xBTd9u4dn1Lb86WHpKswT5XwF277uBTHFikg==", + "license": "MIT", "dependencies": { - "@webassemblyjs/ast": "1.11.6", - "@webassemblyjs/helper-api-error": "1.11.6", - "@webassemblyjs/helper-wasm-bytecode": "1.11.6", - "@webassemblyjs/ieee754": "1.11.6", - "@webassemblyjs/leb128": "1.11.6", - "@webassemblyjs/utf8": "1.11.6" + "@webassemblyjs/ast": "1.13.1", + "@webassemblyjs/helper-api-error": "1.12.1", + "@webassemblyjs/helper-wasm-bytecode": "1.12.1", + "@webassemblyjs/ieee754": "1.12.1", + "@webassemblyjs/leb128": "1.12.1", + "@webassemblyjs/utf8": "1.12.1" } }, "node_modules/@webassemblyjs/wast-printer": { - "version": "1.11.6", - "resolved": "https://registry.npmjs.org/@webassemblyjs/wast-printer/-/wast-printer-1.11.6.tgz", - "integrity": "sha512-JM7AhRcE+yW2GWYaKeHL5vt4xqee5N2WcezptmgyhNS+ScggqcT1OtXykhAb13Sn5Yas0j2uv9tHgrjwvzAP4A==", + "version": "1.13.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wast-printer/-/wast-printer-1.13.1.tgz", + "integrity": "sha512-q0zIfwpbFvaNkgbSzkZFzLsOs8ixZ5MSdTTMESilSAk1C3P8BKEWfbLEvIqyI/PjNpP9+ZU+/KwgfXx3T7ApKw==", + "license": "MIT", "dependencies": { - "@webassemblyjs/ast": "1.11.6", + "@webassemblyjs/ast": "1.13.1", "@xtuc/long": "4.2.2" } }, "node_modules/@xtuc/ieee754": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/@xtuc/ieee754/-/ieee754-1.2.0.tgz", - "integrity": "sha512-DX8nKgqcGwsc0eJSqYt5lwP4DH5FlHnmuWWBRy7X0NcaGR0ZtuyeESgMwTYVEtxmsNGY+qit4QYT/MIYTOTPeA==" + "integrity": "sha512-DX8nKgqcGwsc0eJSqYt5lwP4DH5FlHnmuWWBRy7X0NcaGR0ZtuyeESgMwTYVEtxmsNGY+qit4QYT/MIYTOTPeA==", + "license": "BSD-3-Clause" }, "node_modules/@xtuc/long": { "version": "4.2.2", "resolved": "https://registry.npmjs.org/@xtuc/long/-/long-4.2.2.tgz", - "integrity": "sha512-NuHqBY1PB/D8xU6s/thBgOAiAP7HOYDQ32+BFZILJ8ivkUkAHQnWfn6WhL79Owj1qmUnoN/YPhktdIoucipkAQ==" + "integrity": "sha512-NuHqBY1PB/D8xU6s/thBgOAiAP7HOYDQ32+BFZILJ8ivkUkAHQnWfn6WhL79Owj1qmUnoN/YPhktdIoucipkAQ==", + "license": "Apache-2.0" }, "node_modules/accepts": { "version": "1.3.8", @@ -3936,9 +3954,10 @@ } }, "node_modules/acorn": { - "version": "8.11.3", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.11.3.tgz", - "integrity": "sha512-Y9rRfJG5jcKOE0CLisYbojUjIrIEE7AGMzA/Sm4BslANhbS+cDMpgBdcPT91oJ7OuJ9hYJBx59RjbhxVnrF8Xg==", + "version": "8.14.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.14.0.tgz", + "integrity": "sha512-cl669nCJTZBsL97OF4kUQm5g5hC2uihk0NxY3WENAC0TYdILVkAyHymAntgxGkl7K+t0cXIrH5siy5S4XkFycA==", + "license": "MIT", "bin": { "acorn": "bin/acorn" }, @@ -3946,14 +3965,6 @@ "node": ">=0.4.0" } }, - "node_modules/acorn-import-assertions": { - "version": "1.9.0", - "resolved": "https://registry.npmjs.org/acorn-import-assertions/-/acorn-import-assertions-1.9.0.tgz", - "integrity": "sha512-cmMwop9x+8KFhxvKrKfPYmN6/pKTYYHBqLa0DfvVZcKMJWNyWLnaqND7dx/qn66R7ewM1UX5XMaDVP5wlVTaVA==", - "peerDependencies": { - "acorn": "^8" - } - }, "node_modules/acorn-jsx": { "version": "5.3.2", "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz", @@ -4365,20 +4376,21 @@ } }, "node_modules/body-parser": { - "version": "1.20.1", - "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.1.tgz", - "integrity": "sha512-jWi7abTbYwajOytWCQc37VulmWiRae5RyTpaCyDcS5/lMdtwSz5lOpDE67srw/HYe35f1z3fDQw+3txg7gNtWw==", + "version": "1.20.3", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.3.tgz", + "integrity": "sha512-7rAxByjUMqQ3/bHJy7D6OGXvx/MMc4IqBn/X0fcM1QUcAItpZrBEYhWGem+tzXH90c+G01ypMcYJBO9Y30203g==", + "license": "MIT", "dependencies": { "bytes": "3.1.2", - "content-type": "~1.0.4", + "content-type": "~1.0.5", "debug": "2.6.9", "depd": "2.0.0", "destroy": "1.2.0", "http-errors": "2.0.0", "iconv-lite": "0.4.24", "on-finished": "2.4.1", - "qs": "6.11.0", - "raw-body": "2.5.1", + "qs": "6.13.0", + "raw-body": "2.5.2", "type-is": "~1.6.18", "unpipe": "1.0.0" }, @@ -4391,6 +4403,7 @@ "version": "3.1.2", "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "license": "MIT", "engines": { "node": ">= 0.8" } @@ -4399,6 +4412,7 @@ "version": "2.6.9", "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "license": "MIT", "dependencies": { "ms": "2.0.0" } @@ -4406,7 +4420,8 @@ "node_modules/body-parser/node_modules/ms": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==" + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", + "license": "MIT" }, "node_modules/bonjour-service": { "version": "1.2.1", @@ -4453,20 +4468,21 @@ } }, "node_modules/braces": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz", - "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==", + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", + "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", + "license": "MIT", "dependencies": { - "fill-range": "^7.0.1" + "fill-range": "^7.1.1" }, "engines": { "node": ">=8" } }, "node_modules/browserslist": { - "version": "4.23.3", - "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.23.3.tgz", - "integrity": "sha512-btwCFJVjI4YWDNfau8RhZ+B1Q/VLoUITrm3RlP6y1tYGWIOa+InuYiRGXUBXo8nA1qKmHMyLB/iVQg5TT4eFoA==", + "version": "4.24.2", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.24.2.tgz", + "integrity": "sha512-ZIc+Q62revdMcqC6aChtW4jz3My3klmCO1fEmINZY/8J3EpBg5/A/D0AKmBveUh6pgoeycoMkVMko84tuYS+Gg==", "funding": [ { "type": "opencollective", @@ -4481,11 +4497,12 @@ "url": "https://github.com/sponsors/ai" } ], + "license": "MIT", "dependencies": { - "caniuse-lite": "^1.0.30001646", - "electron-to-chromium": "^1.5.4", + "caniuse-lite": "^1.0.30001669", + "electron-to-chromium": "^1.5.41", "node-releases": "^2.0.18", - "update-browserslist-db": "^1.1.0" + "update-browserslist-db": "^1.1.1" }, "bin": { "browserslist": "cli.js" @@ -4544,13 +4561,19 @@ } }, "node_modules/call-bind": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.5.tgz", - "integrity": "sha512-C3nQxfFZxFRVoJoGKKI8y3MOEo129NQ+FgQ08iye+Mk4zNZZGdjfs06bVTr+DBSlA66Q2VEcMki/cUCP4SercQ==", + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.7.tgz", + "integrity": "sha512-GHTSNSYICQ7scH7sZ+M2rFopRoLh8t2bLSW6BbgrtLsahOIB5iyAVJf9GjWK3cYTDaMj4XdBpM1cA6pIS0Kv2w==", + "license": "MIT", "dependencies": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", "function-bind": "^1.1.2", - "get-intrinsic": "^1.2.1", - "set-function-length": "^1.1.1" + "get-intrinsic": "^1.2.4", + "set-function-length": "^1.2.1" + }, + "engines": { + "node": ">= 0.4" }, "funding": { "url": "https://github.com/sponsors/ljharb" @@ -4596,9 +4619,9 @@ } }, "node_modules/caniuse-lite": { - "version": "1.0.30001655", - "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001655.tgz", - "integrity": "sha512-jRGVy3iSGO5Uutn2owlb5gR6qsGngTw9ZTb4ali9f3glshcNmJ2noam4Mo9zia5P9Dk3jNNydy7vQjuE5dQmfg==", + "version": "1.0.30001677", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001677.tgz", + "integrity": "sha512-fmfjsOlJUpMWu+mAAtZZZHz7UEwsUxIIvu1TJfO1HqFQvB/B+ii0xr9B5HpbZY/mC4XZ8SvjHJqtAY6pDPQEog==", "funding": [ { "type": "opencollective", @@ -4612,7 +4635,8 @@ "type": "github", "url": "https://github.com/sponsors/ai" } - ] + ], + "license": "CC-BY-4.0" }, "node_modules/ccount": { "version": "2.0.1", @@ -5044,6 +5068,7 @@ "version": "1.0.5", "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "license": "MIT", "engines": { "node": ">= 0.6" } @@ -5054,9 +5079,10 @@ "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==" }, "node_modules/cookie": { - "version": "0.5.0", - "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.5.0.tgz", - "integrity": "sha512-YZ3GUyn/o8gfKJlnlX7g7xq4gyO6OSuhGPKaaGssGB2qgDUS0gPgtTvoyZLTt9Ab6dC4hfc9dV5arkvc/OCmrw==", + "version": "0.7.1", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.1.tgz", + "integrity": "sha512-6DnInpx7SJ2AK3+CTUE/ZM0vWTUboZCegxhC2xiIydHR9jNuTAASBrfEpHhiGOZw/nX51bHt6YQl8jsGo4y/0w==", + "license": "MIT", "engines": { "node": ">= 0.6" } @@ -5590,16 +5616,20 @@ } }, "node_modules/define-data-property": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.1.tgz", - "integrity": "sha512-E7uGkTzkk1d0ByLeSc6ZsFS79Axg+m1P/VsgYsxHgiuc3tFSj+MjMIwe90FC4lOAZzNBdY7kkO2P2wKdsQ1vgQ==", + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.4.tgz", + "integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==", + "license": "MIT", "dependencies": { - "get-intrinsic": "^1.2.1", - "gopd": "^1.0.1", - "has-property-descriptors": "^1.0.0" + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "gopd": "^1.0.1" }, "engines": { "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, "node_modules/define-lazy-prop": { @@ -5651,6 +5681,7 @@ "version": "2.0.0", "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "license": "MIT", "engines": { "node": ">= 0.8" } @@ -5667,6 +5698,7 @@ "version": "1.2.0", "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz", "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==", + "license": "MIT", "engines": { "node": ">= 0.8", "npm": "1.2.8000 || >= 1.4.16" @@ -5856,12 +5888,14 @@ "node_modules/ee-first": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", - "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==" + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", + "license": "MIT" }, "node_modules/electron-to-chromium": { - "version": "1.5.13", - "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.13.tgz", - "integrity": "sha512-lbBcvtIJ4J6sS4tb5TLp1b4LyfCdMkwStzXPyAgVgTRAsep4bvrAGaBOP7ZJtQMNJpSQ9SqG4brWOroNaQtm7Q==" + "version": "1.5.52", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.52.tgz", + "integrity": "sha512-xtoijJTZ+qeucLBDNztDOuQBE1ksqjvNjvqFoST3nGC7fSpqJ+X6BdTBaY5BHG+IhWWmpc6b/KfpeuEDupEPOQ==", + "license": "ISC" }, "node_modules/emoji-regex": { "version": "9.2.2", @@ -5891,17 +5925,19 @@ } }, "node_modules/encodeurl": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", - "integrity": "sha512-TPJXq8JqFaVYm2CWmPvnP2Iyo4ZSM7/QKcSmuMLDObfpH5fi7RUGmd/rTDf+rut/saiDiQEeVTNgAmJEdAOx0w==", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "license": "MIT", "engines": { "node": ">= 0.8" } }, "node_modules/enhanced-resolve": { - "version": "5.15.0", - "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.15.0.tgz", - "integrity": "sha512-LXYT42KJ7lpIKECr2mAXIaMldcNCh/7E0KBKOu4KSfkHmP+mZmSs+8V5gBAqisWBy0OO4W5Oyys0GO1Y8KtdKg==", + "version": "5.17.1", + "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.17.1.tgz", + "integrity": "sha512-LMHl3dXhTcfv8gM4kEzIUeTQ+7fpdA0l2tUf34BddXPkz2A5xJ5L/Pchd5BL6rdccM9QGvu0sWZzK1Z1t4wwyg==", + "license": "MIT", "dependencies": { "graceful-fs": "^4.2.4", "tapable": "^2.2.0" @@ -5929,6 +5965,27 @@ "is-arrayish": "^0.2.1" } }, + "node_modules/es-define-property": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.0.tgz", + "integrity": "sha512-jxayLKShrEqqzJ0eumQbVhTYQM27CfT1T35+gCgDFoL82JLsXqTJ76zv6A0YLOgEnLUMvLzsDsGIrl8NFpT2gQ==", + "license": "MIT", + "dependencies": { + "get-intrinsic": "^1.2.4" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, "node_modules/es-module-lexer": { "version": "1.4.1", "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.4.1.tgz", @@ -6129,6 +6186,7 @@ "version": "1.8.1", "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "license": "MIT", "engines": { "node": ">= 0.6" } @@ -6181,36 +6239,37 @@ } }, "node_modules/express": { - "version": "4.18.2", - "resolved": "https://registry.npmjs.org/express/-/express-4.18.2.tgz", - "integrity": "sha512-5/PsL6iGPdfQ/lKM1UuielYgv3BUoJfz1aUwU9vHZ+J7gyvwdQXFEBIEIaxeGf0GIcreATNyBExtalisDbuMqQ==", + "version": "4.21.1", + "resolved": "https://registry.npmjs.org/express/-/express-4.21.1.tgz", + "integrity": "sha512-YSFlK1Ee0/GC8QaO91tHcDxJiE/X4FbpAyQWkxAvG6AXCuR65YzK8ua6D9hvi/TzUfZMpc+BwuM1IPw8fmQBiQ==", + "license": "MIT", "dependencies": { "accepts": "~1.3.8", "array-flatten": "1.1.1", - "body-parser": "1.20.1", + "body-parser": "1.20.3", "content-disposition": "0.5.4", "content-type": "~1.0.4", - "cookie": "0.5.0", + "cookie": "0.7.1", "cookie-signature": "1.0.6", "debug": "2.6.9", "depd": "2.0.0", - "encodeurl": "~1.0.2", + "encodeurl": "~2.0.0", "escape-html": "~1.0.3", "etag": "~1.8.1", - "finalhandler": "1.2.0", + "finalhandler": "1.3.1", "fresh": "0.5.2", "http-errors": "2.0.0", - "merge-descriptors": "1.0.1", + "merge-descriptors": "1.0.3", "methods": "~1.1.2", "on-finished": "2.4.1", "parseurl": "~1.3.3", - "path-to-regexp": "0.1.7", + "path-to-regexp": "0.1.10", "proxy-addr": "~2.0.7", - "qs": "6.11.0", + "qs": "6.13.0", "range-parser": "~1.2.1", "safe-buffer": "5.2.1", - "send": "0.18.0", - "serve-static": "1.15.0", + "send": "0.19.0", + "serve-static": "1.16.2", "setprototypeof": "1.2.0", "statuses": "2.0.1", "type-is": "~1.6.18", @@ -6246,9 +6305,10 @@ "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==" }, "node_modules/express/node_modules/path-to-regexp": { - "version": "0.1.7", - "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz", - "integrity": "sha512-5DFkuoqlv1uYQKxy8omFBeJPQcdoE07Kv2sferDCrAq1ohOU+MSDswDIbnx3YAM60qIOnYa53wBhXW0EbMonrQ==" + "version": "0.1.10", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.10.tgz", + "integrity": "sha512-7lf7qcQidTku0Gu3YDPc8DJ1q7OOucfa/BSsIwjuh56VU7katFvuM8hULfkwB3Fns/rsVF7PwPKVw1sl5KQS9w==", + "license": "MIT" }, "node_modules/express/node_modules/range-parser": { "version": "1.2.1", @@ -6299,14 +6359,6 @@ "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==" }, - "node_modules/fast-url-parser": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/fast-url-parser/-/fast-url-parser-1.1.3.tgz", - "integrity": "sha512-5jOCVXADYNuRkKFzNJ0dCCewsZiYo0dz8QNYljkOpFC6r2U4OBmKtvm/Tsuh4w1YYdDqDb31a8TVhBJ2OJKdqQ==", - "dependencies": { - "punycode": "^1.3.2" - } - }, "node_modules/fastq": { "version": "1.16.0", "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.16.0.tgz", @@ -6422,9 +6474,10 @@ } }, "node_modules/fill-range": { - "version": "7.0.1", - "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz", - "integrity": "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==", + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", + "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", + "license": "MIT", "dependencies": { "to-regex-range": "^5.0.1" }, @@ -6433,12 +6486,13 @@ } }, "node_modules/finalhandler": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.2.0.tgz", - "integrity": "sha512-5uXcUVftlQMFnWC9qu/svkWv3GTd2PfUhK/3PLkYNAe7FbqJMt3515HaxE6eRL74GdsriiwujiawdaB1BpEISg==", + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.1.tgz", + "integrity": "sha512-6BN9trH7bp3qvnrRyzsBz+g3lZxTNZTbVO2EV1CS0WIcDbawYVdYvGflME/9QP0h0pYlCDBCTjYa9nZzMDpyxQ==", + "license": "MIT", "dependencies": { "debug": "2.6.9", - "encodeurl": "~1.0.2", + "encodeurl": "~2.0.0", "escape-html": "~1.0.3", "on-finished": "2.4.1", "parseurl": "~1.3.3", @@ -6453,6 +6507,7 @@ "version": "2.6.9", "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "license": "MIT", "dependencies": { "ms": "2.0.0" } @@ -6460,7 +6515,8 @@ "node_modules/finalhandler/node_modules/ms": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==" + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", + "license": "MIT" }, "node_modules/find-cache-dir": { "version": "4.0.0", @@ -6501,15 +6557,16 @@ } }, "node_modules/follow-redirects": { - "version": "1.15.5", - "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.5.tgz", - "integrity": "sha512-vSFWUON1B+yAw1VN4xMfxgn5fTUiaOzAJCKBwIIgT/+7CuGy9+r+5gITvP62j3RmaD5Ph65UaERdOSRGUzZtgw==", + "version": "1.15.9", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.9.tgz", + "integrity": "sha512-gew4GsXizNgdoRyqmyfMHyAmXsZDk6mHkSxZFCzW9gwlbtOW44CDtYavM+y+72qD/Vq2l550kMF52DT8fOLJqQ==", "funding": [ { "type": "individual", "url": "https://github.com/sponsors/RubenVerborgh" } ], + "license": "MIT", "engines": { "node": ">=4.0" }, @@ -6679,6 +6736,7 @@ "version": "0.5.2", "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==", + "license": "MIT", "engines": { "node": ">= 0.6" } @@ -6736,15 +6794,20 @@ } }, "node_modules/get-intrinsic": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.2.2.tgz", - "integrity": "sha512-0gSo4ml/0j98Y3lngkFEot/zhiCeWsbYIlZ+uZOVgzLyLaUw7wxUL+nCTP0XJvJg1AXulJRI3UJi8GsbDuxdGA==", + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.2.4.tgz", + "integrity": "sha512-5uYhsJH8VJBTv7oslg4BznJYhDoRI6waYCxMmCdnTrcCrHA/fCFKoTFz2JKKE0HdDFUF7/oQuhzumXJK7paBRQ==", + "license": "MIT", "dependencies": { + "es-errors": "^1.3.0", "function-bind": "^1.1.2", "has-proto": "^1.0.1", "has-symbols": "^1.0.3", "hasown": "^2.0.0" }, + "engines": { + "node": ">= 0.4" + }, "funding": { "url": "https://github.com/sponsors/ljharb" } @@ -6803,7 +6866,8 @@ "node_modules/glob-to-regexp": { "version": "0.4.1", "resolved": "https://registry.npmjs.org/glob-to-regexp/-/glob-to-regexp-0.4.1.tgz", - "integrity": "sha512-lkX1HJXwyMcprw/5YUZc2s7DrpAiHB21/V+E1rHUrVNokkvB6bqMzT0VfV6/86ZNabt1k14YOIaT7nDvOX3Iiw==" + "integrity": "sha512-lkX1HJXwyMcprw/5YUZc2s7DrpAiHB21/V+E1rHUrVNokkvB6bqMzT0VfV6/86ZNabt1k14YOIaT7nDvOX3Iiw==", + "license": "BSD-2-Clause" }, "node_modules/global-dirs": { "version": "3.0.1", @@ -7002,11 +7066,12 @@ } }, "node_modules/has-property-descriptors": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.1.tgz", - "integrity": "sha512-VsX8eaIewvas0xnvinAe9bw4WfIeODpGYikiWYLH+dma0Jw6KHYqWiWfhQlgOVK8D6PvjubK5Uc4P0iIhIcNVg==", + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz", + "integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==", + "license": "MIT", "dependencies": { - "get-intrinsic": "^1.2.2" + "es-define-property": "^1.0.0" }, "funding": { "url": "https://github.com/sponsors/ljharb" @@ -7454,6 +7519,7 @@ "version": "2.0.0", "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz", "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==", + "license": "MIT", "dependencies": { "depd": "2.0.0", "inherits": "2.0.4", @@ -7484,9 +7550,10 @@ } }, "node_modules/http-proxy-middleware": { - "version": "2.0.6", - "resolved": "https://registry.npmjs.org/http-proxy-middleware/-/http-proxy-middleware-2.0.6.tgz", - "integrity": "sha512-ya/UeJ6HVBYxrgYotAZo1KvPWlgB48kUJLDePFeneHsVujFaW5WNj2NgWCAE//B1Dl02BIfYlpNgBy8Kf8Rjmw==", + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/http-proxy-middleware/-/http-proxy-middleware-2.0.7.tgz", + "integrity": "sha512-fgVY8AV7qU7z/MmXJ/rxwbrtQH4jBQ9m7kp3llF0liB7glmFeVZFBepQb32T3y8n8k2+AEYuMPCpinYW+/CuRA==", + "license": "MIT", "dependencies": { "@types/http-proxy": "^1.17.8", "http-proxy": "^1.18.1", @@ -7541,6 +7608,7 @@ "version": "0.4.24", "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "license": "MIT", "dependencies": { "safer-buffer": ">= 2.1.2 < 3" }, @@ -7848,6 +7916,7 @@ "version": "7.0.0", "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "license": "MIT", "engines": { "node": ">=0.12.0" } @@ -8680,6 +8749,7 @@ "version": "0.3.0", "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==", + "license": "MIT", "engines": { "node": ">= 0.6" } @@ -8696,9 +8766,13 @@ } }, "node_modules/merge-descriptors": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.1.tgz", - "integrity": "sha512-cCi6g3/Zr1iqQi6ySbseM1Xvooa98N0w31jzUYrXPX2xqObmFGHJ0tQ5u74H3mVh7wLouTseZyYIq39g8cNp1w==" + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.3.tgz", + "integrity": "sha512-gaNvAS7TZ897/rVaZ0nMtAyxNyi/pdbjbAwUpFQpN70GqnVfOiXpeUUMKRBmzXaSQ8DdTX4/0ms62r2K+hE6mQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } }, "node_modules/merge-stream": { "version": "2.0.0", @@ -10393,11 +10467,12 @@ ] }, "node_modules/micromatch": { - "version": "4.0.5", - "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.5.tgz", - "integrity": "sha512-DMy+ERcEW2q8Z2Po+WNXuw3c5YaUSFjAO5GsJqfEl7UjvtIuFKO6ZrKvcItdy98dwFI2N1tg3zNIdKaQT+aNdA==", + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", + "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", + "license": "MIT", "dependencies": { - "braces": "^3.0.2", + "braces": "^3.0.3", "picomatch": "^2.3.1" }, "engines": { @@ -10408,6 +10483,7 @@ "version": "1.6.0", "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", + "license": "MIT", "bin": { "mime": "cli.js" }, @@ -10687,9 +10763,13 @@ } }, "node_modules/object-inspect": { - "version": "1.13.1", - "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.1.tgz", - "integrity": "sha512-5qoj1RUiKOMsCCNLV1CBiPYE10sziTsnmNxkAI/rZhiD63CF7IqdFGC/XzjWjpSgLf0LxXX3bDFIh0E18f6UhQ==", + "version": "1.13.2", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.2.tgz", + "integrity": "sha512-IRZSRuzJiynemAXPYtPe5BoI/RESNYR7TYm50MC5Mqbd3Jmw5y790sErYw3V6SryFJD64b74qQQs9wn5Bg/k3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, "funding": { "url": "https://github.com/sponsors/ljharb" } @@ -10728,6 +10808,7 @@ "version": "2.4.1", "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "license": "MIT", "dependencies": { "ee-first": "1.1.1" }, @@ -11017,9 +11098,10 @@ "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==" }, "node_modules/path-to-regexp": { - "version": "1.8.0", - "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-1.8.0.tgz", - "integrity": "sha512-n43JRhlUKUAlibEJhPeir1ncUID16QnEjNpwzNdO3Lm4ywrBpBZ5oLD0I6br9evr1Y9JTqwRtAh7JLoOzAQdVA==", + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-1.9.0.tgz", + "integrity": "sha512-xIp7/apCFJuUHdDLWe8O1HIkb0kQrOMb/0u6FXQjemHn/ii5LrIzU6bdECnsiTF/GjZkMEKg1xdiZwNqDYlZ6g==", + "license": "MIT", "dependencies": { "isarray": "0.0.1" } @@ -11811,11 +11893,6 @@ "integrity": "sha512-77DZwxQmxKnu3aR542U+X8FypNzbfJ+C5XQDk3uWjWxn6151aIMGthWYRXTqT1E5oJvg+ljaa2OJi+VfvCOQ8w==", "dev": true }, - "node_modules/punycode": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/punycode/-/punycode-1.4.1.tgz", - "integrity": "sha512-jmYNElW7yvO7TV33CjSmvSiE2yco3bV2czu/OzDKdMNVZQWfxCblURLhf+47syQRBntjfLdd/H0egrzIG+oaFQ==" - }, "node_modules/pupa": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/pupa/-/pupa-3.1.0.tgz", @@ -11831,11 +11908,12 @@ } }, "node_modules/qs": { - "version": "6.11.0", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.11.0.tgz", - "integrity": "sha512-MvjoMCJwEarSbUYk5O+nmoSzSutSsTwF85zcHPQ9OrlFoZOYIjaqBAJIqIXjptyD5vThxGq52Xu/MaJzRkIk4Q==", + "version": "6.13.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.13.0.tgz", + "integrity": "sha512-+38qI9SOr8tfZ4QmJNplMUxqjbe7LKvvZgWdExBOmd+egZTtjLB67Gu0HRX3u/XOq7UU2Nx6nsjvS16Z9uwfpg==", + "license": "BSD-3-Clause", "dependencies": { - "side-channel": "^1.0.4" + "side-channel": "^1.0.6" }, "engines": { "node": ">=0.6" @@ -11899,9 +11977,10 @@ } }, "node_modules/raw-body": { - "version": "2.5.1", - "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.1.tgz", - "integrity": "sha512-qqJBtEyVgS0ZmPGdCFPWJ3FreoqvG4MVQln/kCgF7Olq95IbOp0/BWyMwbdtn4VTvkM8Y7khCQ2Xgk/tcrCXig==", + "version": "2.5.2", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.2.tgz", + "integrity": "sha512-8zGqypfENjCIqGhgXToC8aB2r7YrBX+AQAfIPs/Mlk+BtPTztOvTS01NRW/3Eh60J+a48lt8qsCzirQ6loCVfA==", + "license": "MIT", "dependencies": { "bytes": "3.1.2", "http-errors": "2.0.0", @@ -11916,6 +11995,7 @@ "version": "3.1.2", "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "license": "MIT", "engines": { "node": ">= 0.8" } @@ -12741,7 +12821,8 @@ "node_modules/safer-buffer": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", - "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT" }, "node_modules/sax": { "version": "1.3.0", @@ -12854,9 +12935,10 @@ "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==" }, "node_modules/send": { - "version": "0.18.0", - "resolved": "https://registry.npmjs.org/send/-/send-0.18.0.tgz", - "integrity": "sha512-qqWzuOjSFOuqPjFe4NOsMLafToQQwBSOEpS+FwEt3A2V3vKubTquT3vmLTQpFgMXp8AlFWFuP1qKaJZOtPpVXg==", + "version": "0.19.0", + "resolved": "https://registry.npmjs.org/send/-/send-0.19.0.tgz", + "integrity": "sha512-dW41u5VfLXu8SJh5bwRmyYUbAoSB3c9uQh6L8h/KtsFREPWpbX1lrljJo186Jc4nmci/sGUZ9a0a0J2zgfq2hw==", + "license": "MIT", "dependencies": { "debug": "2.6.9", "depd": "2.0.0", @@ -12880,6 +12962,7 @@ "version": "2.6.9", "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "license": "MIT", "dependencies": { "ms": "2.0.0" } @@ -12887,17 +12970,29 @@ "node_modules/send/node_modules/debug/node_modules/ms": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==" + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", + "license": "MIT" + }, + "node_modules/send/node_modules/encodeurl": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", + "integrity": "sha512-TPJXq8JqFaVYm2CWmPvnP2Iyo4ZSM7/QKcSmuMLDObfpH5fi7RUGmd/rTDf+rut/saiDiQEeVTNgAmJEdAOx0w==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } }, "node_modules/send/node_modules/ms": { "version": "2.1.3", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", - "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" }, "node_modules/send/node_modules/range-parser": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "license": "MIT", "engines": { "node": ">= 0.6" } @@ -12911,24 +13006,25 @@ } }, "node_modules/serve-handler": { - "version": "6.1.5", - "resolved": "https://registry.npmjs.org/serve-handler/-/serve-handler-6.1.5.tgz", - "integrity": "sha512-ijPFle6Hwe8zfmBxJdE+5fta53fdIY0lHISJvuikXB3VYFafRjMRpOffSPvCYsbKyBA7pvy9oYr/BT1O3EArlg==", + "version": "6.1.6", + "resolved": "https://registry.npmjs.org/serve-handler/-/serve-handler-6.1.6.tgz", + "integrity": "sha512-x5RL9Y2p5+Sh3D38Fh9i/iQ5ZK+e4xuXRd/pGbM4D13tgo/MGwbttUk8emytcr1YYzBYs+apnUngBDFYfpjPuQ==", + "license": "MIT", "dependencies": { "bytes": "3.0.0", "content-disposition": "0.5.2", - "fast-url-parser": "1.1.3", "mime-types": "2.1.18", "minimatch": "3.1.2", "path-is-inside": "1.0.2", - "path-to-regexp": "2.2.1", + "path-to-regexp": "3.3.0", "range-parser": "1.2.0" } }, "node_modules/serve-handler/node_modules/path-to-regexp": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-2.2.1.tgz", - "integrity": "sha512-gu9bD6Ta5bwGrrU8muHzVOBFFREpp2iRkVfhBJahwJ6p6Xw20SjT0MxLnwkjOibQmGSYhiUnf2FLe7k+jcFmGQ==" + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-3.3.0.tgz", + "integrity": "sha512-qyCH421YQPS2WFDxDjftfc1ZR5WKQzVzqsp4n9M2kQhVOo/ByahFoUNJfl58kOcEGfQ//7weFTDhm+ss8Ecxgw==", + "license": "MIT" }, "node_modules/serve-index": { "version": "1.9.1", @@ -13001,29 +13097,32 @@ } }, "node_modules/serve-static": { - "version": "1.15.0", - "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.15.0.tgz", - "integrity": "sha512-XGuRDNjXUijsUL0vl6nSD7cwURuzEgglbOaFuZM9g3kwDXOWVTck0jLzjPzGD+TazWbboZYu52/9/XPdUgne9g==", + "version": "1.16.2", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.16.2.tgz", + "integrity": "sha512-VqpjJZKadQB/PEbEwvFdO43Ax5dFBZ2UECszz8bQ7pi7wt//PWe1P6MN7eCnjsatYtBT6EuiClbjSWP2WrIoTw==", + "license": "MIT", "dependencies": { - "encodeurl": "~1.0.2", + "encodeurl": "~2.0.0", "escape-html": "~1.0.3", "parseurl": "~1.3.3", - "send": "0.18.0" + "send": "0.19.0" }, "engines": { "node": ">= 0.8.0" } }, "node_modules/set-function-length": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.0.tgz", - "integrity": "sha512-4DBHDoyHlM1IRPGYcoxexgh67y4ueR53FKV1yyxwFMY7aCqcN/38M1+SwZ/qJQ8iLv7+ck385ot4CcisOAPT9w==", + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.2.tgz", + "integrity": "sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==", + "license": "MIT", "dependencies": { - "define-data-property": "^1.1.1", + "define-data-property": "^1.1.4", + "es-errors": "^1.3.0", "function-bind": "^1.1.2", - "get-intrinsic": "^1.2.2", + "get-intrinsic": "^1.2.4", "gopd": "^1.0.1", - "has-property-descriptors": "^1.0.1" + "has-property-descriptors": "^1.0.2" }, "engines": { "node": ">= 0.4" @@ -13032,7 +13131,8 @@ "node_modules/setprototypeof": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", - "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==" + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "license": "ISC" }, "node_modules/shallow-clone": { "version": "3.0.1", @@ -13094,13 +13194,18 @@ } }, "node_modules/side-channel": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.4.tgz", - "integrity": "sha512-q5XPytqFEIKHkGdiMIrY10mvLRvnQh42/+GoBlFW3b2LXLE2xxJpZFdm94we0BaoV3RwJyGqg5wS7epxTv0Zvw==", + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.6.tgz", + "integrity": "sha512-fDW/EZ6Q9RiO8eFG8Hj+7u/oW+XrPTIChwCOM2+th2A6OblDtYYIpve9m+KvI9Z4C9qSEXlaGR6bTEYHReuglA==", + "license": "MIT", "dependencies": { - "call-bind": "^1.0.0", - "get-intrinsic": "^1.0.2", - "object-inspect": "^1.9.0" + "call-bind": "^1.0.7", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.4", + "object-inspect": "^1.13.1" + }, + "engines": { + "node": ">= 0.4" }, "funding": { "url": "https://github.com/sponsors/ljharb" @@ -13300,6 +13405,7 @@ "version": "2.0.1", "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", + "license": "MIT", "engines": { "node": ">= 0.8" } @@ -13671,6 +13777,7 @@ "version": "5.0.1", "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "license": "MIT", "dependencies": { "is-number": "^7.0.0" }, @@ -13682,6 +13789,7 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "license": "MIT", "engines": { "node": ">=0.6" } @@ -13741,6 +13849,7 @@ "version": "1.6.18", "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", + "license": "MIT", "dependencies": { "media-typer": "0.3.0", "mime-types": "~2.1.24" @@ -13753,6 +13862,7 @@ "version": "1.52.0", "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "license": "MIT", "engines": { "node": ">= 0.6" } @@ -13761,6 +13871,7 @@ "version": "2.1.35", "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "license": "MIT", "dependencies": { "mime-db": "1.52.0" }, @@ -13976,14 +14087,15 @@ "version": "1.0.0", "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "license": "MIT", "engines": { "node": ">= 0.8" } }, "node_modules/update-browserslist-db": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.1.0.tgz", - "integrity": "sha512-EdRAaAyk2cUE1wOf2DkEhzxqOQvFOoRJFNS6NeyJ01Gp2beMRpBAINjM2iDXE3KCuKhwnvHIQCJm6ThL2Z+HzQ==", + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.1.1.tgz", + "integrity": "sha512-R8UzCaa9Az+38REPiJ1tXlImTJXlVfgHZsglwBD/k6nj76ctsH1E3q4doGrukiLQd3sGQYu56r5+lo5r94l29A==", "funding": [ { "type": "opencollective", @@ -13998,9 +14110,10 @@ "url": "https://github.com/sponsors/ai" } ], + "license": "MIT", "dependencies": { - "escalade": "^3.1.2", - "picocolors": "^1.0.1" + "escalade": "^3.2.0", + "picocolors": "^1.1.0" }, "bin": { "update-browserslist-db": "cli.js" @@ -14273,9 +14386,10 @@ } }, "node_modules/watchpack": { - "version": "2.4.0", - "resolved": "https://registry.npmjs.org/watchpack/-/watchpack-2.4.0.tgz", - "integrity": "sha512-Lcvm7MGST/4fup+ifyKi2hjyIAwcdI4HRgtvTpIUxBRhB+RFtUh8XtDOxUfctVCnhVi+QQj49i91OyvzkJl6cg==", + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/watchpack/-/watchpack-2.4.2.tgz", + "integrity": "sha512-TnbFSbcOCcDgjZ4piURLCbJ3nJhznVh9kw6F6iokjiFPl8ONxe9A6nMDVXDiNbrSfLILs6vB07F7wLBrwPYzJw==", + "license": "MIT", "dependencies": { "glob-to-regexp": "^0.4.1", "graceful-fs": "^4.1.2" @@ -14302,33 +14416,33 @@ } }, "node_modules/webpack": { - "version": "5.89.0", - "resolved": "https://registry.npmjs.org/webpack/-/webpack-5.89.0.tgz", - "integrity": "sha512-qyfIC10pOr70V+jkmud8tMfajraGCZMBWJtrmuBymQKCrLTRejBI8STDp1MCyZu/QTdZSeacCQYpYNQVOzX5kw==", + "version": "5.96.1", + "resolved": "https://registry.npmjs.org/webpack/-/webpack-5.96.1.tgz", + "integrity": "sha512-l2LlBSvVZGhL4ZrPwyr8+37AunkcYj5qh8o6u2/2rzoPc8gxFJkLj1WxNgooi9pnoc06jh0BjuXnamM4qlujZA==", + "license": "MIT", "dependencies": { - "@types/eslint-scope": "^3.7.3", - "@types/estree": "^1.0.0", - "@webassemblyjs/ast": "^1.11.5", - "@webassemblyjs/wasm-edit": "^1.11.5", - "@webassemblyjs/wasm-parser": "^1.11.5", - "acorn": "^8.7.1", - "acorn-import-assertions": "^1.9.0", - "browserslist": "^4.14.5", + "@types/eslint-scope": "^3.7.7", + "@types/estree": "^1.0.6", + "@webassemblyjs/ast": "^1.12.1", + "@webassemblyjs/wasm-edit": "^1.12.1", + "@webassemblyjs/wasm-parser": "^1.12.1", + "acorn": "^8.14.0", + "browserslist": "^4.24.0", "chrome-trace-event": "^1.0.2", - "enhanced-resolve": "^5.15.0", + "enhanced-resolve": "^5.17.1", "es-module-lexer": "^1.2.1", "eslint-scope": "5.1.1", "events": "^3.2.0", "glob-to-regexp": "^0.4.1", - "graceful-fs": "^4.2.9", + "graceful-fs": "^4.2.11", "json-parse-even-better-errors": "^2.3.1", "loader-runner": "^4.2.0", "mime-types": "^2.1.27", "neo-async": "^2.6.2", "schema-utils": "^3.2.0", "tapable": "^2.1.1", - "terser-webpack-plugin": "^5.3.7", - "watchpack": "^2.4.0", + "terser-webpack-plugin": "^5.3.10", + "watchpack": "^2.4.1", "webpack-sources": "^3.2.3" }, "bin": { @@ -14382,9 +14496,10 @@ } }, "node_modules/webpack-dev-middleware": { - "version": "5.3.3", - "resolved": "https://registry.npmjs.org/webpack-dev-middleware/-/webpack-dev-middleware-5.3.3.tgz", - "integrity": "sha512-hj5CYrY0bZLB+eTO+x/j67Pkrquiy7kWepMHmUMoPsmcUaeEnQJqFzHJOyxgWlq746/wUuA64p9ta34Kyb01pA==", + "version": "5.3.4", + "resolved": "https://registry.npmjs.org/webpack-dev-middleware/-/webpack-dev-middleware-5.3.4.tgz", + "integrity": "sha512-BVdTqhhs+0IfoeAf7EoH5WE+exCmqGerHfDM0IL096Px60Tq2Mn9MAbnaGUe6HiMa41KMCYF19gyzZmBcq/o4Q==", + "license": "MIT", "dependencies": { "colorette": "^2.0.10", "memfs": "^3.4.3", @@ -14489,9 +14604,10 @@ } }, "node_modules/webpack-dev-server/node_modules/ws": { - "version": "8.16.0", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.16.0.tgz", - "integrity": "sha512-HS0c//TP7Ina87TfiPUz1rQzMhHrl/SG2guqRcTOIUYD2q8uhUdNHZYJUaQ8aTGPzCh+c6oawMKW35nFl1dxyQ==", + "version": "8.18.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.18.0.tgz", + "integrity": "sha512-8VbfWfHLbbwu3+N6OKsOMpBdT4kXPDDB9cJk2bJ6mh9ucxdlnNvH1e+roYkKmN9Nxw2yjz7VzeO9oOz2zJ04Pw==", + "license": "MIT", "engines": { "node": ">=10.0.0" }, @@ -14733,9 +14849,10 @@ } }, "node_modules/ws": { - "version": "7.5.9", - "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.9.tgz", - "integrity": "sha512-F+P9Jil7UiSKSkppIiD94dN07AwvFixvLIj1Og1Rl9GGMuNipJnV9JzjD6XuqmAeiswGvUmNLjr5cFuXwNS77Q==", + "version": "7.5.10", + "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.10.tgz", + "integrity": "sha512-+dbF1tHwZpXcbOJdVOkzLDxZP1ailvSxM6ZweXTegylPny803bFhA+vqBYw4s31NSAk4S2Qz+AKXK9a4wkdjcQ==", + "license": "MIT", "engines": { "node": ">=8.3.0" }, From 2e5b5794e9b394405c127893100be21e008b45ad Mon Sep 17 00:00:00 2001 From: Test Date: Wed, 6 Nov 2024 11:31:53 -0800 Subject: [PATCH 63/96] feat: use bm25 for fts --- core/autocomplete/retrieval.ts | 12 +- core/context/retrieval/fullTextSearch.ts | 32 ----- .../pipelines/BaseRetrievalPipeline.ts | 82 +++++++++--- .../pipelines/NoRerankerRetrievalPipeline.ts | 15 ++- .../pipelines/RerankerRetrievalPipeline.ts | 27 ++-- core/context/retrieval/retrieval.ts | 6 +- core/indexing/FullTextSearchCodebaseIndex.ts | 125 +++++++++++------- core/package-lock.json | 64 +++++++++ core/package.json | 1 + extensions/vscode/package-lock.json | 1 + gui/package-lock.json | 1 + 11 files changed, 239 insertions(+), 127 deletions(-) delete mode 100644 core/context/retrieval/fullTextSearch.ts diff --git a/core/autocomplete/retrieval.ts b/core/autocomplete/retrieval.ts index 422b377bd..8cc92ddec 100644 --- a/core/autocomplete/retrieval.ts +++ b/core/autocomplete/retrieval.ts @@ -10,13 +10,11 @@ export async function fullTextRetrieve( const searchStrings = prefix.split("\n").slice(-3); const results: Chunk[] = []; searchStrings.forEach(async (searchString) => { - const chunks = await index.retrieve( - [indexTag], - searchString, - 3, - undefined, - undefined, - ); + const chunks = await index.retrieve({ + tags: [indexTag], + text: searchString, + n: 3, + }); results.push(...chunks); }); return results; diff --git a/core/context/retrieval/fullTextSearch.ts b/core/context/retrieval/fullTextSearch.ts deleted file mode 100644 index 9c52bd6b6..000000000 --- a/core/context/retrieval/fullTextSearch.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { BranchAndDir, Chunk } from "../../index.js"; -import { FullTextSearchCodebaseIndex } from "../../indexing/FullTextSearchCodebaseIndex.js"; - -export async function retrieveFts( - query: string, - n: number, - tags: BranchAndDir[], - filterDirectory: string | undefined, -): Promise { - const ftsIndex = new FullTextSearchCodebaseIndex(); - - let ftsResults: Chunk[] = []; - try { - if (query.trim() !== "") { - ftsResults = await ftsIndex.retrieve( - tags, - query - .trim() - .split(" ") - .map((element) => `"${element}"`) - .join(" OR "), - n, - filterDirectory, - undefined, - ); - } - return ftsResults; - } catch (e) { - console.warn("Error retrieving from FTS:", e); - return []; - } -} diff --git a/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts b/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts index 9495f1608..89323d9b2 100644 --- a/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts +++ b/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts @@ -1,14 +1,11 @@ -import { - BranchAndDir, - Chunk, - ContinueConfig, - IDE, - ILLM, -} from "../../../index.js"; -import { chunkDocument } from "../../../indexing/chunk/chunk.js"; -import { LanceDbIndex } from "../../../indexing/LanceDbIndex.js"; -import { retrieveFts } from "../fullTextSearch.js"; -import { recentlyEditedFilesCache } from "../recentlyEditedFilesCache.js"; +// @ts-ignore +import nlp from "wink-nlp-utils"; + +import { BranchAndDir, Chunk, ContinueConfig, IDE, ILLM } from "../../../"; +import { chunkDocument } from "../../../indexing/chunk/chunk"; +import { FullTextSearchCodebaseIndex } from "../../../indexing/FullTextSearchCodebaseIndex"; +import { LanceDbIndex } from "../../../indexing/LanceDbIndex"; +import { recentlyEditedFilesCache } from "../recentlyEditedFilesCache"; export interface RetrievalPipelineOptions { llm: ILLM; @@ -23,11 +20,18 @@ export interface RetrievalPipelineOptions { includeEmbeddings?: boolean; // Used to handle JB w/o an embeddings model } +export interface RetrievalPipelineRunArguments { + query: string; + tags: BranchAndDir[]; + filterDirectory?: string; +} + export interface IRetrievalPipeline { - run(options: RetrievalPipelineOptions): Promise; + run(args: RetrievalPipelineRunArguments): Promise; } export default class BaseRetrievalPipeline implements IRetrievalPipeline { + private ftsIndex = new FullTextSearchCodebaseIndex(); private lanceDbIndex: LanceDbIndex; constructor(protected readonly options: RetrievalPipelineOptions) { @@ -38,6 +42,49 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline { ); } + private getCleanedTrigrams( + query: RetrievalPipelineRunArguments["query"], + ): string[] { + let text = nlp.string.removeExtraSpaces(query); + text = nlp.string.stem(text); + + let tokens = nlp.string + .tokenize(text, true) + .filter((token: any) => token.tag === "word") + .map((token: any) => token.value); + + tokens = nlp.tokens.removeWords(tokens); + tokens = nlp.tokens.setOfWords(tokens); + + const cleanedTokens = [...tokens].join(" "); + const trigrams = nlp.string.ngram(cleanedTokens, 3); + + return trigrams; + } + + protected async retrieveFts( + args: RetrievalPipelineRunArguments, + n: number, + ): Promise { + try { + if (args.query.trim() === "") { + return []; + } + + const tokens = this.getCleanedTrigrams(args.query).join(" OR "); + + return await this.ftsIndex.retrieve({ + n, + text: tokens, + tags: args.tags, + directory: args.filterDirectory, + }); + } catch (e) { + console.warn("Error retrieving from FTS:", e); + return []; + } + } + protected async retrieveAndChunkRecentlyEditedFiles( n: number, ): Promise { @@ -75,15 +122,6 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline { return chunks.slice(0, n); } - protected async retrieveFts(input: string, n: number): Promise { - return retrieveFts( - input, - n, - this.options.tags, - this.options.filterDirectory, - ); - } - protected async retrieveEmbeddings( input: string, n: number, @@ -96,7 +134,7 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline { ); } - run(): Promise { + run(args: RetrievalPipelineRunArguments): Promise { throw new Error("Not implemented"); } } diff --git a/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts b/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts index 6caef72dd..052a1fce6 100644 --- a/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts +++ b/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts @@ -1,10 +1,13 @@ -import { Chunk } from "../../../index.js"; -import { requestFilesFromRepoMap } from "../repoMapRequest.js"; -import { deduplicateChunks } from "../util.js"; -import BaseRetrievalPipeline from "./BaseRetrievalPipeline.js"; +import { Chunk } from "../../../"; +import { requestFilesFromRepoMap } from "../repoMapRequest"; +import { deduplicateChunks } from "../util"; + +import BaseRetrievalPipeline, { + RetrievalPipelineRunArguments, +} from "./BaseRetrievalPipeline"; export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline { - async run(): Promise { + async run(args: RetrievalPipelineRunArguments): Promise { const { input, nFinal, filterDirectory, includeEmbeddings } = this.options; // We give 1/4 weight to recently edited files, 1/4 to full text search, @@ -15,7 +18,7 @@ export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline { let retrievalResults: Chunk[] = []; - const ftsChunks = await this.retrieveFts(input, ftsNFinal); + const ftsChunks = await this.retrieveFts(args, ftsNFinal); const embeddingsChunks = includeEmbeddings ? await this.retrieveEmbeddings(input, embeddingsNFinal) diff --git a/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts b/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts index 375f1b17b..6f28a4a89 100644 --- a/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts +++ b/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts @@ -1,17 +1,22 @@ -import { Chunk } from "../../../index.js"; -import { RETRIEVAL_PARAMS } from "../../../util/parameters.js"; -import { requestFilesFromRepoMap } from "../repoMapRequest.js"; -import { deduplicateChunks } from "../util.js"; -import BaseRetrievalPipeline from "./BaseRetrievalPipeline.js"; +import { Chunk } from "../../.."; +import { RETRIEVAL_PARAMS } from "../../../util/parameters"; +import { requestFilesFromRepoMap } from "../repoMapRequest"; +import { deduplicateChunks } from "../util"; + +import BaseRetrievalPipeline, { + RetrievalPipelineRunArguments, +} from "./BaseRetrievalPipeline"; export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline { - private async _retrieveInitial(): Promise { + private async _retrieveInitial( + args: RetrievalPipelineRunArguments, + ): Promise { const { input, nRetrieve, filterDirectory, includeEmbeddings } = this.options; let retrievalResults: Chunk[] = []; - const ftsChunks = await this.retrieveFts(input, nRetrieve); + const ftsChunks = await this.retrieveFts(args, nRetrieve); const embeddingsChunks = includeEmbeddings ? await this.retrieveEmbeddings(input, nRetrieve) : []; @@ -104,9 +109,9 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline { return results; } - async run(): Promise { - const intialResults = await this._retrieveInitial(); - const rankedResults = await this._rerank(this.options.input, intialResults); + async run(args: RetrievalPipelineRunArguments): Promise { + let results = await this._retrieveInitial(args); + results = await this._rerank(args.query, results); // // // Expand top reranked results // const expanded = await this._expandRankedResults(results); @@ -120,7 +125,7 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline { // TODO: stitch together results - return rankedResults; + return results; } } diff --git a/core/context/retrieval/retrieval.ts b/core/context/retrieval/retrieval.ts index a40e163a0..8aae10a41 100644 --- a/core/context/retrieval/retrieval.ts +++ b/core/context/retrieval/retrieval.ts @@ -93,7 +93,11 @@ export async function retrieveContextItemsFromEmbeddings( }; const pipeline = new pipelineType(pipelineOptions); - const results = await pipeline.run(); + const results = await pipeline.run({ + tags, + filterDirectory, + query: extras.fullInput, + }); if (results.length === 0) { throw new Error( diff --git a/core/indexing/FullTextSearchCodebaseIndex.ts b/core/indexing/FullTextSearchCodebaseIndex.ts index 27face898..82e4e822f 100644 --- a/core/indexing/FullTextSearchCodebaseIndex.ts +++ b/core/indexing/FullTextSearchCodebaseIndex.ts @@ -1,6 +1,7 @@ import { BranchAndDir, Chunk, IndexTag, IndexingProgressUpdate } from "../"; import { getBasename } from "../util/index"; import { RETRIEVAL_PARAMS } from "../util/parameters"; + import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex"; import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex"; import { @@ -10,10 +11,20 @@ import { type CodebaseIndex, } from "./types"; +export interface RetrieveConfig { + tags: BranchAndDir[]; + text: string; + n: number; + directory?: string; + filterPaths?: string[]; + bm25Threshold?: number; +} + export class FullTextSearchCodebaseIndex implements CodebaseIndex { relativeExpectedTime: number = 0.2; static artifactId = "sqliteFts"; artifactId: string = FullTextSearchCodebaseIndex.artifactId; + pathWeightMultiplier = 10.0; private async _createTables(db: DatabaseConnection) { await db.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS fts USING fts5( @@ -71,17 +82,17 @@ export class FullTextSearchCodebaseIndex implements CodebaseIndex { desc: `Indexing ${getBasename(item.path)}`, status: "indexing", }; - markComplete([item], IndexResultType.Compute); + await markComplete([item], IndexResultType.Compute); } // Add tag for (const item of results.addTag) { - markComplete([item], IndexResultType.AddTag); + await markComplete([item], IndexResultType.AddTag); } // Remove tag for (const item of results.removeTag) { - markComplete([item], IndexResultType.RemoveTag); + await markComplete([item], IndexResultType.RemoveTag); } // Delete @@ -93,63 +104,81 @@ export class FullTextSearchCodebaseIndex implements CodebaseIndex { await db.run("DELETE FROM fts WHERE path = ?", [item.path]); - markComplete([item], IndexResultType.Delete); + await markComplete([item], IndexResultType.Delete); } } - async retrieve( - tags: BranchAndDir[], - text: string, - n: number, - directory: string | undefined, - filterPaths: string[] | undefined, - bm25Threshold: number = RETRIEVAL_PARAMS.bm25Threshold, - ): Promise { + async retrieve(config: RetrieveConfig): Promise { const db = await SqliteDb.get(); - // Notice that the "chunks" artifactId is used because of linking between tables - const tagStrings = tags.map((tag) => { - return tagToString({ ...tag, artifactId: ChunkCodebaseIndex.artifactId }); - }); + const query = this.buildRetrieveQuery(config); + const parameters = this.getRetrieveQueryParameters(config); - const query = `SELECT fts_metadata.chunkId, fts_metadata.path, fts.content, rank - FROM fts - JOIN fts_metadata ON fts.rowid = fts_metadata.id - JOIN chunk_tags ON fts_metadata.chunkId = chunk_tags.chunkId - WHERE fts MATCH '${text.replace( - /\?/g, - "", - )}' AND chunk_tags.tag IN (${tagStrings.map(() => "?").join(",")}) - ${ - filterPaths - ? `AND fts_metadata.path IN (${filterPaths.map(() => "?").join(",")})` - : "" - } - ORDER BY rank - LIMIT ?`; + let results = await db.all(query, parameters); - let results = await db.all(query, [ - ...tagStrings, - ...(filterPaths || []), - Math.ceil(n), - ]); - - results = results.filter((result) => result.rank <= bm25Threshold); + results = results.filter( + (result) => + result.rank <= (config.bm25Threshold ?? RETRIEVAL_PARAMS.bm25Threshold), + ); const chunks = await db.all( `SELECT * FROM chunks WHERE id IN (${results.map(() => "?").join(",")})`, results.map((result) => result.chunkId), ); - return chunks.map((chunk) => { - return { - filepath: chunk.path, - index: chunk.index, - startLine: chunk.startLine, - endLine: chunk.endLine, - content: chunk.content, - digest: chunk.cacheKey, - }; - }); + return chunks.map((chunk) => ({ + filepath: chunk.path, + index: chunk.index, + startLine: chunk.startLine, + endLine: chunk.endLine, + content: chunk.content, + digest: chunk.cacheKey, + })); + } + + private buildTagFilter(tags: BranchAndDir[]): string { + const tagStrings = this.convertTags(tags); + + return `AND chunk_tags.tag IN (${tagStrings.map(() => "?").join(",")})`; + } + + private buildPathFilter(filterPaths: string[] | undefined): string { + if (!filterPaths || filterPaths.length === 0) { + return ""; + } + return `AND fts_metadata.path IN (${filterPaths.map(() => "?").join(",")})`; + } + + private buildRetrieveQuery(config: RetrieveConfig): string { + return ` + SELECT fts_metadata.chunkId, fts_metadata.path, fts.content, rank + FROM fts + JOIN fts_metadata ON fts.rowid = fts_metadata.id + JOIN chunk_tags ON fts_metadata.chunkId = chunk_tags.chunkId + WHERE fts MATCH ? + ${this.buildTagFilter(config.tags)} + ${this.buildPathFilter(config.filterPaths)} + ORDER BY bm25(fts, ${this.pathWeightMultiplier}) + LIMIT ? + `; + } + + private getRetrieveQueryParameters(config: RetrieveConfig) { + const { text, tags, filterPaths, n } = config; + const tagStrings = this.convertTags(tags); + + return [ + text.replace(/\?/g, ""), + ...tagStrings, + ...(filterPaths || []), + Math.ceil(n), + ]; + } + + private convertTags(tags: BranchAndDir[]): string[] { + // Notice that the "chunks" artifactId is used because of linking between tables + return tags.map((tag) => + tagToString({ ...tag, artifactId: ChunkCodebaseIndex.artifactId }), + ); } } diff --git a/core/package-lock.json b/core/package-lock.json index 9e3937c64..f218b1904 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -64,6 +64,7 @@ "vectordb": "^0.4.20", "web-tree-sitter": "^0.21.0", "win-ca": "^3.5.1", + "wink-nlp-utils": "^2.1.0", "workerpool": "^9.1.3", "yaml": "^2.4.2", "zod": "^3.23.8" @@ -14850,6 +14851,69 @@ "node": ">=4" } }, + "node_modules/wink-distance": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/wink-distance/-/wink-distance-2.0.2.tgz", + "integrity": "sha512-pyEhUB/OKFYcgOC4J6E+c+gwVA/8qg2s5n49mIcUsJZM5iDSa17uOxRQXR4rvfp+gbj55K/I08FwjFBwb6fq3g==", + "dependencies": { + "wink-helpers": "^2.0.0", + "wink-jaro-distance": "^2.0.0" + } + }, + "node_modules/wink-eng-lite-web-model": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/wink-eng-lite-web-model/-/wink-eng-lite-web-model-1.8.0.tgz", + "integrity": "sha512-PlSaw2tzQ2SrKYEaH6AbxIUCFnQ9H7FeReVluV9O9VpgfYYa+urttUoAgzDrVujeMkJtACAIY8eFIkQgbEMpPg==", + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/wink-helpers": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/wink-helpers/-/wink-helpers-2.0.0.tgz", + "integrity": "sha512-I/ZzXrHcNRXuoeFJmp2vMVqDI6UCK02Tds1WP4kSGAmx520gjL1BObVzF7d2ps24tyHIly9ngdB2jwhlFUjPvg==" + }, + "node_modules/wink-jaro-distance": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/wink-jaro-distance/-/wink-jaro-distance-2.0.0.tgz", + "integrity": "sha512-9bcUaXCi9N8iYpGWbFkf83OsBkg17r4hEyxusEzl+nnReLRPqxhB9YNeRn3g54SYnVRNXP029lY3HDsbdxTAuA==" + }, + "node_modules/wink-nlp": { + "version": "1.14.3", + "resolved": "https://registry.npmjs.org/wink-nlp/-/wink-nlp-1.14.3.tgz", + "integrity": "sha512-lvY5iCs3T8I34F8WKS70+2P0U9dWLn3vdPf/Z+m2VK14N7OmqnPzmHfh3moHdusajoQ37Em39z0IZB9K4x/96A==" + }, + "node_modules/wink-nlp-utils": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/wink-nlp-utils/-/wink-nlp-utils-2.1.0.tgz", + "integrity": "sha512-b7PcRhEBNxQmsmht70jLOkwYUyie3da4/cgEXL+CumYO5b/nwV+W7fuMXToh5BtGq1RABznmc2TGTp1Qf/JUXg==", + "dependencies": { + "wink-distance": "^2.0.1", + "wink-eng-lite-web-model": "^1.4.3", + "wink-helpers": "^2.0.0", + "wink-nlp": "^1.12.0", + "wink-porter2-stemmer": "^2.0.1", + "wink-tokenizer": "^5.2.3" + } + }, + "node_modules/wink-porter2-stemmer": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/wink-porter2-stemmer/-/wink-porter2-stemmer-2.0.1.tgz", + "integrity": "sha512-0g+RkkqhRXFmSpJQStVXW5N/WsshWpJXsoDRW7DwVkGI2uDT6IBCoq3xdH5p6IHLaC6ygk7RWUsUx4alKxoagQ==" + }, + "node_modules/wink-tokenizer": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/wink-tokenizer/-/wink-tokenizer-5.3.0.tgz", + "integrity": "sha512-O/yAw0g3FmSgeeQuYAJJfP7fVPB4A6ay0018qASh79aWmIOyPYy4j4r9EQT8xBjicja6lCLvgRVAybmEBaATQA==", + "dependencies": { + "emoji-regex": "^9.0.0" + } + }, + "node_modules/wink-tokenizer/node_modules/emoji-regex": { + "version": "9.2.2", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz", + "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==" + }, "node_modules/word-wrap": { "version": "1.2.5", "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz", diff --git a/core/package.json b/core/package.json index ed489d1f2..952a9503d 100644 --- a/core/package.json +++ b/core/package.json @@ -95,6 +95,7 @@ "vectordb": "^0.4.20", "web-tree-sitter": "^0.21.0", "win-ca": "^3.5.1", + "wink-nlp-utils": "^2.1.0", "workerpool": "^9.1.3", "yaml": "^2.4.2", "zod": "^3.23.8" diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index c39c6391c..466cd705e 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -149,6 +149,7 @@ "vectordb": "^0.4.20", "web-tree-sitter": "^0.21.0", "win-ca": "^3.5.1", + "wink-nlp-utils": "^2.1.0", "workerpool": "^9.1.3", "yaml": "^2.4.2", "zod": "^3.23.8" diff --git a/gui/package-lock.json b/gui/package-lock.json index b0be81c6c..5c0221a2f 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -151,6 +151,7 @@ "vectordb": "^0.4.20", "web-tree-sitter": "^0.21.0", "win-ca": "^3.5.1", + "wink-nlp-utils": "^2.1.0", "workerpool": "^9.1.3", "yaml": "^2.4.2", "zod": "^3.23.8" From ef2f20fac59fc86b211ff46fed84e504ec4e2f0c Mon Sep 17 00:00:00 2001 From: Test Date: Wed, 6 Nov 2024 13:46:50 -0800 Subject: [PATCH 64/96] Update CodeBlockToolbar.tsx --- gui/src/components/markdown/CodeBlockToolbar.tsx | 15 ++++----------- 1 file changed, 4 insertions(+), 11 deletions(-) diff --git a/gui/src/components/markdown/CodeBlockToolbar.tsx b/gui/src/components/markdown/CodeBlockToolbar.tsx index a01dd78d2..ac4c03bb2 100644 --- a/gui/src/components/markdown/CodeBlockToolbar.tsx +++ b/gui/src/components/markdown/CodeBlockToolbar.tsx @@ -131,7 +131,6 @@ function CodeBlockToolBar(props: CodeBlockToolBarProps) { const defaultModel = useSelector(defaultModelSelector); const isTerminal = isTerminalCodeBlock(props.language, props.text); const [isCopied, setIsCopied] = useState(false); - const [isApplying, setIsApplying] = useState(false); const streamIdRef = useRef(null); if (streamIdRef.current === null) { @@ -149,10 +148,11 @@ function CodeBlockToolBar(props: CodeBlockToolBarProps) { useWebviewListener( "applyCodeFromChat", async () => { - await ideMessenger.request("applyToCurrentFile", { + await ideMessenger.request("applyToFile", { curSelectedModelTitle: defaultModel.title, text: props.text, streamId: streamIdRef.current, + filepath: props.filepath, }); dispatch(incrementNextCodeBlockToApplyIndex({})); }, @@ -172,8 +172,6 @@ function CodeBlockToolBar(props: CodeBlockToolBarProps) { } async function onClickApply() { - if (isApplying) return; - if (isTerminal) { await ideMessenger.ide.runCommand(getTerminalCommand(props.text)); return; @@ -232,7 +230,6 @@ function CodeBlockToolBar(props: CodeBlockToolBarProps) { {!isJetBrains() && isTerminal && ( @@ -240,15 +237,11 @@ function CodeBlockToolBar(props: CodeBlockToolBarProps) { )} - {isApplying ? ( - - ) : ( - - )} + Date: Wed, 6 Nov 2024 15:47:04 -0800 Subject: [PATCH 65/96] remove test copy --- gui/src/components/mainInput/TipTapEditor.tsx | 1 - 1 file changed, 1 deletion(-) diff --git a/gui/src/components/mainInput/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor.tsx index dfaeaf607..98a5c11db 100644 --- a/gui/src/components/mainInput/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor.tsx @@ -863,7 +863,6 @@ function TipTapEditor(props: TipTapEditorProps) { event.preventDefault(); }} > -

{`${editorFocusedRef.current}`}

{props.header}
From 9a85a891818f0f2d012e0d8a0a881fab180cb27b Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Wed, 6 Nov 2024 16:17:40 -0800 Subject: [PATCH 66/96] clean up --- core/protocol/ide.ts | 1 - gui/src/components/mainInput/TipTapEditor.tsx | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/core/protocol/ide.ts b/core/protocol/ide.ts index 6a9f177d0..eda6bebfb 100644 --- a/core/protocol/ide.ts +++ b/core/protocol/ide.ts @@ -89,7 +89,6 @@ export type ToIdeFromWebviewOrCoreProtocol = { ]; logoutOfControlPlane: [undefined, void]; pathSep: [undefined, string]; - hideGUI: [undefined, void]; }; export type ToWebviewOrCoreFromIdeProtocol = { diff --git a/gui/src/components/mainInput/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor.tsx index 98a5c11db..01ee8dea6 100644 --- a/gui/src/components/mainInput/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor.tsx @@ -819,7 +819,7 @@ function TipTapEditor(props: TipTapEditorProps) { return ( { From 5a7f196fffc74696179edadb30e307a93254004a Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 7 Nov 2024 01:17:41 -0800 Subject: [PATCH 67/96] handle file change and delete on vscode and jetbrains --- .../ContinuePluginStartupActivity.kt | 30 +- .../ConfigJsonSchemaProviderFactory.kt | 2 +- .../src/main/resources/config_schema.json | 3293 ---------------- extensions/vscode/continue_rc_schema.json | 3303 ----------------- .../vscode/src/extension/VsCodeExtension.ts | 2 +- 5 files changed, 24 insertions(+), 6606 deletions(-) delete mode 100644 extensions/intellij/src/main/resources/config_schema.json delete mode 100644 extensions/vscode/continue_rc_schema.json diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt index 00c5d7b1c..509bc44ce 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt @@ -30,6 +30,11 @@ import javax.swing.* import com.intellij.openapi.components.service import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.roots.ModuleRootManager +import com.intellij.openapi.vfs.VirtualFileManager +import com.intellij.openapi.vfs.newvfs.BulkFileListener +import com.intellij.openapi.vfs.newvfs.events.VFileEvent +import com.intellij.openapi.vfs.newvfs.events.VFileDeleteEvent +import com.intellij.openapi.vfs.newvfs.events.VFileContentChangeEvent fun showTutorial(project: Project) { val tutorialFileName = getTutorialFileName() @@ -149,15 +154,24 @@ class ContinuePluginStartupActivity : StartupActivity, Disposable, DumbAware { }) // Handle file changes and deletions - reindex - connection.subscribe(VirtualFileManager.VFS_CHANGES, object : VirtualFileListener { - override fun fileDeleted(event: VirtualFileEvent) { - val data = mapOf("dirs" to listOf(event.filePath)) - continuePluginService.coreMessenger?.request("index/forceReIndex", data, null) { _ -> } - } + connection.subscribe(VirtualFileManager.VFS_CHANGES, object : BulkFileListener { + override fun after(events: List) { + // Collect all relevant paths for deletions + val deletedPaths = events.filterIsInstance() + .map { event -> event.file.path.split("/").dropLast(1).joinToString("/") } - override fun contentsChanged(event: VirtualFileEvent) { - val data = mapOf("dirs" to listOf(event.filePath)) - continuePluginService.coreMessenger?.request("index/forceReIndex", data, null) { _ -> } + // Collect all relevant paths for content changes + val changedPaths = events.filterIsInstance() + .map { event -> event.file.path.split("/").dropLast(1).joinToString("/") } + + // Combine both lists of paths for re-indexing + val allPaths = deletedPaths + changedPaths + + // Create a data map if there are any paths to re-index + if (allPaths.isNotEmpty()) { + val data = mapOf("dirs" to allPaths) + continuePluginService.coreMessenger?.request("index/forceReIndex", data, null) { _ -> } + } } }) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ConfigJsonSchemaProviderFactory.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ConfigJsonSchemaProviderFactory.kt index c303b26fb..e4e21b957 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ConfigJsonSchemaProviderFactory.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ConfigJsonSchemaProviderFactory.kt @@ -22,7 +22,7 @@ class ConfigJsonSchemaProviderFactory : JsonSchemaProviderFactory { class ConfigJsonSchemaFileProvider : JsonSchemaFileProvider { override fun isAvailable(file: VirtualFile): Boolean { - return path.endsWith("/.continue/config.json") + return file.path.endsWith(".continue/config.json") } override fun getName(): String { diff --git a/extensions/intellij/src/main/resources/config_schema.json b/extensions/intellij/src/main/resources/config_schema.json deleted file mode 100644 index a35b7999e..000000000 --- a/extensions/intellij/src/main/resources/config_schema.json +++ /dev/null @@ -1,3293 +0,0 @@ -{ - "title": "config.json", - "$ref": "#/definitions/SerializedContinueConfig", - "definitions": { - "BaseCompletionOptions": { - "title": "BaseCompletionOptions", - "type": "object", - "properties": { - "stream": { - "title": "Stream", - "description": "Whether to stream the LLM response. Currently only respected by the 'anthropic' provider. Otherwise will always stream.", - "type": "boolean", - "default": true - }, - "temperature": { - "title": "Temperature", - "description": "The temperature of the completion.", - "type": "number" - }, - "topP": { - "title": "Top P", - "description": "The topP of the completion.", - "type": "number" - }, - "topK": { - "title": "Top K", - "description": "The topK of the completion.", - "type": "integer" - }, - "presencePenalty": { - "title": "Presence Penalty", - "description": "The presence penalty Aof the completion.", - "type": "number" - }, - "frequencePenalty": { - "title": "Frequency Penalty", - "description": "The frequency penalty of the completion.", - "type": "number" - }, - "mirostat": { - "title": "Mirostat", - "description": "Enable Mirostat sampling, controlling perplexity during text generation (default: 0, 0 = disabled, 1 = Mirostat, 2 = Mirostat 2.0). Only available for Ollama, LM Studio, and llama.cpp providers", - "type": "number" - }, - "stop": { - "title": "Stop", - "description": "The stop tokens of the completion.", - "type": "array", - "items": { - "type": "string" - } - }, - "maxTokens": { - "title": "Max Tokens", - "description": "The maximum number of tokens to generate.", - "default": 600, - "type": "integer" - }, - "numThreads": { - "title": "Number of threads", - "description": "The number of threads used in the generation process. Only available for Ollama (this is the num_thread parameter)", - "type": "integer" - }, - "keepAlive": { - "title": "Ollama keep_alive", - "description": "The number of seconds after no requests are made to unload the model from memory. Defaults to 60*30 = 30min", - "type": "integer" - } - } - }, - "ClientCertificateOptions": { - "title": "ClientCertificateOptions", - "type": "object", - "properties": { - "cert": { - "title": "Cert Path", - "description": "Path to the client certificate file", - "type": "string" - }, - "key": { - "title": "Key Path", - "description": "Path to the client certificate key file", - "type": "string" - }, - "passphrase": { - "title": "Passphrase", - "description": "Passphrase for the client certificate key file", - "type": "string" - } - }, - "required": [ - "cert", - "key" - ] - }, - "RequestOptions": { - "title": "RequestOptions", - "type": "object", - "properties": { - "timeout": { - "title": "Timeout", - "description": "Set the timeout for each request to the LLM. If you are running a local LLM that takes a while to respond, you might want to set this to avoid timeouts.", - "default": 7200, - "type": "integer" - }, - "verifySsl": { - "title": "Verify Ssl", - "description": "Whether to verify SSL certificates for requests.", - "type": "boolean" - }, - "caBundlePath": { - "title": "Ca Bundle Path", - "description": "Path to a custom CA bundle to use when making the HTTP request", - "anyOf": [ - { - "type": "string" - }, - { - "type": "array", - "items": { - "type": "string" - } - } - ] - }, - "proxy": { - "title": "Proxy", - "description": "Proxy URL to use when making the HTTP request", - "type": "string" - }, - "headers": { - "title": "Headers", - "description": "Headers to use when making the HTTP request", - "type": "object", - "additionalProperties": { - "type": "string" - } - }, - "extraBodyProperties": { - "title": "Extra Body Properties", - "description": "This object will be merged with the body when making the HTTP requests", - "type": "object" - }, - "noProxy": { - "title": "No Proxy", - "description": "A list of hostnames for which Continue should not use the proxy specified in requestOptions.proxy", - "type": "array", - "items": { - "type": "string" - } - }, - "clientCertificate": { - "title": "Client Certificate", - "description": "Client certificate to use when making the HTTP request", - "$ref": "#/definitions/ClientCertificateOptions" - } - } - }, - "ModelDescription": { - "title": "ModelDescription", - "type": "object", - "properties": { - "title": { - "title": "Title", - "description": "The title you wish to give your model.", - "type": "string" - }, - "provider": { - "title": "Provider", - "description": "The provider of the model. This is used to determine the type of model, and how to interact with it.", - "enum": [ - "openai", - "free-trial", - "anthropic", - "cohere", - "bedrock", - "bedrockimport", - "sagemaker", - "together", - "ollama", - "huggingface-tgi", - "huggingface-inference-api", - "llama.cpp", - "replicate", - "gemini", - "lmstudio", - "llamafile", - "mistral", - "deepinfra", - "groq", - "fireworks", - "cloudflare", - "deepseek", - "azure", - "msty", - "watsonx", - "openrouter", - "sambanova", - "nvidia", - "vllm", - "cerebras", - "askSage", - "nebius", - "vertexai", - ], - "markdownEnumDescriptions": [ - "### OpenAI\nUse gpt-4, gpt-3.5-turbo, or any other OpenAI model. See [here](https://openai.com/product#made-for-developers) to obtain an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/openai)", - "### Free Trial\nNew users can try out Continue for free using a proxy server that securely makes calls to OpenAI using our API key. If you are ready to use your own API key or have used all 250 free uses, you can enter your API key in config.json where it says `apiKey=\"\"` or select another model provider.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/freetrial)", - "### Anthropic\nTo get started with Anthropic models, you first need to sign up for the open beta [here](https://claude.ai/login) to obtain an API key.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/anthropicllm)", - "### Anthropic Vertex AI\nTo get started you need to enable the [Vertex AI API](https://console.cloud.google.com/marketplace/product/google/aiplatform.googleapis.com) and set up the [Google Application Default Credentials](https://cloud.google.com/docs/authentication/provide-credentials-adc).", - "### Cohere\nTo use Cohere, visit the [Cohere dashboard](https://dashboard.cohere.com/api-keys) to create an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/cohere)", - "### Bedrock\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock)", - "### Bedrock Imported Models\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock)", - "### Sagemaker\nSagemaker is AWS' machine learning platform.", - "### Together\nTogether is a hosted service that provides extremely fast streaming of open-source language models. To get started with Together:\n1. Obtain an API key from [here](https://together.ai)\n2. Paste below\n3. Select a model preset\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/togetherllm)", - "### Ollama\nTo get started with Ollama, follow these steps:\n1. Download from [ollama.ai](https://ollama.ai/) and open the application\n2. Open a terminal and run `ollama run `. Example model names are `codellama:7b-instruct` or `llama2:7b-text`. You can find the full list [here](https://ollama.ai/library).\n3. Make sure that the model name used in step 2 is the same as the one in config.json (e.g. `model=\"codellama:7b-instruct\"`)\n4. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/ollama)", - "### Huggingface TGI\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/huggingfacetgi)", - "### Huggingface Inference API\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/huggingfaceinferenceapi)", - "### Llama.cpp\nllama.cpp comes with a [built-in server](https://github.com/ggerganov/llama.cpp/tree/master/examples/server#llamacppexampleserver) that can be run from source. To do this:\n\n1. Clone the repository with `git clone https://github.com/ggerganov/llama.cpp`.\n2. `cd llama.cpp`\n3. Run `make` to build the server.\n4. Download the model you'd like to use and place it in the `llama.cpp/models` directory (the best place to find models is [The Bloke on HuggingFace](https://huggingface.co/TheBloke))\n5. Run the llama.cpp server with the command below (replacing with the model you downloaded):\n\n```shell\n.\\server.exe -c 4096 --host 0.0.0.0 -t 16 --mlock -m models/codellama-7b-instruct.Q8_0.gguf\n```\n\nAfter it's up and running, you can start using Continue.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/llamacpp)", - "### Replicate\nReplicate is a hosted service that makes it easy to run ML models. To get started with Replicate:\n1. Obtain an API key from [here](https://replicate.com)\n2. Paste below\n3. Select a model preset\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/replicatellm)", - "### Gemini API\nTo get started with Google Makersuite, obtain your API key from [here](https://makersuite.google.com) and paste it below.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/geminiapi)", - "### Gemini API on Vertex AI\nTo get started you need to enable the [Vertex AI API](https://console.cloud.google.com/marketplace/product/google/aiplatform.googleapis.com) and set up the [Google Application Default Credentials](https://cloud.google.com/docs/authentication/provide-credentials-adc).", - "### LMStudio\nLMStudio provides a professional and well-designed GUI for exploring, configuring, and serving LLMs. It is available on both Mac and Windows. To get started:\n1. Download from [lmstudio.ai](https://lmstudio.ai/) and open the application\n2. Search for and download the desired model from the home screen of LMStudio.\n3. In the left-bar, click the '<->' icon to open the Local Inference Server and press 'Start Server'.\n4. Once your model is loaded and the server has started, you can begin using Continue.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/lmstudio)", - "### Llamafile\nTo get started with llamafiles, find and download a binary on their [GitHub repo](https://github.com/Mozilla-Ocho/llamafile#binary-instructions). Then run it with the following command:\n\n```shell\nchmod +x ./llamafile\n./llamafile\n```\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/llamafile)", - "### Mistral API\n\nTo get access to the Mistral API, obtain your API key from the [Mistral platform](https://docs.mistral.ai/)", - "### Mistral API on Vertex AI\nTo get started you need to enable the [Vertex AI API](https://console.cloud.google.com/marketplace/product/google/aiplatform.googleapis.com) and set up the [Google Application Default Credentials](https://cloud.google.com/docs/authentication/provide-credentials-adc).", - "### DeepInfra\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/deepinfra)", - "### Groq\nGroq provides extremely fast inference of open-source language models. To get started, obtain an API key from [their console](https://console.groq.com/keys).", - "### Fireworks\nFireworks is a fast inference engine for open-source language models. To get started, obtain an API key from [their console](https://fireworks.ai/api-keys).", - "### Cloudflare Workers AI\n\n[Reference](https://developers.cloudflare.com/workers-ai/)", - "### Deepseek\n Deepseek's API provides the best pricing for their state-of-the-art Deepseek Coder models. To get started, obtain an API key from [their console](https://platform.deepseek.com/api_keys)", - "### Azure OpenAI\n Azure OpenAI lets you securely run OpenAI's models on Azure. To get started, follow the steps [here](https://docs.continue.dev/reference/Model%20Providers/azure)", - "### Msty\nMsty is the simplest way to get started with online or local LLMs on all desktop platforms - Windows, Mac, and Linux. No fussing around, one-click and you are up and running. To get started, follow these steps:\n1. Download from [Msty.app](https://msty.app/), open the application, and click 'Setup Local AI'.\n2. Go to the Local AI Module page and download a model of your choice.\n3. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/Msty)", - "### IBM watsonx\nwatsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks.", - "### OpenRouter\nOpenRouter offers a single API to access almost any language model. To get started, obtain an API key from [their console](https://openrouter.ai/settings/keys).", - "### NVIDIA NIMs\nNVIDIA offers a single API to access almost any language model. To find out more, visit the [LLM APIs Documentation](https://docs.api.nvidia.com/nim/reference/llm-apis).\nFor information specific to getting a key, please check out the [docs here](https://docs.nvidia.com/nim/large-language-models/latest/getting-started.html#option-1-from-api-catalog)", - "### vLLM\nvLLM is a highly performant way of hosting LLMs for a team. To get started, follow their [quickstart](https://docs.vllm.ai/en/latest/getting_started/quickstart.html) to set up your server.", - "### Cerebras\nCerebras Inference uses specialized silicon to provides superfast inference. To get started, get your API keys from [their console](https://cloud.cerebras.ai/).", - "### Ask Sage\nAsk Sage is an agnostic hosted service that provides language models. To get started with Ask Sage:\n1. Obtain an API key from your account. For more information, visit [Ask Sage](https://docs.asksage.ai/).\n2. Paste the API key below.\n3. Select a model preset.\n> [Reference](https://docs.asksage.ai/)" - ], - "type": "string" - }, - "model": { - "title": "Model", - "description": "The name of the model. Used to autodetect prompt template.", - "type": "string" - }, - "apiKey": { - "title": "Api Key", - "description": "OpenAI, Anthropic, Cohere, Together, or other API key", - "type": "string" - }, - "apiBase": { - "title": "Api Base", - "description": "The base URL of the LLM API.", - "type": "string" - }, - "region": { - "title": "Region", - "description": "The region where the model is hosted", - "anyOf": [ - { - "enum": [ - "us-east-1", - "us-east-2", - "us-west-1", - "us-west-2", - "eu-west-1", - "eu-central-1", - "ap-southeast-1", - "ap-northeast-1", - "ap-south-1", - "us-central1", - "us-east1", - "us-east4", - "us-east5", - "us-west1", - "us-west4", - "us-south1", - "northamerica-northeast1", - "southamerica-east1", - "europe-central2", - "europe-north1", - "europe-west1", - "europe-west2", - "europe-west3", - "europe-west4", - "europe-west6", - "europe-west8", - "europe-west9", - "europe-southwest1", - "asia-east1", - "asia-east2", - "asia-south1", - "asia-northeast1", - "asia-northeast3", - "asia-southeast1", - "australia-southeast1", - "me-central1", - "me-central2", - "me-west1" - ], - "type": "string" - }, - { - "type": "string" - } - ] - }, - "profile": { - "title": "Profile", - "description": "The AWS security profile to use", - "type": "string" - }, - "modelArn": { - "title": "Profile", - "description": "The AWS arn for the imported model", - "type": "string" - }, - "contextLength": { - "title": "Context Length", - "description": "The maximum context length of the LLM in tokens, as counted by countTokens.", - "default": 2048, - "type": "integer" - }, - "maxStopWords": { - "title": "Max Stop Words", - "description": "The maximum number of stop words that the API will accept. You can set this if you are receiving an error about the number of stop words, but otherwise should leave it undefined.", - "type": "integer" - }, - "template": { - "title": "Template", - "description": "The chat template used to format messages. This is auto-detected for most models, but can be overridden here. Choose none if you are using vLLM or another server that automatically handles prompting.", - "enum": [ - "llama2", - "alpaca", - "zephyr", - "phi2", - "phind", - "anthropic", - "chatml", - "none", - "deepseek", - "openchat", - "xwin-coder", - "neural-chat", - "codellama-70b", - "llava", - "gemma", - "llama3" - ], - "type": "string" - }, - "promptTemplates": { - "title": "Prompt Templates", - "markdownDescription": "A mapping of prompt template name ('edit' is currently the only one used in Continue) to a string giving the prompt template. See [here](https://docs.continue.dev/model-setup/configuration#customizing-the-edit-prompt) for an example.", - "x-intellij-html-description": "A mapping of prompt template name ('edit' is currently the only one used in Continue) to a string giving the prompt template. See
here for an example.", - "type": "object", - "additionalProperties": { - "type": "string" - } - }, - "completionOptions": { - "title": "Completion Options", - "description": "Options for the completion endpoint. Read more about the completion options in the documentation.", - "default": { - "temperature": null, - "topP": null, - "topK": null, - "presencePenalty": null, - "frequencyPenalty": null, - "stop": null, - "maxTokens": 600 - }, - "allOf": [ - { - "$ref": "#/definitions/BaseCompletionOptions" - } - ] - }, - "systemMessage": { - "title": "System Message", - "description": "A system message that will always be followed by the LLM", - "type": "string" - }, - "requestOptions": { - "title": "Request Options", - "description": "Options for the HTTP request to the LLM.", - "default": { - "timeout": 7200, - "verifySsl": null, - "caBundlePath": null, - "proxy": null, - "headers": null, - "extraBodyProperties": null - }, - "allOf": [ - { - "$ref": "#/definitions/RequestOptions" - } - ] - }, - "apiType": { - "title": "Api Type", - "markdownDescription": "OpenAI API type, either `openai` or `azure`", - "x-intellij-html-description": "OpenAI API type, either openai or azure", - "enum": [ - "openai", - "azure" - ] - }, - "apiVersion": { - "title": "Api Version", - "description": "Azure OpenAI API version (e.g. 2023-07-01-preview)", - "type": "string" - }, - "engine": { - "title": "Engine", - "description": "Azure OpenAI engine", - "type": "string" - }, - "capabilities": { - "type": "object", - "description": "We will attempt to automatically detect the capabilities of the model based on its title and provider, but this may not always be accurate. You can override the model's capabilities here.", - "properties": { - "uploadImage": { - "type": "boolean", - "description": "Indicates whether the model can upload images." - } - } - } - }, - "required": [ - "title", - "provider", - "model" - ], - "allOf": [ - { - "if": { - "properties": { - "provider": { - "type": "str" - } - }, - "not": { - "required": [ - "provider" - ] - } - }, - "then": { - "properties": { - "model": { - "description": "Choose a provider first, then model options will be shown here." - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "openai", - "anthropic", - "cohere", - "gemini", - "huggingface-inference-api", - "replicate", - "together", - "cloudflare", - "sambanova", - "nebius" - ] - } - }, - "required": [ - "provider" - ] - }, - "then": { - "required": [ - "apiKey" - ] - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "bedrockimport" - ] - } - }, - "required": [ - "provider" - ] - }, - "then": { - "required": [ - "modelArn" - ] - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "huggingface-tgi", - "huggingface-inference-api" - ] - } - } - }, - "then": { - "required": [ - "apiBase" - ] - }, - "required": [ - "provider" - ] - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "openai" - ] - } - }, - "required": [ - "provider" - ] - }, - "then": { - "properties": { - "engine": { - "type": "string" - }, - "apiType": { - "type": "string" - }, - "apiVersion": { - "type": "string" - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "cloudflare" - ] - } - }, - "required": [ - "provider" - ] - }, - "then": { - "properties": { - "accountId": { - "type": "string" - }, - "aiGatewaySlug": { - "type": "string" - }, - "model": { - "anyOf": [ - { - "enum": [ - "@cf/meta/llama-3-8b-instruct", - "@hf/thebloke/deepseek-coder-6.7b-instruct-awq", - "@cf/deepseek-ai/deepseek-math-7b-instruct", - "@cf/thebloke/discolm-german-7b-v1-awq", - "@cf/tiiuae/falcon-7b-instruct", - "@cf/google/gemma-2b-it-lora", - "@hf/google/gemma-7b-it", - "@cf/google/gemma-7b-it-lora", - "@hf/nousresearch/hermes-2-pro-mistral-7b", - "@cf/meta/llama-2-7b-chat-fp16", - "@cf/meta/llama-2-7b-chat-int8", - "@cf/meta-llama/llama-2-7b-chat-hf-lora", - "@hf/thebloke/llama-2-13b-chat-awq", - "@hf/thebloke/llamaguard-7b-awq", - "@cf/mistral/mistral-7b-instruct-v0.1", - "@hf/mistral/mistral-7b-instruct-v0.2", - "@cf/mistral/mistral-7b-instruct-v0.2-lora", - "@hf/thebloke/neural-chat-7b-v3-1-awq", - "@cf/openchat/openchat-3.5-0106", - "@hf/thebloke/openhermes-2.5-mistral-7b-awq", - "@cf/microsoft/phi-2", - "@cf/qwen/qwen1.5-0.5b-chat", - "@cf/qwen/qwen1.5-1.8b-chat", - "@cf/qwen/qwen1.5-7b-chat-awq", - "@cf/qwen/qwen1.5-14b-chat-awq", - "@cf/defog/sqlcoder-7b-2", - "@hf/nexusflow/starling-lm-7b-beta", - "@cf/tinyllama/tinyllama-1.1b-chat-v1.0", - "@hf/thebloke/zephyr-7b-beta-awq", - "@hf/thebloke/deepseek-coder-6.7b-base-awq" - ] - }, - { - "type": "string" - } - ] - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "openai" - ] - } - }, - "required": [ - "provider" - ] - }, - "then": { - "properties": { - "model": { - "anyOf": [ - { - "enum": [ - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-4o", - "gpt-4o-mini", - "gpt-4", - "gpt-3.5-turbo-0613", - "gpt-4-32k", - "gpt-4-0125-preview", - "gpt-4-turbo", - "AUTODETECT" - ] - }, - { - "type": "string" - } - ] - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "replicate" - ] - } - }, - "required": [ - "provider" - ] - }, - "then": { - "properties": { - "model": { - "anyOf": [ - { - "enum": [ - "llama3.1-8b", - "llama3.1-70b", - "llama3.1-405b", - "llama3-8b", - "llama3-70b", - "codellama-7b", - "codellama-13b", - "codellama-34b", - "llama2-7b", - "llama2-13b" - ] - }, - { - "type": "string" - } - ] - }, - "markdownDescription": "Select a pre-defined option, or find an exact model ID from Replicate [here](https://replicate.com/collections/streaming-language-models).", - "x-intellij-html-description": "Select a pre-defined option, or find an exact model ID from Replicate here." - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "free-trial" - ] - } - }, - "required": [ - "provider" - ] - }, - "then": { - "properties": { - "model": { - "enum": [ - "gpt-4o", - "codestral-latest", - "llama3.1-70b", - "llama3.1-405b", - "gpt-3.5-turbo", - "gemini-pro", - "claude-3-5-sonnet-20240620", - "claude-3-haiku-20240307", - "AUTODETECT" - ] - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "openai" - ] - }, - "apiType": { - "not": { - "const": "azure" - } - } - }, - "required": [ - "provider" - ] - }, - "then": { - "properties": { - "model": { - "anyOf": [ - { - "enum": [ - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-4o", - "gpt-4o-mini", - "gpt-4", - "gpt-3.5-turbo-0613", - "gpt-4-32k", - "gpt-4-turbo", - "gpt-4-vision-preview", - "mistral-7b", - "mistral-8x7b", - "llama2-7b", - "llama2-13b", - "codellama-7b", - "codellama-13b", - "codellama-34b", - "codellama-70b", - "llama3-8b", - "llama3-70b", - "llama3.1-8b", - "llama3.1-70b", - "llama3.1-405b", - "phind-codellama-34b", - "wizardcoder-7b", - "wizardcoder-13b", - "wizardcoder-34b", - "zephyr-7b", - "codeup-13b", - "deepseek-7b", - "deepseek-33b", - "neural-chat-7b", - "deepseek-1b", - "stable-code-3b", - "starcoder-1b", - "starcoder-3b", - "starcoder2-3b", - "mistral-tiny", - "mistral-small", - "mistral-medium", - "AUTODETECT" - ] - }, - { - "type": "string" - } - ] - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "anthropic" - ] - } - }, - "required": [ - "provider" - ] - }, - "then": { - "properties": { - "cacheBehavior": { - "title": "Caching Behavior", - "description": "Options for the prompt caching", - "properties": { - "cacheSystemMessage": { - "type": "boolean" - }, - "cacheConversation": { - "type": "boolean" - } - } - }, - "model": { - "anyOf": [ - { - "enum": [ - "claude-2", - "claude-instant-1", - "claude-3-5-sonnet-20240620", - "claude-3-opus-20240229", - "claude-3-sonnet-20240229", - "claude-3-haiku-20240307", - "claude-2.1" - ] - }, - { - "type": "string" - } - ] - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "cohere" - ] - } - }, - "required": [ - "provider" - ] - }, - "then": { - "properties": { - "model": { - "enum": [ - "command-r", - "command-r-plus" - ] - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "bedrock" - ] - } - }, - "required": [ - "provider" - ] - }, - "then": { - "properties": { - "model": { - "anyOf": [ - { - "enum": [ - "claude-3-sonnet-20240229", - "claude-3-haiku-20240307", - "claude-2" - ] - }, - { - "type": "string" - } - ] - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "sagemaker" - ] - } - }, - "required": [ - "provider" - ] - }, - "then": { - "properties": { - "model": { - "description": "SageMaker endpoint name" - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "gemini" - ] - } - }, - "required": [ - "provider" - ] - }, - "then": { - "properties": { - "cacheBehavior": { - "title": "Caching Behavior", - "description": "Options for the prompt caching", - "properties": { - "cacheSystemMessage": { - "type": "boolean" - } - } - }, - "model": { - "enum": [ - "chat-bison-001", - "gemini-pro", - "gemini-1.5-pro-latest", - "gemini-1.5-pro", - "gemini-1.5-flash-latest", - "gemini-1.5-flash" - ] - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "together" - ] - } - }, - "required": [ - "provider" - ] - }, - "then": { - "properties": { - "model": { - "anyOf": [ - { - "enum": [ - "mistral-7b", - "mistral-8x7b", - "llama2-7b", - "llama2-13b", - "llama3-8b", - "llama3-70b", - "llama3.1-8b", - "llama3.1-70b", - "llama3.1-405b", - "codellama-7b", - "codellama-13b", - "codellama-34b", - "codellama-70b", - "phind-codellama-34b" - ] - }, - { - "type": "string" - } - ], - "markdownDescription": "Select a pre-defined option, or find an exact model string from Together AI [here](https://docs.together.ai/docs/inference-models).", - "x-intellij-html-description": "Select a pre-defined option, or find an exact model string from Together AI here." - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "deepinfra" - ] - } - }, - "required": [ - "provider" - ] - }, - "then": { - "properties": { - "model": { - "markdownDescription": "Find the model name you want to use from DeepInfra [here](https://deepinfra.com/models?type=text-generation).", - "x-intellij-html-description": "Find the model name you want to use from DeepInfra here." - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "huggingface-tgi", - "huggingface-inference-api", - "llama.cpp", - "text-gen-webui", - "llamafile" - ] - } - }, - "required": [ - "provider" - ] - }, - "then": { - "properties": { - "model": { - "anyOf": [ - { - "enum": [ - "mistral-7b", - "mistral-8x7b", - "llama2-7b", - "llama2-13b", - "codellama-7b", - "codellama-13b", - "codellama-34b", - "codellama-70b", - "llama3-8b", - "llama3-70b", - "llama3.1-8b", - "llama3.1-70b", - "llama3.1-405b", - "phind-codellama-34b", - "wizardcoder-7b", - "wizardcoder-13b", - "wizardcoder-34b", - "zephyr-7b", - "codeup-13b", - "deepseek-7b", - "deepseek-33b", - "neural-chat-7b", - "deepseek-1b", - "stable-code-3b", - "starcoder-1b", - "starcoder-3b", - "starcoder2-3b" - ] - }, - { - "type": "string" - } - ] - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "ollama" - ] - } - }, - "required": [ - "provider" - ] - }, - "then": { - "properties": { - "model": { - "anyOf": [ - { - "enum": [ - "mistral-7b", - "llama2-7b", - "llama2-13b", - "codellama-7b", - "codellama-13b", - "codellama-34b", - "codellama-70b", - "llama3-8b", - "llama3-70b", - "llama3.1-8b", - "llama3.1-70b", - "llama3.1-405b", - "phi-2", - "phind-codellama-34b", - "wizardcoder-7b", - "wizardcoder-13b", - "wizardcoder-34b", - "zephyr-7b", - "codeup-13b", - "deepseek-7b", - "deepseek-33b", - "neural-chat-7b", - "deepseek-1b", - "stable-code-3b", - "starcoder-1b", - "starcoder-3b", - "starcoder2-3b", - "AUTODETECT" - ] - }, - { - "type": "string" - } - ], - "markdownDescription": "Select a pre-defined option, or find the exact model tag for an Ollama model [here](https://ollama.ai/library).", - "x-intellij-html-description": "Select a pre-defined option, or find the exact model tag for an Ollama model here." - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "mistral" - ] - } - }, - "required": [ - "provider" - ] - }, - "then": { - "properties": { - "model": { - "enum": [ - "codestral-latest", - "codestral-mamba-latest", - "open-mistral-7b", - "open-mixtral-8x7b", - "open-mixtral-8x22b", - "mistral-small-latest", - "mistral-large-latest" - ] - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "vertexai" - ] - } - }, - "required": [ - "provider" - ] - }, - "then": { - "required": [ - "projectId", - "region" - ] - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "deepseek" - ] - } - }, - "required": [ - "provider" - ] - }, - "then": { - "properties": { - "cacheBehavior": { - "title": "Caching Behavior", - "description": "Options for the prompt caching", - "properties": { - "cacheSystemMessage": { - "type": "boolean" - }, - "cacheConversation": { - "type": "boolean" - } - } - }, - "model": { - "enum": [ - "deepseek-chat", - "deepseek-coder" - ] - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "groq" - ] - } - }, - "required": [ - "provider" - ] - }, - "then": { - "properties": { - "model": { - "enum": [ - "llama2-70b", - "mistral-8x7b", - "gemma", - "gemma2", - "llama3-8b", - "llama3-70b", - "llama3.1-8b", - "llama3.1-70b", - "llama3.1-405b", - "AUTODETECT" - ] - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "fireworks" - ] - } - }, - "required": [ - "provider" - ] - }, - "then": { - "properties": { - "model": { - "enum": [ - "starcoder-7b" - ] - } - } - } - }, - { - "if": { - "properties": { - "apiType": { - "const": "azure" - } - }, - "required": [ - "apiType" - ] - }, - "then": { - "required": [ - "engine", - "apiVersion", - "apiBase" - ] - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "openai" - ] - } - }, - "required": [ - "provider" - ] - }, - "then": { - "properties": { - "useLegacyCompletionsEndpoint": { - "type": "boolean" - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "const": "llamafile" - } - }, - "required": [ - "provider" - ] - }, - "then": { - "properties": { - "llamafileCommand": { - "type": "string" - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "cerebras" - ] - } - }, - "required": [ - "provider" - ] - }, - "then": { - "properties": { - "model": { - "enum": [ - "llama3.1-8b", - "llama3.1-70b" - ] - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "text-gen-webui" - ] - } - }, - "required": [ - "provider" - ] - }, - "then": { - "properties": { - "streamingUrl": { - "type": "string" - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "flowise" - ] - } - }, - "required": [ - "provider" - ] - }, - "then": { - "properties": { - "timeout": { - "title": "Timeout", - "description": "Set the timeout for each request to Flowise. If you are running a local version of Flowise it might takes a while to respond, you might want to set this to avoid timeouts.", - "default": 5000, - "type": "integer" - }, - "additionalHeaders": { - "description": "A list of additional headers", - "type": "array", - "items": { - "type": "object", - "properties": { - "key": { - "title": "Key", - "description": "Header key", - "type": "string" - }, - "value": { - "title": "Value", - "description": "Header value", - "type": "string" - } - }, - "required": [ - "key", - "value" - ] - } - }, - "additionalFlowiseConfiguration": { - "description": "A list of additional properties to be sent along `overrideConfig`", - "type": "array", - "items": { - "type": "object", - "properties": { - "key": { - "title": "Key", - "description": "Configuration Property key", - "type": "string" - }, - "value": { - "title": "Value", - "description": "Configuration Property value" - } - }, - "required": [ - "key", - "value" - ] - } - }, - "model": { - "anyOf": [ - { - "enum": [ - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-4o", - "gpt-4o-mini", - "gpt-4", - "gpt-3.5-turbo-0613", - "gpt-4-32k", - "gpt-4-turbo", - "gpt-4-vision-preview", - "mistral-7b", - "mistral-8x7b", - "llama2-7b", - "llama2-13b", - "codellama-7b", - "codellama-13b", - "codellama-34b", - "codellama-70b", - "llama3-8b", - "llama3-70b", - "llama3.1-8b", - "llama3.1-70b", - "llama3.1-405b", - "phind-codellama-34b", - "wizardcoder-7b", - "wizardcoder-13b", - "wizardcoder-34b", - "zephyr-7b", - "codeup-13b", - "deepseek-7b", - "deepseek-33b", - "claude-2", - "claude-instant-1", - "claude-3-5-sonnet-20240620", - "claude-3-opus-20240229", - "claude-3-sonnet-20240229", - "claude-3-haiku-20240307", - "claude-2.1", - "command-r", - "command-r-plus", - "chat-bison-001", - "gemini-pro", - "gemini-1.5-pro-latest", - "gemini-1.5-pro", - "gemini-1.5-flash-latest", - "gemini-1.5-flash", - "mistral-tiny", - "mistral-small", - "mistral-medium", - "deepseek-1b", - "stable-code-3b", - "starcoder-1b", - "starcoder-3b", - "starcoder2-3b" - ] - }, - { - "type": "string" - } - ] - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "watsonx" - ] - } - }, - "required": [ - "provider" - ] - }, - "then": { - "properties": { - "apiBase": { - "type": "string" - }, - "apiKey": { - "type": "string" - }, - "apiVersion": { - "type": "string" - }, - "projectId": { - "type": "string" - }, - "deploymentId": { - "type": "string" - }, - "model": { - "enum": [ - "ibm/granite-13b-chat-v2", - "ibm/granite-3b-code-instruct", - "ibm/granite-8b-code-instruct", - "ibm/granite-20b-code-instruct", - "ibm/granite-3b-code-instruct", - "ibm/granite-8b-code-instruct", - "ibm/granite-34b-code-instruct", - "ibm/granite-3-8b-instruct", - "ibm/granite-3-2b-instruct", - "mistralai/mistral-large", - "meta-llama/llama-3-8b-instruct", - "meta-llama/llama-3-70b-instruct" - ] - } - }, - "required": [ - "apiBase", - "apiKey", - "apiVersion" - ] - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "sambanova" - ] - } - }, - "required": [ - "provider" - ] - }, - "then": { - "properties": { - "model": { - "anyOf": [ - { - "enum": [ - "llama3.1-8b", - "llama3.1-70b", - "llama3.1-405b" - ] - }, - { - "type": "string" - } - ], - "description": "Select a pre-defined option." - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "ask-sage" - ] - } - }, - "required": [ - "provider" - ] - }, - "then": { - "properties": { - "model": { - "anyOf": [ - { - "enum": [ - "gpt-4o", - "gpt-4o-mini", - "gpt-4gov", - "gpt-4ogov", - "claude-3.5-sonnet", - "claude-3-opus", - "mistral-large", - "llama-3-chat", - "gemini-pro", - "AUTODETECT" - ] - }, - { - "type": "string" - } - ] - } - } - } - } - ] - }, - "ModelRoles": { - "title": "ModelRoles", - "type": "object", - "properties": { - "default": { - "title": "Default", - "description": "The default model. If other model roles are not set, they will fall back to default.", - "type": "string" - }, - "chat": { - "title": "Chat", - "description": "The model to use for chat. If not set, will fall back to default.", - "type": "string" - }, - "edit": { - "title": "Edit", - "description": "The model to use for editing. If not set, will fall back to default.", - "type": "string" - }, - "summarize": { - "title": "Summarize", - "description": "The model to use for summarization. If not set, will fall back to default.", - "type": "string" - } - }, - "required": [ - "default" - ] - }, - "SlashCommand": { - "title": "SlashCommand", - "type": "object", - "properties": { - "name": { - "title": "Name", - "anyOf": [ - { - "enum": [ - "issue", - "share", - "cmd", - "edit", - "comment", - "http", - "commit", - "review" - ], - "type": "string", - "markdownEnumDescriptions": [ - "Generate a link to a drafted GitHub issue", - "Export the current chat session to markdown", - "Generate a terminal command and paste it into the terminal", - "Edit the highlighted code with given instructions", - "Add comments to the highlighted code", - "Write a custom slash command at your own HTTP endpoint. Set 'url' in the params object for the endpoint you have setup.", - "Generate a commit message for the current changes", - "Review code and give feedback" - ] - }, - { - "type": "string" - } - ] - }, - "description": { - "title": "Description", - "type": "string" - }, - "step": { - "title": "Step", - "description": "This property is no longer required and has no effect. To use a built-in slash command, instead set the 'name' property to one of the pre-configured options.", - "type": "string" - }, - "params": { - "title": "Params", - "default": {}, - "type": "object" - } - }, - "allOf": [ - { - "if": { - "properties": { - "name": { - "enum": [ - "issue" - ] - } - } - }, - "then": { - "properties": { - "params": { - "properties": { - "repositoryUrl": { - "type": "string", - "description": "Enter the URL of the GitHub repository for which you want to generate the issue." - } - }, - "required": [ - "repositoryUrl" - ] - } - }, - "required": [ - "params" - ] - } - }, - { - "if": { - "properties": { - "name": { - "enum": [ - "edit" - ] - } - } - }, - "then": { - "properties": { - "params": { - "properties": { - "recap": { - "type": "boolean", - "markdownDescription": "If recap is set to `true`, Continue will generate a summary of the changes after making the edit.", - "x-intellij-html-description": "If recap is set to true, Continue will generate a summary of the changes after making the edit." - }, - "tokenLimit": { - "type": "integer", - "description": "By default, Continue doesn't let you edit extremely large ranges (beyond 1,200 tokens), because the LLM is unlikely to succeed. But if you would like to override this limit with the understanding of possible failure you may do so here." - } - } - } - } - } - }, - { - "if": { - "properties": { - "name": { - "enum": [ - "share" - ] - } - } - }, - "then": { - "properties": { - "params": { - "properties": { - "outputDir": { - "type": "string", - "markdownDescription": "If outputDir is set to `.` or begins with `./` or `.\\`, file will be saved to the current workspace or a subdirectory thereof, respectively. `~` can similarly be used to specify the user's home directory.", - "x-intellij-html-description": "If outputDir is set to . or begins with ./ or .\\, file will be saved to the current workspace or a subdirectory thereof, respectively. ~ can similarly be used to specify the user's home directory." - } - } - } - } - } - }, - { - "if": { - "properties": { - "name": { - "enum": [ - "commit" - ] - } - } - }, - "then": { - "properties": { - "params": { - "properties": { - "includeUnstaged": { - "type": "boolean", - "markdownDescription": "If set to `true`, then unstaged changes are also included in the prompt, otherwise only staged changes are included. Default is `false`.", - "x-intellij-html-description": "If set to true, then unstaged changes are also included in the prompt, otherwise only staged changes are included. Default is false." - } - } - } - } - } - } - ], - "required": [ - "name", - "description" - ] - }, - "CustomCommand": { - "title": "CustomCommand", - "type": "object", - "properties": { - "name": { - "title": "Name", - "type": "string" - }, - "prompt": { - "title": "Prompt", - "type": "string" - }, - "description": { - "title": "Description", - "type": "string" - } - }, - "required": [ - "name", - "prompt", - "description" - ] - }, - "ContextProviderWithParams": { - "title": "ContextProviderWithParams", - "type": "object", - "properties": { - "name": { - "title": "Name", - "anyOf": [ - { - "enum": [ - "diff", - "terminal", - "debugger", - "open", - "google", - "search", - "http", - "codebase", - "problems", - "folder", - "issue", - "docs", - "tree", - "highlights", - "outline", - "postgres", - "code", - "currentFile", - "url", - "database", - "os", - "repo-map", - "greptile", - "web" - ], - "markdownEnumDescriptions": [ - "Reference the contents of the current changes as given by `git diff`", - "Reference the last terminal command", - "Reference the contents of the local variables in the debugger with top n level (defaulting to 3) of call stack for that thread", - "Reference the contents of all open or pinned files.", - "Enter a search phrase and include the Google search results as context", - "Reference the results of a ripgrep search in your codebase", - "Write a custom context provider at your own HTTP endpoint. Set 'url' in the params object for the endpoint you have setup.", - "Use embeddings to automatically find relevant files from throughout the codebase", - "Reference all linting errors and warnings in the currently open file", - "Include important files from a folder in the prompt, as determined by similarity search", - "Reference GitHub issues from a repository", - "Retrieve important pages from a documentation website, as determined by similarity search", - "Display a file tree of the current workspace", - "Include important highlighted sections from your code", - "Include a repo map showing important code objects", - "References Postgres table schema and sample rows", - "Reference specific functions and classes from throughout your codebase", - "Reference the contents of the currently active file", - "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", - "Query your greptile index of the current repo", - "Search the web for sources related to your question" - ], - "type": "string" - }, - { - "type": "string" - } - ] - }, - "params": { - "title": "Params", - "default": {}, - "type": "object" - } - }, - "allOf": [ - { - "if": { - "properties": { - "name": { - "enum": [ - "discord" - ] - } - } - }, - "then": { - "allOf": [ - { - "properties": { - "params": { - "properties": { - "discordKey": { - "type": "string", - "description": "Your Discord bot token to access the Discord API. Required to fetch messages from servers." - }, - "guildId": { - "type": "string", - "description": "The ID of the guild (server) from which to fetch channels and messages." - }, - "channels": { - "type": "array", - "description": "A list of channel objects to search for messages", - "items": { - "type": "object", - "properties": { - "id": { - "type": "string", - "description": "The unique ID of the channel" - }, - "name": { - "type": "string", - "description": "The name of the channel" - } - }, - "required": [ - "id" - ] - } - } - }, - "required": [ - "discordKey" - ] - } - } - }, - { - "oneOf": [ - { - "properties": { - "params": { - "required": [ - "guildId" - ] - } - } - }, - { - "properties": { - "params": { - "required": [ - "channels" - ] - } - } - } - ] - } - ] - } - }, - { - "if": { - "properties": { - "name": { - "enum": [ - "google" - ] - } - } - }, - "then": { - "properties": { - "params": { - "properties": { - "serperApiKey": { - "type": "string", - "description": "Your API key for https://serper.dev in order to get Google search results" - } - }, - "required": [ - "serperApiKey" - ] - } - }, - "required": [ - "params" - ] - } - }, - { - "if": { - "properties": { - "name": { - "enum": [ - "web" - ] - } - } - }, - "then": { - "properties": { - "params": { - "properties": { - "n": { - "title": "N", - "description": "The number of results to return", - "default": 6, - "type": "integer" - } - } - } - }, - "required": [ - "params" - ] - } - }, - { - "if": { - "properties": { - "name": { - "enum": [ - "open" - ] - } - } - }, - "then": { - "properties": { - "params": { - "properties": { - "onlyPinned": { - "type": "boolean", - "description": "If set to true, only 'pinned' files will be included.", - "default": false - } - } - } - } - } - }, - { - "if": { - "properties": { - "name": { - "enum": [ - "issue" - ] - } - } - }, - "then": { - "properties": { - "params": { - "properties": { - "githubToken": { - "type": "string", - "description": "Your GitHub token to access the GitHub API. Required for private repositories." - }, - "repos": { - "type": "array", - "description": "A list of repositories to search for issues", - "items": { - "type": "object", - "properties": { - "owner": { - "type": "string", - "description": "The owner of the repository" - }, - "repo": { - "type": "string", - "description": "The name of the repository" - }, - "type": { - "type": "string", - "description": "The type of issues to search for", - "enum": [ - "open", - "closed", - "all" - ] - } - }, - "required": [ - "owner", - "repo" - ] - } - } - }, - "required": [ - "repos" - ] - } - }, - "required": [ - "params" - ] - } - }, - { - "if": { - "properties": { - "name": { - "enum": [ - "database" - ] - } - } - }, - "then": { - "properties": { - "params": { - "properties": { - "connections": { - "type": "array", - "description": "A list of database connections", - "items": { - "type": "object", - "properties": { - "name": { - "type": "string", - "description": "A unique name for this database connection" - }, - "connection_type": { - "type": "string", - "description": "The type of database (e.g., 'postgres', 'mysql')", - "enum": [ - "postgres", - "mysql", - "sqlite" - ] - }, - "connection": { - "type": "object", - "properties": { - "user": { - "type": "string", - "description": "The database user name" - }, - "host": { - "type": "string", - "description": "The host address of the database server" - }, - "database": { - "type": "string", - "description": "The name of the database to connect to" - }, - "password": { - "type": "string", - "description": "The password for the database user" - }, - "port": { - "type": "integer", - "description": "The port number to connect to at the host" - }, - "filename": { - "type": "string", - "description": "File location for simple file DB's" - } - }, - "required": [] - } - }, - "required": [ - "name", - "connection_type", - "connection" - ] - } - } - }, - "required": [ - "connections" - ] - } - }, - "required": [ - "params" - ] - } - }, - { - "if": { - "properties": { - "name": { - "enum": [ - "gitlab-mr" - ] - } - } - }, - "then": { - "properties": { - "params": { - "properties": { - "domain": { - "type": "string", - "description": "Your GitLab domain, will default to gitlab.com" - }, - "token": { - "type": "string", - "description": "Your private access token." - }, - "filterComments": { - "type": "boolean", - "description": "If you have code selected, filters out comments that aren't related to the selection." - } - }, - "required": [ - "token" - ] - } - }, - "required": [ - "params" - ] - } - }, - { - "if": { - "properties": { - "name": { - "enum": [ - "jira" - ] - } - } - }, - "then": { - "properties": { - "params": { - "properties": { - "domain": { - "type": "string", - "description": "Your Jira domain, for example company.atlassian.net." - }, - "email": { - "type": "string", - "description": "The email that you log into Jira with" - }, - "token": { - "type": "string", - "description": "Your atlassian API token from https://id.atlassian.com/manage-profile/security/api-tokens" - }, - "issueQuery": { - "type": "string", - "description": "Customize the query used to find Jira issues" - }, - "apiVersion": { - "type": "integer", - "markdownDescription": "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.", - "x-intellij-html-description": "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." - }, - "requestOptions": { - "title": "Request Options", - "description": "Options for the HTTPS request to Jira.", - "default": { - "timeout": 7200, - "verifySsl": null, - "caBundlePath": null, - "proxy": null, - "headers": null, - "extraBodyProperties": null - }, - "allOf": [ - { - "$ref": "#/definitions/RequestOptions" - } - ] - } - }, - "required": [ - "domain", - "token" - ] - } - }, - "required": [ - "params" - ] - } - }, - { - "if": { - "properties": { - "name": { - "enum": [ - "http" - ] - } - } - }, - "then": { - "properties": { - "params": { - "properties": { - "url": { - "type": "string", - "description": "The HTTP endpoint of your context provider server." - }, - "options": { - "title": "Custom Options", - "description": "Additional options to pass to your custom HTTP server.", - "type": "object" - } - }, - "required": [ - "url" - ] - } - }, - "required": [ - "params" - ] - } - }, - { - "if": { - "properties": { - "name": { - "enum": [ - "codebase", - "folder" - ] - } - } - }, - "then": { - "properties": { - "params": { - "properties": { - "nRetrieve": { - "title": "N Retrieve", - "description": "Number of results to initially retrieve from vector database", - "default": 50, - "type": "integer" - }, - "nFinal": { - "title": "N Final", - "description": "Final number of results to use after re-ranking", - "default": 10, - "type": "integer" - }, - "useReranking": { - "title": "Use Reranking", - "description": "Whether to use re-ranking, which will allow initial selection of nRetrieve results, then will use an LLM to select the top nFinal results. Disabling re-ranking will give faster, but less accurate, results.", - "default": true, - "type": "boolean" - } - } - } - } - } - }, - { - "if": { - "properties": { - "name": { - "enum": [ - "postgres" - ] - } - } - }, - "then": { - "properties": { - "params": { - "properties": { - "host": { - "title": "Host", - "description": "Database host", - "default": "localhost", - "type": "string" - }, - "port": { - "title": "Port", - "description": "Database port", - "default": 5432, - "type": "integer" - }, - "user": { - "title": "User", - "description": "Database user", - "default": "postgres", - "type": "string" - }, - "password": { - "title": "Password", - "description": "Database password", - "type": "string" - }, - "database": { - "title": "Database", - "description": "Database name", - "default": "postgres", - "type": "string" - }, - "schema": { - "title": "Schema", - "description": "Database schema", - "default": "public", - "type": "string" - }, - "sampleRows": { - "title": "Sample Rows", - "description": "Number of rows to sample from the database", - "default": 3, - "type": "integer" - } - } - } - }, - "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" - ] - }, - "SerializedContinueConfig": { - "title": "config.json", - "type": "object", - "properties": { - "docs": { - "title": "Docs", - "description": "A list of documentation sites to be indexed", - "type": "array", - "items": { - "type": "object", - "properties": { - "title": { - "type": "string", - "description": "The title of the documentation site" - }, - "startUrl": { - "type": "string", - "description": "The starting URL for indexing the documentation" - }, - "rootUrl": { - "type": "string", - "description": "The root URL of the documentation site" - }, - "maxDepth": { - "type": "integer", - "description": "The maximum depth to crawl the documentation site" - }, - "favicon": { - "type": "string", - "description": "The URL path to a favicon for the site - by default, it will be `/favicon.ico` path from the Start URL" - } - }, - "required": [ - "title", - "startUrl" - ] - } - }, - "allowAnonymousTelemetry": { - "title": "Allow Anonymous Telemetry", - "markdownDescription": "If this field is set to `true`, we will collect anonymous telemetry as described in the documentation page on telemetry. If set to `false`, we will not collect any data. Learn more in [the docs](https://docs.continue.dev/telemetry).", - "x-intellij-html-description": "If this field is set to `true`, we will collect anonymous telemetry as described in the documentation page on telemetry. If set to `false`, we will not collect any data. Learn more in the docs.", - "default": true, - "type": "boolean" - }, - "models": { - "title": "Models", - "markdownDescription": "Learn about setting up models in [the documentation](https://docs.continue.dev/model-setup/overview).", - "x-intellij-html-description": "Learn about setting up models in the documentation.", - "default": [ - { - "title": "GPT-4 (trial)", - "provider": "free-trial", - "model": "gpt-4", - "apiKey": "" - } - ], - "type": "array", - "items": { - "$ref": "#/definitions/ModelDescription" - } - }, - "systemMessage": { - "title": "System Message", - "description": "A system message that will always be followed by the LLM", - "type": "string" - }, - "completionOptions": { - "title": "Completion Options", - "description": "Default options for completion. These will be overriden by any options set for a specific model.", - "default": { - "temperature": null, - "topP": null, - "topK": null, - "presencePenalty": null, - "frequencyPenalty": null, - "stop": null, - "maxTokens": 600 - }, - "allOf": [ - { - "$ref": "#/definitions/BaseCompletionOptions" - } - ] - }, - "requestOptions": { - "title": "Request Options", - "description": "Default request options for all fetch requests from models and context providers. These will be overriden by any model-specific request options.", - "allOf": [ - { - "$ref": "#/definitions/RequestOptions" - } - ] - }, - "slashCommands": { - "title": "Slash Commands", - "markdownDescription": "An array of slash commands that let you take custom actions from the sidebar. Learn more in the [documentation](https://docs.continue.dev/customization/slash-commands).", - "x-intellij-html-description": "An array of slash commands that let you take custom actions from the sidebar. Learn more in the documentation.", - "default": [], - "type": "array", - "items": { - "$ref": "#/definitions/SlashCommand" - } - }, - "customCommands": { - "title": "Custom Commands", - "markdownDescription": "An array of custom commands that allow you to reuse prompts. Each has name, description, and prompt properties. When you enter `/` in the text input, it will act as a shortcut to the prompt. Learn more in the [documentation](https://docs.continue.dev/customization/slash-commands#custom-commands-use-natural-language).", - "x-intellij-html-description": "An array of custom commands that allow you to reuse prompts. Each has name, description, and prompt properties. When you enter / in the text input, it will act as a shortcut to the prompt. Learn more in the documentation.", - "default": [ - { - "name": "test", - "prompt": "{{{ input }}}\n\nWrite a comprehensive set of unit tests for the selected code. It should setup, run tests that check for correctness including important edge cases, and teardown. Ensure that the tests are complete and sophisticated. Give the tests just as chat output, don't edit any file.", - "description": "This is an example custom command. Open config.json to edit it and create more" - } - ], - "type": "array", - "items": { - "$ref": "#/definitions/CustomCommand" - } - }, - "contextProviders": { - "title": "Context Providers", - "markdownDescription": "A list of ContextProvider objects that can be used to provide context to the LLM by typing '@'. Read more about ContextProviders in [the documentation](https://docs.continue.dev/customization/context-providers).", - "x-intellij-html-description": "A list of ContextProvider objects that can be used to provide context to the LLM by typing '@'. Read more about ContextProviders in the documentation.", - "default": [], - "type": "array", - "items": { - "$ref": "#/definitions/ContextProviderWithParams" - } - }, - "userToken": { - "title": "User Token", - "description": "An optional token to identify the user.", - "type": "string" - }, - "disableIndexing": { - "title": "Disable Indexing", - "markdownDescription": "If set to `true`, Continue will not index the codebase. This is mainly used for debugging purposes.", - "x-intellij-html-description": "If set to true, Continue will not index the codebase. This is mainly used for debugging purposes.", - "default": false, - "type": "boolean" - }, - "disableSessionTitles": { - "title": "Disable Session Titles", - "markdownDescription": "If set to `true`, Continue will not make extra requests to the LLM to generate a summary title of each session.", - "x-intellij-html-description": "If set to true, Continue will not make extra requests to the LLM to generate a summary title of each session.", - "default": false, - "type": "boolean" - }, - "embeddingsProvider": { - "title": "Embeddings Provider", - "markdownDescription": "The method that will be used to generate codebase embeddings. The default is `transformers.js`, which will run locally in the browser. Learn about the other options [here](https://docs.continue.dev/features/codebase-embeddings#embeddings-providers).", - "x-intellij-html-description": "The method that will be used to generate codebase embeddings. The default is transformers.js, which will run locally in the browser. Learn about the other options here.

Note: transformers.js currently cannot be used in JetBrains.", - "type": "object", - "properties": { - "provider": { - "enum": [ - "huggingface-tei", - "transformers.js", - "ollama", - "openai", - "cohere", - "free-trial", - "gemini", - "voyage", - "nvidia", - "bedrock", - "sagemaker", - "nebius", - "vertexai" - ] - }, - "model": { - "type": "string" - }, - "apiKey": { - "type": "string" - }, - "apiBase": { - "type": "string" - }, - "requestOptions": { - "title": "Request Options", - "description": "Request options to be used in any fetch requests made by the embeddings provider", - "$ref": "#/definitions/RequestOptions" - }, - "maxChunkSize": { - "title": "Maximum Chunk Size", - "description": "The maximum number of tokens that each chunk of a document is allowed to have", - "type": "integer", - "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", - "$ref": "#/definitions/ModelDescription/properties/region" - }, - "profile": { - "title": "Profile", - "description": "The AWS security profile to use", - "type": "string" - } - }, - "required": [ - "provider" - ], - "allOf": [ - { - "if": { - "properties": { - "provider": { - "enum": [ - "cohere", - "voyage", - "nvidia", - "gemini" - ] - } - }, - "required": [ - "provider" - ] - }, - "then": { - "required": [ - "apiKey" - ] - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "sagemaker" - ] - } - }, - "required": [ - "provider" - ] - }, - "then": { - "properties": { - "model": { - "description": "SageMaker endpoint name" - } - }, - "required": [ - "model" - ] - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "vertexai" - ] - } - }, - "required": [ - "provider" - ] - }, - "then": { - "properties": { - "projectId": { - "description": "The name of your VertexAI project" - }, - "region": { - "description": "The region your VertexAI model is hosted in - typically central1", - "default": "central1" - }, - "model": { - "default": "text-embedding-004" - } - }, - "required": [ - "projectId", - "model", - "region" - ] - } - } - ] - }, - "reranker": { - "title": "Reranker", - "description": "The reranker is responsible for selecting the final results when retrieving snippets from your codebase.", - "type": "object", - "properties": { - "name": { - "enum": [ - "cohere", - "voyage", - "llm", - "free-trial", - "huggingface-tei" - ] - }, - "params": { - "type": "object" - } - }, - "required": [ - "name" - ], - "allOf": [ - { - "if": { - "properties": { - "name": { - "enum": [ - "cohere" - ] - } - }, - "required": [ - "name" - ] - }, - "then": { - "properties": { - "params": { - "type": "object", - "properties": { - "model": { - "enum": [ - "rerank-english-v3.0", - "rerank-multilingual-v3.0", - "rerank-english-v2.0", - "rerank-multilingual-v2.0" - ] - }, - "apiBase": { - "type": "string" - }, - "apiKey": { - "type": "string" - } - }, - "required": [ - "apiKey" - ] - } - } - } - }, - { - "if": { - "properties": { - "name": { - "enum": [ - "llm" - ] - } - }, - "required": [ - "name" - ] - }, - "then": { - "properties": { - "params": { - "type": "object", - "properties": { - "modelTitle": { - "type": "string" - } - }, - "required": [ - "modelTitle" - ] - } - } - } - }, - { - "if": { - "properties": { - "name": { - "enum": [ - "voyage" - ] - } - }, - "required": [ - "name" - ] - }, - "then": { - "properties": { - "params": { - "type": "object", - "properties": { - "apiKey": { - "type": "string" - }, - "model": { - "enum": [ - "rerank-lite-1", - "rerank-1", - "rerank-2", - "rerank-2-lite" - ] - } - }, - "required": [ - "apiKey" - ] - } - } - } - }, - { - "if": { - "properties": { - "name": { - "enum": [ - "huggingface-tei" - ] - } - }, - "required": [ - "name" - ] - }, - "then": { - "properties": { - "params": { - "type": "object", - "properties": { - "apiBase": { - "type": "string", - "default": "http://localhost:8080" - }, - "truncate": { - "type": "boolean", - "description": "Whether to truncate long sequences to the maximum allowed context length.", - "default": false - }, - "truncation_direction": { - "enum": [ - "Right", - "Left" - ], - "description": "Whether to truncate sequences from the left or right.", - "default": "Right" - } - }, - "required": [ - "apiBase" - ] - } - }, - "if": { - "properties": { - "truncate": { - "const": true - } - } - }, - "then": { - "required": [ - "truncation_direction" - ] - } - } - } - ] - }, - "tabAutocompleteModel": { - "title": "Tab Autocomplete Model", - "markdownDescription": "The model used for tab autocompletion. If undefined, Continue will default to using starcoder2:3b on a local Ollama instance.\n\n*IMPORTANT*:\n\nIf you use a custom model, ensure that it is one trained for fill-in-the-middle completions. An instruct model is typically not well-suited to autocomplete and you may receive unsatisfactory completions.", - "x-intellij-html-description": "The model used for tab autocompletion. If undefined, Continue will default to using starcoder2:3b on a local Ollama instance.

IMPORTANT:

If you use a custom model, ensure that it is one trained for fill-in-the-middle completions. An instruct model is typically not well-suited to autocomplete and you may receive unsatisfactory completions.", - "default": { - "title": "Tab Autocomplete Model", - "provider": "ollama", - "model": "deepseek-coder:1.3b-base" - }, - "oneOf": [ - { - "$ref": "#/definitions/ModelDescription" - }, - { - "type": "array", - "items": { - "$ref": "#/definitions/ModelDescription" - } - } - ] - }, - "tabAutocompleteOptions": { - "title": "TabAutocompleteOptions", - "type": "object", - "markdownDescription": "These options let you customize your tab-autocomplete experience. Read about all options in [the docs](https://docs.continue.dev/features/tab-autocomplete#configuration-options).", - "x-intellij-html-description": "These options let you customize your tab-autocomplete experience. Read about all options in the docs.", - "properties": { - "disable": { - "type": "boolean", - "description": "Disable tab autocomplete. This can also be done from the IDE settings.", - "default": false - }, - "useCopyBuffer": { - "type": "boolean", - "description": "Determines whether the copy buffer will be considered when contructing the prompt." - }, - "useFileSuffix": { - "type": "boolean", - "description": "Determines whether to use the file suffix in the prompt." - }, - "maxPromptTokens": { - "type": "number", - "description": "The maximum number of prompt tokens to use. A smaller number will yield faster completions, but less context." - }, - "debounceDelay": { - "type": "number", - "description": "The delay in milliseconds before triggering autocomplete after a keystroke." - }, - "maxSuffixPercentage": { - "type": "number", - "description": "The maximum percentage of the prompt that can be dedicated to the suffix." - }, - "prefixPercentage": { - "type": "number", - "description": "The percentage of the input that should be dedicated to the prefix." - }, - "transform": { - "type": "boolean", - "description": "Whether LLM output should be transformed to correct common model pitfalls." - }, - "template": { - "type": "string", - "description": "An optional template string to be used for autocomplete. It will be rendered with the Mustache templating language, and is passed the 'prefix' and 'suffix' variables." - }, - "multilineCompletions": { - "enum": [ - "always", - "never", - "auto" - ], - "description": "If set to true, Continue will only complete a single line at a time." - }, - "useCache": { - "type": "boolean", - "description": "Whether to cache completions" - }, - "onlyMyCode": { - "type": "boolean", - "description": "If set to true, Continue will not include any snippets from go to definition unless they are within your repository" - }, - "useOtherFiles": { - "type": "boolean", - "description": "Defaults to true. If set to false, Continue will not attempt to include snippets from other files." - }, - "disableInFiles": { - "description": "A list of files / glob patterns in which to disable tab autocomplete. For example, *.csv if you'd like to disable autocomplete in .csv files.", - "type": "array", - "items": { - "type": "string" - } - } - }, - "required": [] - }, - "ui": { - "type": "object", - "properties": { - "codeBlockToolbarPosition": { - "enum": [ - "top", - "bottom" - ], - "default": "top", - "description": "Whether to show the copy and apply code buttons at the top or bottom of code blocks in the sidebar." - }, - "fontSize": { - "type": "number" - }, - "displayRawMarkdown": { - "type": "boolean", - "description": "If set to true, we will display the model output as raw markdown.", - "default": false - }, - "showChatScrollbar": { - "title": "Show Chat Scrollbar", - "markdownDescription": "If set to `true`, a scrollbar will be displayed in the chat window to navigate through messages.", - "x-intellij-html-description": "If set to true, a scrollbar will be displayed in the chat window to navigate through messages.", - "default": false, - "type": "boolean" - } - } - }, - "analytics": { - "type": "object", - "properties": { - "provider": { - "type": "string", - "enum": [ - "posthog", - "logstash" - ], - "description": "The 3rd party analytics provider to use.", - "default": "posthog", - "markdownEnumDescriptions": [ - "### Posthog\nTo use Posthog, set up an account, obtain your client key, and enter it in the client key field.", - "### Logstash\nContinue's Logstash integration uses the TCP input at the specified URL" - ] - }, - "url": { - "type": "string", - "description": "The URL to which analytics will be sent" - }, - "clientKey": { - "type": "string", - "description": "The client key to use for analytics" - } - }, - "required": [ - "provider" - ], - "allOf": [ - { - "if": { - "properties": { - "provider": { - "enum": [ - "posthog" - ] - } - } - }, - "then": { - "required": [ - "clientKey" - ] - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "logstash" - ] - } - } - }, - "then": { - "required": [ - "url" - ] - } - } - ] - }, - "experimental": { - "type": "object", - "title": "Experimental", - "description": "Experimental properties are subject to change.", - "properties": { - "defaultContext": { - "type": "array", - "items": { - "allOf": [ - { - "$ref": "#/definitions/ContextProviderWithParams" - }, - { - "properties": { - "query": { - "type": "string", - "description": "Required for certain context providers, like 'url' in order to specify the input, or which of the dropdown items to select." - } - } - } - ] - } - }, - "modelRoles": { - "type": "object", - "properties": { - "inlineEdit": { - "description": "The 'title' property of the model you wish to use for inline edits", - "type": "string" - }, - "applyCodeBlock": { - "description": "The 'title' property of the model you wish to use for applying code blocks", - "type": "string" - }, - "repoMapFileSelection": { - "description": "The 'title' property of the model you wish to use for repo map file selections", - "type": "string" - } - } - }, - "readResponseTTS": { - "type": "boolean", - "default": true, - "description": "Automatically read LLM chat responses aloud using system TTS models" - }, - "promptPath": { - "type": "string" - }, - "quickActions": { - "type": "array", - "items": { - "type": "object", - "properties": { - "title": { - "type": "string", - "description": "The title of the quick action that will display in the Code Lens." - }, - "prompt": { - "type": "string", - "description": "The prompt that will be sent to the model when the quick action is invoked, with the function or class body concatenated." - }, - "sendToChat": { - "type": "boolean", - "description": "If true, the result of the quick action will be sent to the chat panel. If false, the streamed result will be inserted into the document.", - "default": false - } - }, - "required": [ - "prompt", - "title" - ] - }, - "description": "Quick actions are a way to add custom commands to the Code Lens of function and class declarations." - }, - "contextMenuPrompts": { - "type": "object", - "properties": { - "comment": { - "type": "string", - "default": "Write comments for this code. Do not change anything about the code itself." - }, - "docstring": { - "type": "string", - "default": "Write a docstring for this code. Do not change anything about the code itself." - }, - "fix": { - "type": "string", - "default": "Fix this code" - }, - "optimize": { - "type": "string", - "default": "Optimize this code" - }, - "fixGrammar": { - "type": "string", - "default": "If there are any grammar or spelling mistakes in this writing, fix them. Do not make other large changes to the writing." - } - } - } - } - } - } - } - } -} \ No newline at end of file diff --git a/extensions/vscode/continue_rc_schema.json b/extensions/vscode/continue_rc_schema.json deleted file mode 100644 index d3cf24b2f..000000000 --- a/extensions/vscode/continue_rc_schema.json +++ /dev/null @@ -1,3303 +0,0 @@ -{ - "title": "config.json", - "$ref": "#/definitions/SerializedContinueConfig", - "definitions": { - "BaseCompletionOptions": { - "title": "BaseCompletionOptions", - "type": "object", - "properties": { - "stream": { - "title": "Stream", - "description": "Whether to stream the LLM response. Currently only respected by the 'anthropic' provider. Otherwise will always stream.", - "type": "boolean", - "default": true - }, - "temperature": { - "title": "Temperature", - "description": "The temperature of the completion.", - "type": "number" - }, - "topP": { - "title": "Top P", - "description": "The topP of the completion.", - "type": "number" - }, - "topK": { - "title": "Top K", - "description": "The topK of the completion.", - "type": "integer" - }, - "presencePenalty": { - "title": "Presence Penalty", - "description": "The presence penalty Aof the completion.", - "type": "number" - }, - "frequencePenalty": { - "title": "Frequency Penalty", - "description": "The frequency penalty of the completion.", - "type": "number" - }, - "mirostat": { - "title": "Mirostat", - "description": "Enable Mirostat sampling, controlling perplexity during text generation (default: 0, 0 = disabled, 1 = Mirostat, 2 = Mirostat 2.0). Only available for Ollama, LM Studio, and llama.cpp providers", - "type": "number" - }, - "stop": { - "title": "Stop", - "description": "The stop tokens of the completion.", - "type": "array", - "items": { - "type": "string" - } - }, - "maxTokens": { - "title": "Max Tokens", - "description": "The maximum number of tokens to generate.", - "default": 600, - "type": "integer" - }, - "numThreads": { - "title": "Number of threads", - "description": "The number of threads used in the generation process. Only available for Ollama (this is the num_thread parameter)", - "type": "integer" - }, - "keepAlive": { - "title": "Ollama keep_alive", - "description": "The number of seconds after no requests are made to unload the model from memory. Defaults to 60*30 = 30min", - "type": "integer" - } - } - }, - "ClientCertificateOptions": { - "title": "ClientCertificateOptions", - "type": "object", - "properties": { - "cert": { - "title": "Cert Path", - "description": "Path to the client certificate file", - "type": "string" - }, - "key": { - "title": "Key Path", - "description": "Path to the client certificate key file", - "type": "string" - }, - "passphrase": { - "title": "Passphrase", - "description": "Passphrase for the client certificate key file", - "type": "string" - } - }, - "required": [ - "cert", - "key" - ] - }, - "RequestOptions": { - "title": "RequestOptions", - "type": "object", - "properties": { - "timeout": { - "title": "Timeout", - "description": "Set the timeout for each request to the LLM. If you are running a local LLM that takes a while to respond, you might want to set this to avoid timeouts.", - "default": 7200, - "type": "integer" - }, - "verifySsl": { - "title": "Verify Ssl", - "description": "Whether to verify SSL certificates for requests.", - "type": "boolean" - }, - "caBundlePath": { - "title": "Ca Bundle Path", - "description": "Path to a custom CA bundle to use when making the HTTP request", - "anyOf": [ - { - "type": "string" - }, - { - "type": "array", - "items": { - "type": "string" - } - } - ] - }, - "proxy": { - "title": "Proxy", - "description": "Proxy URL to use when making the HTTP request", - "type": "string" - }, - "headers": { - "title": "Headers", - "description": "Headers to use when making the HTTP request", - "type": "object", - "additionalProperties": { - "type": "string" - } - }, - "extraBodyProperties": { - "title": "Extra Body Properties", - "description": "This object will be merged with the body when making the HTTP requests", - "type": "object" - }, - "noProxy": { - "title": "No Proxy", - "description": "A list of hostnames for which Continue should not use the proxy specified in requestOptions.proxy", - "type": "array", - "items": { - "type": "string" - } - }, - "clientCertificate": { - "title": "Client Certificate", - "description": "Client certificate to use when making the HTTP request", - "$ref": "#/definitions/ClientCertificateOptions" - } - } - }, - "ModelDescription": { - "title": "ModelDescription", - "type": "object", - "properties": { - "title": { - "title": "Title", - "description": "The title you wish to give your model.", - "type": "string" - }, - "provider": { - "title": "Provider", - "description": "The provider of the model. This is used to determine the type of model, and how to interact with it.", - "enum": [ - "openai", - "free-trial", - "anthropic", - "cohere", - "bedrock", - "bedrockimport", - "sagemaker", - "together", - "ollama", - "huggingface-tgi", - "huggingface-inference-api", - "llama.cpp", - "replicate", - "gemini", - "lmstudio", - "llamafile", - "mistral", - "deepinfra", - "groq", - "fireworks", - "cloudflare", - "deepseek", - "azure", - "msty", - "watsonx", - "openrouter", - "sambanova", - "nvidia", - "vllm", - "cerebras", - "askSage", - "nebius", - "vertexai" - ], - "markdownEnumDescriptions": [ - "### OpenAI\nUse gpt-4, gpt-3.5-turbo, or any other OpenAI model. See [here](https://openai.com/product#made-for-developers) to obtain an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/openai)", - "### Free Trial\nNew users can try out Continue for free using a proxy server that securely makes calls to OpenAI using our API key. If you are ready to use your own API key or have used all 250 free uses, you can enter your API key in config.json where it says `apiKey=\"\"` or select another model provider.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/freetrial)", - "### Anthropic\nTo get started with Anthropic models, you first need to sign up for the open beta [here](https://claude.ai/login) to obtain an API key.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/anthropicllm)", - "### Anthropic Vertex AI\nTo get started you need to enable the [Vertex AI API](https://console.cloud.google.com/marketplace/product/google/aiplatform.googleapis.com) and set up the [Google Application Default Credentials](https://cloud.google.com/docs/authentication/provide-credentials-adc).", - "### Cohere\nTo use Cohere, visit the [Cohere dashboard](https://dashboard.cohere.com/api-keys) to create an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/cohere)", - "### Bedrock\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock)", - "### Bedrock Imported Models\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock)", - "### Sagemaker\nSagemaker is AWS' machine learning platform.", - "### Together\nTogether is a hosted service that provides extremely fast streaming of open-source language models. To get started with Together:\n1. Obtain an API key from [here](https://together.ai)\n2. Paste below\n3. Select a model preset\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/togetherllm)", - "### Ollama\nTo get started with Ollama, follow these steps:\n1. Download from [ollama.ai](https://ollama.ai/) and open the application\n2. Open a terminal and run `ollama run `. Example model names are `codellama:7b-instruct` or `llama2:7b-text`. You can find the full list [here](https://ollama.ai/library).\n3. Make sure that the model name used in step 2 is the same as the one in config.json (e.g. `model=\"codellama:7b-instruct\"`)\n4. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/ollama)", - "### Huggingface TGI\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/huggingfacetgi)", - "### Huggingface Inference API\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/huggingfaceinferenceapi)", - "### Llama.cpp\nllama.cpp comes with a [built-in server](https://github.com/ggerganov/llama.cpp/tree/master/examples/server#llamacppexampleserver) that can be run from source. To do this:\n\n1. Clone the repository with `git clone https://github.com/ggerganov/llama.cpp`.\n2. `cd llama.cpp`\n3. Run `make` to build the server.\n4. Download the model you'd like to use and place it in the `llama.cpp/models` directory (the best place to find models is [The Bloke on HuggingFace](https://huggingface.co/TheBloke))\n5. Run the llama.cpp server with the command below (replacing with the model you downloaded):\n\n```shell\n.\\server.exe -c 4096 --host 0.0.0.0 -t 16 --mlock -m models/codellama-7b-instruct.Q8_0.gguf\n```\n\nAfter it's up and running, you can start using Continue.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/llamacpp)", - "### Replicate\nReplicate is a hosted service that makes it easy to run ML models. To get started with Replicate:\n1. Obtain an API key from [here](https://replicate.com)\n2. Paste below\n3. Select a model preset\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/replicatellm)", - "### Gemini API\nTo get started with Google Makersuite, obtain your API key from [here](https://makersuite.google.com) and paste it below.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/geminiapi)", - "### Gemini API on Vertex AI\nTo get started you need to enable the [Vertex AI API](https://console.cloud.google.com/marketplace/product/google/aiplatform.googleapis.com) and set up the [Google Application Default Credentials](https://cloud.google.com/docs/authentication/provide-credentials-adc).", - "### LMStudio\nLMStudio provides a professional and well-designed GUI for exploring, configuring, and serving LLMs. It is available on both Mac and Windows. To get started:\n1. Download from [lmstudio.ai](https://lmstudio.ai/) and open the application\n2. Search for and download the desired model from the home screen of LMStudio.\n3. In the left-bar, click the '<->' icon to open the Local Inference Server and press 'Start Server'.\n4. Once your model is loaded and the server has started, you can begin using Continue.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/lmstudio)", - "### Llamafile\nTo get started with llamafiles, find and download a binary on their [GitHub repo](https://github.com/Mozilla-Ocho/llamafile#binary-instructions). Then run it with the following command:\n\n```shell\nchmod +x ./llamafile\n./llamafile\n```\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/llamafile)", - "### Mistral API\n\nTo get access to the Mistral API, obtain your API key from the [Mistral platform](https://docs.mistral.ai/)", - "### Mistral API on Vertex AI\nTo get started you need to enable the [Vertex AI API](https://console.cloud.google.com/marketplace/product/google/aiplatform.googleapis.com) and set up the [Google Application Default Credentials](https://cloud.google.com/docs/authentication/provide-credentials-adc).", - "### DeepInfra\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/deepinfra)", - "### Groq\nGroq provides extremely fast inference of open-source language models. To get started, obtain an API key from [their console](https://console.groq.com/keys).", - "### Fireworks\nFireworks is a fast inference engine for open-source language models. To get started, obtain an API key from [their console](https://fireworks.ai/api-keys).", - "### Cloudflare Workers AI\n\n[Reference](https://developers.cloudflare.com/workers-ai/)", - "### Deepseek\n Deepseek's API provides the best pricing for their state-of-the-art Deepseek Coder models. To get started, obtain an API key from [their console](https://platform.deepseek.com/api_keys)", - "### Azure OpenAI\n Azure OpenAI lets you securely run OpenAI's models on Azure. To get started, follow the steps [here](https://docs.continue.dev/reference/Model%20Providers/azure)", - "### Msty\nMsty is the simplest way to get started with online or local LLMs on all desktop platforms - Windows, Mac, and Linux. No fussing around, one-click and you are up and running. To get started, follow these steps:\n1. Download from [Msty.app](https://msty.app/), open the application, and click 'Setup Local AI'.\n2. Go to the Local AI Module page and download a model of your choice.\n3. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/Msty)", - "### IBM watsonx\nwatsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks.", - "### OpenRouter\nOpenRouter offers a single API to access almost any language model. To get started, obtain an API key from [their console](https://openrouter.ai/settings/keys).", - "### NVIDIA NIMs\nNVIDIA offers a single API to access almost any language model. To find out more, visit the [LLM APIs Documentation](https://docs.api.nvidia.com/nim/reference/llm-apis).\nFor information specific to getting a key, please check out the [docs here](https://docs.nvidia.com/nim/large-language-models/latest/getting-started.html#option-1-from-api-catalog)", - "### vLLM\nvLLM is a highly performant way of hosting LLMs for a team. To get started, follow their [quickstart](https://docs.vllm.ai/en/latest/getting_started/quickstart.html) to set up your server.", - "### Cerebras\nCerebras Inference uses specialized silicon to provides superfast inference. To get started, get your API keys from [their console](https://cloud.cerebras.ai/).", - "### Ask Sage\nAsk Sage is an agnostic hosted service that provides language models. To get started with Ask Sage:\n1. Obtain an API key from your account. For more information, visit [Ask Sage](https://docs.asksage.ai/).\n2. Paste the API key below.\n3. Select a model preset.\n> [Reference](https://docs.asksage.ai/)" - ], - "type": "string" - }, - "model": { - "title": "Model", - "description": "The name of the model. Used to autodetect prompt template.", - "type": "string" - }, - "apiKey": { - "title": "Api Key", - "description": "OpenAI, Anthropic, Cohere, Together, or other API key", - "type": "string" - }, - "apiBase": { - "title": "Api Base", - "description": "The base URL of the LLM API.", - "type": "string" - }, - "region": { - "title": "Region", - "description": "The region where the model is hosted", - "anyOf": [ - { - "enum": [ - "us-east-1", - "us-east-2", - "us-west-1", - "us-west-2", - "eu-west-1", - "eu-central-1", - "ap-southeast-1", - "ap-northeast-1", - "ap-south-1", - "us-central1", - "us-east1", - "us-east4", - "us-east5", - "us-west1", - "us-west4", - "us-south1", - "northamerica-northeast1", - "southamerica-east1", - "europe-central2", - "europe-north1", - "europe-west1", - "europe-west2", - "europe-west3", - "europe-west4", - "europe-west6", - "europe-west8", - "europe-west9", - "europe-southwest1", - "asia-east1", - "asia-east2", - "asia-south1", - "asia-northeast1", - "asia-northeast3", - "asia-southeast1", - "australia-southeast1", - "me-central1", - "me-central2", - "me-west1" - ], - "type": "string" - }, - { - "type": "string" - } - ] - }, - "profile": { - "title": "Profile", - "description": "The AWS security profile to use", - "type": "string" - }, - "modelArn": { - "title": "Profile", - "description": "The AWS arn for the imported model", - "type": "string" - }, - "contextLength": { - "title": "Context Length", - "description": "The maximum context length of the LLM in tokens, as counted by countTokens.", - "default": 2048, - "type": "integer" - }, - "maxStopWords": { - "title": "Max Stop Words", - "description": "The maximum number of stop words that the API will accept. You can set this if you are receiving an error about the number of stop words, but otherwise should leave it undefined.", - "type": "integer" - }, - "template": { - "title": "Template", - "description": "The chat template used to format messages. This is auto-detected for most models, but can be overridden here. Choose none if you are using vLLM or another server that automatically handles prompting.", - "enum": [ - "llama2", - "alpaca", - "zephyr", - "phi2", - "phind", - "anthropic", - "chatml", - "none", - "deepseek", - "openchat", - "xwin-coder", - "neural-chat", - "codellama-70b", - "llava", - "gemma", - "llama3" - ], - "type": "string" - }, - "promptTemplates": { - "title": "Prompt Templates", - "markdownDescription": "A mapping of prompt template name ('edit' is currently the only one used in Continue) to a string giving the prompt template. See [here](https://docs.continue.dev/model-setup/configuration#customizing-the-edit-prompt) for an example.", - "x-intellij-html-description": "A mapping of prompt template name ('edit' is currently the only one used in Continue) to a string giving the prompt template. See here for an example.", - "type": "object", - "additionalProperties": { - "type": "string" - } - }, - "completionOptions": { - "title": "Completion Options", - "description": "Options for the completion endpoint. Read more about the completion options in the documentation.", - "default": { - "temperature": null, - "topP": null, - "topK": null, - "presencePenalty": null, - "frequencyPenalty": null, - "stop": null, - "maxTokens": 600 - }, - "allOf": [ - { - "$ref": "#/definitions/BaseCompletionOptions" - } - ] - }, - "systemMessage": { - "title": "System Message", - "description": "A system message that will always be followed by the LLM", - "type": "string" - }, - "requestOptions": { - "title": "Request Options", - "description": "Options for the HTTP request to the LLM.", - "default": { - "timeout": 7200, - "verifySsl": null, - "caBundlePath": null, - "proxy": null, - "headers": null, - "extraBodyProperties": null - }, - "allOf": [ - { - "$ref": "#/definitions/RequestOptions" - } - ] - }, - "apiType": { - "title": "Api Type", - "markdownDescription": "OpenAI API type, either `openai` or `azure`", - "x-intellij-html-description": "OpenAI API type, either openai or azure", - "enum": [ - "openai", - "azure" - ] - }, - "apiVersion": { - "title": "Api Version", - "description": "Azure OpenAI API version (e.g. 2023-07-01-preview)", - "type": "string" - }, - "engine": { - "title": "Engine", - "description": "Azure OpenAI engine", - "type": "string" - }, - "capabilities": { - "type": "object", - "description": "We will attempt to automatically detect the capabilities of the model based on its title and provider, but this may not always be accurate. You can override the model's capabilities here.", - "properties": { - "uploadImage": { - "type": "boolean", - "description": "Indicates whether the model can upload images." - } - } - } - }, - "required": [ - "title", - "provider", - "model" - ], - "allOf": [ - { - "if": { - "properties": { - "provider": { - "type": "str" - } - }, - "not": { - "required": [ - "provider" - ] - } - }, - "then": { - "properties": { - "model": { - "description": "Choose a provider first, then model options will be shown here." - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "openai", - "anthropic", - "cohere", - "gemini", - "huggingface-inference-api", - "replicate", - "together", - "cloudflare", - "sambanova", - "nebius" - ] - } - }, - "required": [ - "provider" - ] - }, - "then": { - "required": [ - "apiKey" - ] - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "bedrockimport" - ] - } - }, - "required": [ - "provider" - ] - }, - "then": { - "required": [ - "modelArn" - ] - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "huggingface-tgi", - "huggingface-inference-api" - ] - } - } - }, - "then": { - "required": [ - "apiBase" - ] - }, - "required": [ - "provider" - ] - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "openai" - ] - } - }, - "required": [ - "provider" - ] - }, - "then": { - "properties": { - "engine": { - "type": "string" - }, - "apiType": { - "type": "string" - }, - "apiVersion": { - "type": "string" - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "cloudflare" - ] - } - }, - "required": [ - "provider" - ] - }, - "then": { - "properties": { - "accountId": { - "type": "string" - }, - "aiGatewaySlug": { - "type": "string" - }, - "model": { - "anyOf": [ - { - "enum": [ - "@cf/meta/llama-3-8b-instruct", - "@hf/thebloke/deepseek-coder-6.7b-instruct-awq", - "@cf/deepseek-ai/deepseek-math-7b-instruct", - "@cf/thebloke/discolm-german-7b-v1-awq", - "@cf/tiiuae/falcon-7b-instruct", - "@cf/google/gemma-2b-it-lora", - "@hf/google/gemma-7b-it", - "@cf/google/gemma-7b-it-lora", - "@hf/nousresearch/hermes-2-pro-mistral-7b", - "@cf/meta/llama-2-7b-chat-fp16", - "@cf/meta/llama-2-7b-chat-int8", - "@cf/meta-llama/llama-2-7b-chat-hf-lora", - "@hf/thebloke/llama-2-13b-chat-awq", - "@hf/thebloke/llamaguard-7b-awq", - "@cf/mistral/mistral-7b-instruct-v0.1", - "@hf/mistral/mistral-7b-instruct-v0.2", - "@cf/mistral/mistral-7b-instruct-v0.2-lora", - "@hf/thebloke/neural-chat-7b-v3-1-awq", - "@cf/openchat/openchat-3.5-0106", - "@hf/thebloke/openhermes-2.5-mistral-7b-awq", - "@cf/microsoft/phi-2", - "@cf/qwen/qwen1.5-0.5b-chat", - "@cf/qwen/qwen1.5-1.8b-chat", - "@cf/qwen/qwen1.5-7b-chat-awq", - "@cf/qwen/qwen1.5-14b-chat-awq", - "@cf/defog/sqlcoder-7b-2", - "@hf/nexusflow/starling-lm-7b-beta", - "@cf/tinyllama/tinyllama-1.1b-chat-v1.0", - "@hf/thebloke/zephyr-7b-beta-awq", - "@hf/thebloke/deepseek-coder-6.7b-base-awq" - ] - }, - { - "type": "string" - } - ] - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "openai" - ] - } - }, - "required": [ - "provider" - ] - }, - "then": { - "properties": { - "model": { - "anyOf": [ - { - "enum": [ - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-4o", - "gpt-4o-mini", - "gpt-4", - "gpt-3.5-turbo-0613", - "gpt-4-32k", - "gpt-4-0125-preview", - "gpt-4-turbo", - "AUTODETECT" - ] - }, - { - "type": "string" - } - ] - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "replicate" - ] - } - }, - "required": [ - "provider" - ] - }, - "then": { - "properties": { - "model": { - "anyOf": [ - { - "enum": [ - "llama3.1-8b", - "llama3.1-70b", - "llama3.1-405b", - "llama3-8b", - "llama3-70b", - "codellama-7b", - "codellama-13b", - "codellama-34b", - "llama2-7b", - "llama2-13b" - ] - }, - { - "type": "string" - } - ] - }, - "markdownDescription": "Select a pre-defined option, or find an exact model ID from Replicate [here](https://replicate.com/collections/streaming-language-models).", - "x-intellij-html-description": "Select a pre-defined option, or find an exact model ID from Replicate here." - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "free-trial" - ] - } - }, - "required": [ - "provider" - ] - }, - "then": { - "properties": { - "model": { - "enum": [ - "gpt-4o", - "codestral-latest", - "llama3.1-70b", - "llama3.1-405b", - "gpt-3.5-turbo", - "gemini-pro", - "claude-3-5-sonnet-20240620", - "claude-3-haiku-20240307", - "AUTODETECT" - ] - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "openai" - ] - }, - "apiType": { - "not": { - "const": "azure" - } - } - }, - "required": [ - "provider" - ] - }, - "then": { - "properties": { - "model": { - "anyOf": [ - { - "enum": [ - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-4o", - "gpt-4o-mini", - "gpt-4", - "gpt-3.5-turbo-0613", - "gpt-4-32k", - "gpt-4-turbo", - "gpt-4-vision-preview", - "mistral-7b", - "mistral-8x7b", - "llama2-7b", - "llama2-13b", - "codellama-7b", - "codellama-13b", - "codellama-34b", - "codellama-70b", - "llama3-8b", - "llama3-70b", - "llama3.1-8b", - "llama3.1-70b", - "llama3.1-405b", - "phind-codellama-34b", - "wizardcoder-7b", - "wizardcoder-13b", - "wizardcoder-34b", - "zephyr-7b", - "codeup-13b", - "deepseek-7b", - "deepseek-33b", - "neural-chat-7b", - "deepseek-1b", - "stable-code-3b", - "starcoder-1b", - "starcoder-3b", - "starcoder2-3b", - "mistral-tiny", - "mistral-small", - "mistral-medium", - "AUTODETECT" - ] - }, - { - "type": "string" - } - ] - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "anthropic" - ] - } - }, - "required": [ - "provider" - ] - }, - "then": { - "properties": { - "cacheBehavior": { - "title": "Caching Behavior", - "description": "Options for the prompt caching", - "properties": { - "cacheSystemMessage": { - "type": "boolean" - }, - "cacheConversation": { - "type": "boolean" - } - } - }, - "model": { - "anyOf": [ - { - "enum": [ - "claude-2", - "claude-instant-1", - "claude-3-5-sonnet-20240620", - "claude-3-opus-20240229", - "claude-3-sonnet-20240229", - "claude-3-haiku-20240307", - "claude-2.1" - ] - }, - { - "type": "string" - } - ] - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "cohere" - ] - } - }, - "required": [ - "provider" - ] - }, - "then": { - "properties": { - "model": { - "enum": [ - "command-r", - "command-r-plus" - ] - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "bedrock" - ] - } - }, - "required": [ - "provider" - ] - }, - "then": { - "properties": { - "model": { - "anyOf": [ - { - "enum": [ - "claude-3-sonnet-20240229", - "claude-3-haiku-20240307", - "claude-2" - ] - }, - { - "type": "string" - } - ] - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "sagemaker" - ] - } - }, - "required": [ - "provider" - ] - }, - "then": { - "properties": { - "model": { - "description": "SageMaker endpoint name" - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "gemini" - ] - } - }, - "required": [ - "provider" - ] - }, - "then": { - "properties": { - "cacheBehavior": { - "title": "Caching Behavior", - "description": "Options for the prompt caching", - "properties": { - "cacheSystemMessage": { - "type": "boolean" - } - } - }, - "model": { - "enum": [ - "chat-bison-001", - "gemini-pro", - "gemini-1.5-pro-latest", - "gemini-1.5-pro", - "gemini-1.5-flash-latest", - "gemini-1.5-flash" - ] - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "together" - ] - } - }, - "required": [ - "provider" - ] - }, - "then": { - "properties": { - "model": { - "anyOf": [ - { - "enum": [ - "mistral-7b", - "mistral-8x7b", - "llama2-7b", - "llama2-13b", - "llama3-8b", - "llama3-70b", - "llama3.1-8b", - "llama3.1-70b", - "llama3.1-405b", - "codellama-7b", - "codellama-13b", - "codellama-34b", - "codellama-70b", - "phind-codellama-34b" - ] - }, - { - "type": "string" - } - ], - "markdownDescription": "Select a pre-defined option, or find an exact model string from Together AI [here](https://docs.together.ai/docs/inference-models).", - "x-intellij-html-description": "Select a pre-defined option, or find an exact model string from Together AI here." - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "deepinfra" - ] - } - }, - "required": [ - "provider" - ] - }, - "then": { - "properties": { - "model": { - "markdownDescription": "Find the model name you want to use from DeepInfra [here](https://deepinfra.com/models?type=text-generation).", - "x-intellij-html-description": "Find the model name you want to use from DeepInfra here." - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "huggingface-tgi", - "huggingface-inference-api", - "llama.cpp", - "text-gen-webui", - "llamafile" - ] - } - }, - "required": [ - "provider" - ] - }, - "then": { - "properties": { - "model": { - "anyOf": [ - { - "enum": [ - "mistral-7b", - "mistral-8x7b", - "llama2-7b", - "llama2-13b", - "codellama-7b", - "codellama-13b", - "codellama-34b", - "codellama-70b", - "llama3-8b", - "llama3-70b", - "llama3.1-8b", - "llama3.1-70b", - "llama3.1-405b", - "phind-codellama-34b", - "wizardcoder-7b", - "wizardcoder-13b", - "wizardcoder-34b", - "zephyr-7b", - "codeup-13b", - "deepseek-7b", - "deepseek-33b", - "neural-chat-7b", - "deepseek-1b", - "stable-code-3b", - "starcoder-1b", - "starcoder-3b", - "starcoder2-3b" - ] - }, - { - "type": "string" - } - ] - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "ollama" - ] - } - }, - "required": [ - "provider" - ] - }, - "then": { - "properties": { - "model": { - "anyOf": [ - { - "enum": [ - "mistral-7b", - "llama2-7b", - "llama2-13b", - "codellama-7b", - "codellama-13b", - "codellama-34b", - "codellama-70b", - "llama3-8b", - "llama3-70b", - "llama3.1-8b", - "llama3.1-70b", - "llama3.1-405b", - "phi-2", - "phind-codellama-34b", - "wizardcoder-7b", - "wizardcoder-13b", - "wizardcoder-34b", - "zephyr-7b", - "codeup-13b", - "deepseek-7b", - "deepseek-33b", - "neural-chat-7b", - "deepseek-1b", - "stable-code-3b", - "starcoder-1b", - "starcoder-3b", - "starcoder2-3b", - "AUTODETECT" - ] - }, - { - "type": "string" - } - ], - "markdownDescription": "Select a pre-defined option, or find the exact model tag for an Ollama model [here](https://ollama.ai/library).", - "x-intellij-html-description": "Select a pre-defined option, or find the exact model tag for an Ollama model here." - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "mistral" - ] - } - }, - "required": [ - "provider" - ] - }, - "then": { - "properties": { - "model": { - "enum": [ - "codestral-latest", - "codestral-mamba-latest", - "open-mistral-7b", - "open-mixtral-8x7b", - "open-mixtral-8x22b", - "mistral-small-latest", - "mistral-large-latest" - ] - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "vertexai" - ] - } - }, - "required": [ - "provider" - ] - }, - "then": { - "required": [ - "projectId", - "region" - ] - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "deepseek" - ] - } - }, - "required": [ - "provider" - ] - }, - "then": { - "properties": { - "cacheBehavior": { - "title": "Caching Behavior", - "description": "Options for the prompt caching", - "properties": { - "cacheSystemMessage": { - "type": "boolean" - }, - "cacheConversation": { - "type": "boolean" - } - } - }, - "model": { - "enum": [ - "deepseek-chat", - "deepseek-coder" - ] - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "groq" - ] - } - }, - "required": [ - "provider" - ] - }, - "then": { - "properties": { - "model": { - "enum": [ - "llama2-70b", - "mistral-8x7b", - "gemma", - "gemma2", - "llama3-8b", - "llama3-70b", - "llama3.1-8b", - "llama3.1-70b", - "llama3.1-405b", - "AUTODETECT" - ] - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "fireworks" - ] - } - }, - "required": [ - "provider" - ] - }, - "then": { - "properties": { - "model": { - "enum": [ - "starcoder-7b" - ] - } - } - } - }, - { - "if": { - "properties": { - "apiType": { - "const": "azure" - } - }, - "required": [ - "apiType" - ] - }, - "then": { - "required": [ - "engine", - "apiVersion", - "apiBase" - ] - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "openai" - ] - } - }, - "required": [ - "provider" - ] - }, - "then": { - "properties": { - "useLegacyCompletionsEndpoint": { - "type": "boolean" - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "const": "llamafile" - } - }, - "required": [ - "provider" - ] - }, - "then": { - "properties": { - "llamafileCommand": { - "type": "string" - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "cerebras" - ] - } - }, - "required": [ - "provider" - ] - }, - "then": { - "properties": { - "model": { - "enum": [ - "llama3.1-8b", - "llama3.1-70b" - ] - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "text-gen-webui" - ] - } - }, - "required": [ - "provider" - ] - }, - "then": { - "properties": { - "streamingUrl": { - "type": "string" - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "flowise" - ] - } - }, - "required": [ - "provider" - ] - }, - "then": { - "properties": { - "timeout": { - "title": "Timeout", - "description": "Set the timeout for each request to Flowise. If you are running a local version of Flowise it might takes a while to respond, you might want to set this to avoid timeouts.", - "default": 5000, - "type": "integer" - }, - "additionalHeaders": { - "description": "A list of additional headers", - "type": "array", - "items": { - "type": "object", - "properties": { - "key": { - "title": "Key", - "description": "Header key", - "type": "string" - }, - "value": { - "title": "Value", - "description": "Header value", - "type": "string" - } - }, - "required": [ - "key", - "value" - ] - } - }, - "additionalFlowiseConfiguration": { - "description": "A list of additional properties to be sent along `overrideConfig`", - "type": "array", - "items": { - "type": "object", - "properties": { - "key": { - "title": "Key", - "description": "Configuration Property key", - "type": "string" - }, - "value": { - "title": "Value", - "description": "Configuration Property value" - } - }, - "required": [ - "key", - "value" - ] - } - }, - "model": { - "anyOf": [ - { - "enum": [ - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-4o", - "gpt-4o-mini", - "gpt-4", - "gpt-3.5-turbo-0613", - "gpt-4-32k", - "gpt-4-turbo", - "gpt-4-vision-preview", - "mistral-7b", - "mistral-8x7b", - "llama2-7b", - "llama2-13b", - "codellama-7b", - "codellama-13b", - "codellama-34b", - "codellama-70b", - "llama3-8b", - "llama3-70b", - "llama3.1-8b", - "llama3.1-70b", - "llama3.1-405b", - "phind-codellama-34b", - "wizardcoder-7b", - "wizardcoder-13b", - "wizardcoder-34b", - "zephyr-7b", - "codeup-13b", - "deepseek-7b", - "deepseek-33b", - "claude-2", - "claude-instant-1", - "claude-3-5-sonnet-20240620", - "claude-3-opus-20240229", - "claude-3-sonnet-20240229", - "claude-3-haiku-20240307", - "claude-2.1", - "command-r", - "command-r-plus", - "chat-bison-001", - "gemini-pro", - "gemini-1.5-pro-latest", - "gemini-1.5-pro", - "gemini-1.5-flash-latest", - "gemini-1.5-flash", - "mistral-tiny", - "mistral-small", - "mistral-medium", - "deepseek-1b", - "stable-code-3b", - "starcoder-1b", - "starcoder-3b", - "starcoder2-3b" - ] - }, - { - "type": "string" - } - ] - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "watsonx" - ] - } - }, - "required": [ - "provider" - ] - }, - "then": { - "properties": { - "apiBase": { - "type": "string" - }, - "apiKey": { - "type": "string" - }, - "apiVersion": { - "type": "string" - }, - "projectId": { - "type": "string" - }, - "deploymentId": { - "type": "string" - }, - "model": { - "enum": [ - "ibm/granite-13b-chat-v2", - "ibm/granite-3b-code-instruct", - "ibm/granite-8b-code-instruct", - "ibm/granite-20b-code-instruct", - "ibm/granite-3b-code-instruct", - "ibm/granite-8b-code-instruct", - "ibm/granite-34b-code-instruct", - "ibm/granite-3-8b-instruct", - "ibm/granite-3-2b-instruct", - "mistralai/mistral-large", - "meta-llama/llama-3-8b-instruct", - "meta-llama/llama-3-70b-instruct" - ] - } - }, - "required": [ - "apiBase", - "apiKey", - "apiVersion" - ] - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "sambanova" - ] - } - }, - "required": [ - "provider" - ] - }, - "then": { - "properties": { - "model": { - "anyOf": [ - { - "enum": [ - "llama3.1-8b", - "llama3.1-70b", - "llama3.1-405b" - ] - }, - { - "type": "string" - } - ], - "description": "Select a pre-defined option." - } - } - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "ask-sage" - ] - } - }, - "required": [ - "provider" - ] - }, - "then": { - "properties": { - "model": { - "anyOf": [ - { - "enum": [ - "gpt-4o", - "gpt-4o-mini", - "gpt-4gov", - "gpt-4ogov", - "claude-3.5-sonnet", - "claude-3-opus", - "mistral-large", - "llama-3-chat", - "gemini-pro", - "AUTODETECT" - ] - }, - { - "type": "string" - } - ] - } - } - } - } - ] - }, - "ModelRoles": { - "title": "ModelRoles", - "type": "object", - "properties": { - "default": { - "title": "Default", - "description": "The default model. If other model roles are not set, they will fall back to default.", - "type": "string" - }, - "chat": { - "title": "Chat", - "description": "The model to use for chat. If not set, will fall back to default.", - "type": "string" - }, - "edit": { - "title": "Edit", - "description": "The model to use for editing. If not set, will fall back to default.", - "type": "string" - }, - "summarize": { - "title": "Summarize", - "description": "The model to use for summarization. If not set, will fall back to default.", - "type": "string" - } - }, - "required": [ - "default" - ] - }, - "SlashCommand": { - "title": "SlashCommand", - "type": "object", - "properties": { - "name": { - "title": "Name", - "anyOf": [ - { - "enum": [ - "issue", - "share", - "cmd", - "edit", - "comment", - "http", - "commit", - "review" - ], - "type": "string", - "markdownEnumDescriptions": [ - "Generate a link to a drafted GitHub issue", - "Export the current chat session to markdown", - "Generate a terminal command and paste it into the terminal", - "Edit the highlighted code with given instructions", - "Add comments to the highlighted code", - "Write a custom slash command at your own HTTP endpoint. Set 'url' in the params object for the endpoint you have setup.", - "Generate a commit message for the current changes", - "Review code and give feedback" - ] - }, - { - "type": "string" - } - ] - }, - "description": { - "title": "Description", - "type": "string" - }, - "step": { - "title": "Step", - "description": "This property is no longer required and has no effect. To use a built-in slash command, instead set the 'name' property to one of the pre-configured options.", - "type": "string" - }, - "params": { - "title": "Params", - "default": {}, - "type": "object" - } - }, - "allOf": [ - { - "if": { - "properties": { - "name": { - "enum": [ - "issue" - ] - } - } - }, - "then": { - "properties": { - "params": { - "properties": { - "repositoryUrl": { - "type": "string", - "description": "Enter the URL of the GitHub repository for which you want to generate the issue." - } - }, - "required": [ - "repositoryUrl" - ] - } - }, - "required": [ - "params" - ] - } - }, - { - "if": { - "properties": { - "name": { - "enum": [ - "edit" - ] - } - } - }, - "then": { - "properties": { - "params": { - "properties": { - "recap": { - "type": "boolean", - "markdownDescription": "If recap is set to `true`, Continue will generate a summary of the changes after making the edit.", - "x-intellij-html-description": "If recap is set to true, Continue will generate a summary of the changes after making the edit." - }, - "tokenLimit": { - "type": "integer", - "description": "By default, Continue doesn't let you edit extremely large ranges (beyond 1,200 tokens), because the LLM is unlikely to succeed. But if you would like to override this limit with the understanding of possible failure you may do so here." - } - } - } - } - } - }, - { - "if": { - "properties": { - "name": { - "enum": [ - "share" - ] - } - } - }, - "then": { - "properties": { - "params": { - "properties": { - "outputDir": { - "type": "string", - "markdownDescription": "If outputDir is set to `.` or begins with `./` or `.\\`, file will be saved to the current workspace or a subdirectory thereof, respectively. `~` can similarly be used to specify the user's home directory.", - "x-intellij-html-description": "If outputDir is set to . or begins with ./ or .\\, file will be saved to the current workspace or a subdirectory thereof, respectively. ~ can similarly be used to specify the user's home directory." - } - } - } - } - } - }, - { - "if": { - "properties": { - "name": { - "enum": [ - "commit" - ] - } - } - }, - "then": { - "properties": { - "params": { - "properties": { - "includeUnstaged": { - "type": "boolean", - "markdownDescription": "If set to `true`, then unstaged changes are also included in the prompt, otherwise only staged changes are included. Default is `false`.", - "x-intellij-html-description": "If set to true, then unstaged changes are also included in the prompt, otherwise only staged changes are included. Default is false." - } - } - } - } - } - } - ], - "required": [ - "name", - "description" - ] - }, - "CustomCommand": { - "title": "CustomCommand", - "type": "object", - "properties": { - "name": { - "title": "Name", - "type": "string" - }, - "prompt": { - "title": "Prompt", - "type": "string" - }, - "description": { - "title": "Description", - "type": "string" - } - }, - "required": [ - "name", - "prompt", - "description" - ] - }, - "ContextProviderWithParams": { - "title": "ContextProviderWithParams", - "type": "object", - "properties": { - "name": { - "title": "Name", - "anyOf": [ - { - "enum": [ - "diff", - "terminal", - "debugger", - "open", - "google", - "search", - "http", - "codebase", - "problems", - "folder", - "issue", - "docs", - "tree", - "highlights", - "outline", - "postgres", - "code", - "currentFile", - "url", - "database", - "os", - "repo-map", - "greptile", - "web" - ], - "markdownEnumDescriptions": [ - "Reference the contents of the current changes as given by `git diff`", - "Reference the last terminal command", - "Reference the contents of the local variables in the debugger with top n level (defaulting to 3) of call stack for that thread", - "Reference the contents of all open or pinned files.", - "Enter a search phrase and include the Google search results as context", - "Reference the results of a ripgrep search in your codebase", - "Write a custom context provider at your own HTTP endpoint. Set 'url' in the params object for the endpoint you have setup.", - "Use embeddings to automatically find relevant files from throughout the codebase", - "Reference all linting errors and warnings in the currently open file", - "Include important files from a folder in the prompt, as determined by similarity search", - "Reference GitHub issues from a repository", - "Retrieve important pages from a documentation website, as determined by similarity search", - "Display a file tree of the current workspace", - "Include important highlighted sections from your code", - "Include a repo map showing important code objects", - "References Postgres table schema and sample rows", - "Reference specific functions and classes from throughout your codebase", - "Reference the contents of the currently active file", - "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", - "Query your greptile index of the current repo", - "Search the web for sources related to your question" - ], - "type": "string" - }, - { - "type": "string" - } - ] - }, - "params": { - "title": "Params", - "default": {}, - "type": "object" - } - }, - "allOf": [ - { - "if": { - "properties": { - "name": { - "enum": [ - "discord" - ] - } - } - }, - "then": { - "allOf": [ - { - "properties": { - "params": { - "properties": { - "discordKey": { - "type": "string", - "description": "Your Discord bot token to access the Discord API. Required to fetch messages from servers." - }, - "guildId": { - "type": "string", - "description": "The ID of the guild (server) from which to fetch channels and messages." - }, - "channels": { - "type": "array", - "description": "A list of channel objects to search for messages", - "items": { - "type": "object", - "properties": { - "id": { - "type": "string", - "description": "The unique ID of the channel" - }, - "name": { - "type": "string", - "description": "The name of the channel" - } - }, - "required": [ - "id" - ] - } - } - }, - "required": [ - "discordKey" - ] - } - } - }, - { - "oneOf": [ - { - "properties": { - "params": { - "required": [ - "guildId" - ] - } - } - }, - { - "properties": { - "params": { - "required": [ - "channels" - ] - } - } - } - ] - } - ] - } - }, - { - "if": { - "properties": { - "name": { - "enum": [ - "google" - ] - } - } - }, - "then": { - "properties": { - "params": { - "properties": { - "serperApiKey": { - "type": "string", - "description": "Your API key for https://serper.dev in order to get Google search results" - } - }, - "required": [ - "serperApiKey" - ] - } - }, - "required": [ - "params" - ] - } - }, - { - "if": { - "properties": { - "name": { - "enum": [ - "web" - ] - } - } - }, - "then": { - "properties": { - "params": { - "properties": { - "n": { - "title": "N", - "description": "The number of results to return", - "default": 6, - "type": "integer" - } - } - } - }, - "required": [ - "params" - ] - } - }, - { - "if": { - "properties": { - "name": { - "enum": [ - "open" - ] - } - } - }, - "then": { - "properties": { - "params": { - "properties": { - "onlyPinned": { - "type": "boolean", - "description": "If set to true, only 'pinned' files will be included.", - "default": false - } - } - } - } - } - }, - { - "if": { - "properties": { - "name": { - "enum": [ - "issue" - ] - } - } - }, - "then": { - "properties": { - "params": { - "properties": { - "githubToken": { - "type": "string", - "description": "Your GitHub token to access the GitHub API. Required for private repositories." - }, - "repos": { - "type": "array", - "description": "A list of repositories to search for issues", - "items": { - "type": "object", - "properties": { - "owner": { - "type": "string", - "description": "The owner of the repository" - }, - "repo": { - "type": "string", - "description": "The name of the repository" - }, - "type": { - "type": "string", - "description": "The type of issues to search for", - "enum": [ - "open", - "closed", - "all" - ] - } - }, - "required": [ - "owner", - "repo" - ] - } - } - }, - "required": [ - "repos" - ] - } - }, - "required": [ - "params" - ] - } - }, - { - "if": { - "properties": { - "name": { - "enum": [ - "database" - ] - } - } - }, - "then": { - "properties": { - "params": { - "properties": { - "connections": { - "type": "array", - "description": "A list of database connections", - "items": { - "type": "object", - "properties": { - "name": { - "type": "string", - "description": "A unique name for this database connection" - }, - "connection_type": { - "type": "string", - "description": "The type of database (e.g., 'postgres', 'mysql')", - "enum": [ - "postgres", - "mysql", - "sqlite" - ] - }, - "connection": { - "type": "object", - "properties": { - "user": { - "type": "string", - "description": "The database user name" - }, - "host": { - "type": "string", - "description": "The host address of the database server" - }, - "database": { - "type": "string", - "description": "The name of the database to connect to" - }, - "password": { - "type": "string", - "description": "The password for the database user" - }, - "port": { - "type": "integer", - "description": "The port number to connect to at the host" - }, - "filename": { - "type": "string", - "description": "File location for simple file DB's" - } - }, - "required": [] - } - }, - "required": [ - "name", - "connection_type", - "connection" - ] - } - } - }, - "required": [ - "connections" - ] - } - }, - "required": [ - "params" - ] - } - }, - { - "if": { - "properties": { - "name": { - "enum": [ - "gitlab-mr" - ] - } - } - }, - "then": { - "properties": { - "params": { - "properties": { - "domain": { - "type": "string", - "description": "Your GitLab domain, will default to gitlab.com" - }, - "token": { - "type": "string", - "description": "Your private access token." - }, - "filterComments": { - "type": "boolean", - "description": "If you have code selected, filters out comments that aren't related to the selection." - } - }, - "required": [ - "token" - ] - } - }, - "required": [ - "params" - ] - } - }, - { - "if": { - "properties": { - "name": { - "enum": [ - "jira" - ] - } - } - }, - "then": { - "properties": { - "params": { - "properties": { - "domain": { - "type": "string", - "description": "Your Jira domain, for example company.atlassian.net." - }, - "email": { - "type": "string", - "description": "The email that you log into Jira with" - }, - "token": { - "type": "string", - "description": "Your atlassian API token from https://id.atlassian.com/manage-profile/security/api-tokens" - }, - "issueQuery": { - "type": "string", - "description": "Customize the query used to find Jira issues" - }, - "apiVersion": { - "type": "integer", - "markdownDescription": "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.", - "x-intellij-html-description": "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." - }, - "requestOptions": { - "title": "Request Options", - "description": "Options for the HTTPS request to Jira.", - "default": { - "timeout": 7200, - "verifySsl": null, - "caBundlePath": null, - "proxy": null, - "headers": null, - "extraBodyProperties": null - }, - "allOf": [ - { - "$ref": "#/definitions/RequestOptions" - } - ] - } - }, - "required": [ - "domain", - "token" - ] - } - }, - "required": [ - "params" - ] - } - }, - { - "if": { - "properties": { - "name": { - "enum": [ - "http" - ] - } - } - }, - "then": { - "properties": { - "params": { - "properties": { - "url": { - "type": "string", - "description": "The HTTP endpoint of your context provider server." - }, - "options": { - "title": "Custom Options", - "description": "Additional options to pass to your custom HTTP server.", - "type": "object" - } - }, - "required": [ - "url" - ] - } - }, - "required": [ - "params" - ] - } - }, - { - "if": { - "properties": { - "name": { - "enum": [ - "codebase", - "folder" - ] - } - } - }, - "then": { - "properties": { - "params": { - "properties": { - "nRetrieve": { - "title": "N Retrieve", - "description": "Number of results to initially retrieve from vector database", - "default": 50, - "type": "integer" - }, - "nFinal": { - "title": "N Final", - "description": "Final number of results to use after re-ranking", - "default": 10, - "type": "integer" - }, - "useReranking": { - "title": "Use Reranking", - "description": "Whether to use re-ranking, which will allow initial selection of nRetrieve results, then will use an LLM to select the top nFinal results. Disabling re-ranking will give faster, but less accurate, results.", - "default": true, - "type": "boolean" - } - } - } - } - } - }, - { - "if": { - "properties": { - "name": { - "enum": [ - "postgres" - ] - } - } - }, - "then": { - "properties": { - "params": { - "properties": { - "host": { - "title": "Host", - "description": "Database host", - "default": "localhost", - "type": "string" - }, - "port": { - "title": "Port", - "description": "Database port", - "default": 5432, - "type": "integer" - }, - "user": { - "title": "User", - "description": "Database user", - "default": "postgres", - "type": "string" - }, - "password": { - "title": "Password", - "description": "Database password", - "type": "string" - }, - "database": { - "title": "Database", - "description": "Database name", - "default": "postgres", - "type": "string" - }, - "schema": { - "title": "Schema", - "description": "Database schema", - "default": "public", - "type": "string" - }, - "sampleRows": { - "title": "Sample Rows", - "description": "Number of rows to sample from the database", - "default": 3, - "type": "integer" - } - } - } - }, - "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" - ] - }, - "SerializedContinueConfig": { - "title": "config.json", - "type": "object", - "properties": { - "docs": { - "title": "Docs", - "description": "A list of documentation sites to be indexed", - "type": "array", - "items": { - "type": "object", - "properties": { - "title": { - "type": "string", - "description": "The title of the documentation site" - }, - "startUrl": { - "type": "string", - "description": "The starting URL for indexing the documentation" - }, - "rootUrl": { - "type": "string", - "description": "The root URL of the documentation site" - }, - "maxDepth": { - "type": "integer", - "description": "The maximum depth to crawl the documentation site" - }, - "favicon": { - "type": "string", - "description": "The URL path to a favicon for the site - by default, it will be `/favicon.ico` path from the Start URL" - } - }, - "required": [ - "title", - "startUrl" - ] - } - }, - "allowAnonymousTelemetry": { - "title": "Allow Anonymous Telemetry", - "markdownDescription": "If this field is set to `true`, we will collect anonymous telemetry as described in the documentation page on telemetry. If set to `false`, we will not collect any data. Learn more in [the docs](https://docs.continue.dev/telemetry).", - "x-intellij-html-description": "If this field is set to `true`, we will collect anonymous telemetry as described in the documentation page on telemetry. If set to `false`, we will not collect any data. Learn more in the docs.", - "default": true, - "type": "boolean" - }, - "models": { - "title": "Models", - "markdownDescription": "Learn about setting up models in [the documentation](https://docs.continue.dev/model-setup/overview).", - "x-intellij-html-description": "Learn about setting up models in the documentation.", - "default": [ - { - "title": "GPT-4 (trial)", - "provider": "free-trial", - "model": "gpt-4", - "apiKey": "" - } - ], - "type": "array", - "items": { - "$ref": "#/definitions/ModelDescription" - } - }, - "systemMessage": { - "title": "System Message", - "description": "A system message that will always be followed by the LLM", - "type": "string" - }, - "completionOptions": { - "title": "Completion Options", - "description": "Default options for completion. These will be overriden by any options set for a specific model.", - "default": { - "temperature": null, - "topP": null, - "topK": null, - "presencePenalty": null, - "frequencyPenalty": null, - "stop": null, - "maxTokens": 600 - }, - "allOf": [ - { - "$ref": "#/definitions/BaseCompletionOptions" - } - ] - }, - "requestOptions": { - "title": "Request Options", - "description": "Default request options for all fetch requests from models and context providers. These will be overriden by any model-specific request options.", - "allOf": [ - { - "$ref": "#/definitions/RequestOptions" - } - ] - }, - "slashCommands": { - "title": "Slash Commands", - "markdownDescription": "An array of slash commands that let you take custom actions from the sidebar. Learn more in the [documentation](https://docs.continue.dev/customization/slash-commands).", - "x-intellij-html-description": "An array of slash commands that let you take custom actions from the sidebar. Learn more in the documentation.", - "default": [], - "type": "array", - "items": { - "$ref": "#/definitions/SlashCommand" - } - }, - "customCommands": { - "title": "Custom Commands", - "markdownDescription": "An array of custom commands that allow you to reuse prompts. Each has name, description, and prompt properties. When you enter `/` in the text input, it will act as a shortcut to the prompt. Learn more in the [documentation](https://docs.continue.dev/customization/slash-commands#custom-commands-use-natural-language).", - "x-intellij-html-description": "An array of custom commands that allow you to reuse prompts. Each has name, description, and prompt properties. When you enter / in the text input, it will act as a shortcut to the prompt. Learn more in the documentation.", - "default": [ - { - "name": "test", - "prompt": "{{{ input }}}\n\nWrite a comprehensive set of unit tests for the selected code. It should setup, run tests that check for correctness including important edge cases, and teardown. Ensure that the tests are complete and sophisticated. Give the tests just as chat output, don't edit any file.", - "description": "This is an example custom command. Open config.json to edit it and create more" - } - ], - "type": "array", - "items": { - "$ref": "#/definitions/CustomCommand" - } - }, - "contextProviders": { - "title": "Context Providers", - "markdownDescription": "A list of ContextProvider objects that can be used to provide context to the LLM by typing '@'. Read more about ContextProviders in [the documentation](https://docs.continue.dev/customization/context-providers).", - "x-intellij-html-description": "A list of ContextProvider objects that can be used to provide context to the LLM by typing '@'. Read more about ContextProviders in the documentation.", - "default": [], - "type": "array", - "items": { - "$ref": "#/definitions/ContextProviderWithParams" - } - }, - "userToken": { - "title": "User Token", - "description": "An optional token to identify the user.", - "type": "string" - }, - "disableIndexing": { - "title": "Disable Indexing", - "markdownDescription": "If set to `true`, Continue will not index the codebase. This is mainly used for debugging purposes.", - "x-intellij-html-description": "If set to true, Continue will not index the codebase. This is mainly used for debugging purposes.", - "default": false, - "type": "boolean" - }, - "disableSessionTitles": { - "title": "Disable Session Titles", - "markdownDescription": "If set to `true`, Continue will not make extra requests to the LLM to generate a summary title of each session.", - "x-intellij-html-description": "If set to true, Continue will not make extra requests to the LLM to generate a summary title of each session.", - "default": false, - "type": "boolean" - }, - "embeddingsProvider": { - "title": "Embeddings Provider", - "markdownDescription": "The method that will be used to generate codebase embeddings. The default is `transformers.js`, which will run locally in the browser. Learn about the other options [here](https://docs.continue.dev/features/codebase-embeddings#embeddings-providers).", - "x-intellij-html-description": "The method that will be used to generate codebase embeddings. The default is transformers.js, which will run locally in the browser. Learn about the other options here.

Note: transformers.js currently cannot be used in JetBrains.", - "type": "object", - "properties": { - "provider": { - "enum": [ - "huggingface-tei", - "transformers.js", - "ollama", - "openai", - "cohere", - "free-trial", - "gemini", - "voyage", - "nvidia", - "bedrock", - "sagemaker", - "nebius", - "vertexai" - ] - }, - "model": { - "type": "string" - }, - "apiKey": { - "type": "string" - }, - "apiBase": { - "type": "string" - }, - "requestOptions": { - "title": "Request Options", - "description": "Request options to be used in any fetch requests made by the embeddings provider", - "$ref": "#/definitions/RequestOptions" - }, - "maxChunkSize": { - "title": "Maximum Chunk Size", - "description": "The maximum number of tokens that each chunk of a document is allowed to have", - "type": "integer", - "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", - "$ref": "#/definitions/ModelDescription/properties/region" - }, - "profile": { - "title": "Profile", - "description": "The AWS security profile to use", - "type": "string" - } - }, - "required": [ - "provider" - ], - "allOf": [ - { - "if": { - "properties": { - "provider": { - "enum": [ - "cohere", - "voyage", - "nvidia", - "gemini" - ] - } - }, - "required": [ - "provider" - ] - }, - "then": { - "required": [ - "apiKey" - ] - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "sagemaker" - ] - } - }, - "required": [ - "provider" - ] - }, - "then": { - "properties": { - "model": { - "description": "SageMaker endpoint name" - } - }, - "required": [ - "model" - ] - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "vertexai" - ] - } - }, - "required": [ - "provider" - ] - }, - "then": { - "properties": { - "projectId": { - "description": "The name of your VertexAI project" - }, - "region": { - "description": "The region your VertexAI model is hosted in - typically central1", - "default": "central1" - }, - "model": { - "default": "text-embedding-004" - } - }, - "required": [ - "projectId", - "model", - "region" - ] - } - } - ] - }, - "reranker": { - "title": "Reranker", - "description": "The reranker is responsible for selecting the final results when retrieving snippets from your codebase.", - "type": "object", - "properties": { - "name": { - "enum": [ - "cohere", - "voyage", - "llm", - "free-trial", - "huggingface-tei" - ] - }, - "params": { - "type": "object" - } - }, - "required": [ - "name" - ], - "allOf": [ - { - "if": { - "properties": { - "name": { - "enum": [ - "cohere" - ] - } - }, - "required": [ - "name" - ] - }, - "then": { - "properties": { - "params": { - "type": "object", - "properties": { - "model": { - "enum": [ - "rerank-english-v3.0", - "rerank-multilingual-v3.0", - "rerank-english-v2.0", - "rerank-multilingual-v2.0" - ] - }, - "apiBase": { - "type": "string" - }, - "apiKey": { - "type": "string" - } - }, - "required": [ - "apiKey" - ] - } - } - } - }, - { - "if": { - "properties": { - "name": { - "enum": [ - "llm" - ] - } - }, - "required": [ - "name" - ] - }, - "then": { - "properties": { - "params": { - "type": "object", - "properties": { - "modelTitle": { - "type": "string" - } - }, - "required": [ - "modelTitle" - ] - } - } - } - }, - { - "if": { - "properties": { - "name": { - "enum": [ - "voyage" - ] - } - }, - "required": [ - "name" - ] - }, - "then": { - "properties": { - "params": { - "type": "object", - "properties": { - "apiKey": { - "type": "string" - }, - "model": { - "enum": [ - "rerank-lite-1", - "rerank-1", - "rerank-2", - "rerank-2-lite" - ] - } - }, - "required": [ - "apiKey" - ] - } - } - } - }, - { - "if": { - "properties": { - "name": { - "enum": [ - "huggingface-tei" - ] - } - }, - "required": [ - "name" - ] - }, - "then": { - "properties": { - "params": { - "type": "object", - "properties": { - "apiBase": { - "type": "string", - "default": "http://localhost:8080" - }, - "truncate": { - "type": "boolean", - "description": "Whether to truncate long sequences to the maximum allowed context length.", - "default": false - }, - "truncation_direction": { - "enum": [ - "Right", - "Left" - ], - "description": "Whether to truncate sequences from the left or right.", - "default": "Right" - } - }, - "required": [ - "apiBase" - ] - } - }, - "if": { - "properties": { - "truncate": { - "const": true - } - } - }, - "then": { - "required": [ - "truncation_direction" - ] - } - } - } - ] - }, - "tabAutocompleteModel": { - "title": "Tab Autocomplete Model", - "markdownDescription": "The model used for tab autocompletion. If undefined, Continue will default to using starcoder2:3b on a local Ollama instance.\n\n*IMPORTANT*:\n\nIf you use a custom model, ensure that it is one trained for fill-in-the-middle completions. An instruct model is typically not well-suited to autocomplete and you may receive unsatisfactory completions.", - "x-intellij-html-description": "The model used for tab autocompletion. If undefined, Continue will default to using starcoder2:3b on a local Ollama instance.

IMPORTANT:

If you use a custom model, ensure that it is one trained for fill-in-the-middle completions. An instruct model is typically not well-suited to autocomplete and you may receive unsatisfactory completions.", - "default": { - "title": "Tab Autocomplete Model", - "provider": "ollama", - "model": "deepseek-coder:1.3b-base" - }, - "oneOf": [ - { - "$ref": "#/definitions/ModelDescription" - }, - { - "type": "array", - "items": { - "$ref": "#/definitions/ModelDescription" - } - } - ] - }, - "tabAutocompleteOptions": { - "title": "TabAutocompleteOptions", - "type": "object", - "markdownDescription": "These options let you customize your tab-autocomplete experience. Read about all options in [the docs](https://docs.continue.dev/features/tab-autocomplete#configuration-options).", - "x-intellij-html-description": "These options let you customize your tab-autocomplete experience. Read about all options in the docs.", - "properties": { - "disable": { - "type": "boolean", - "description": "Disable tab autocomplete. This can also be done from the IDE settings.", - "default": false - }, - "useCopyBuffer": { - "type": "boolean", - "description": "Determines whether the copy buffer will be considered when contructing the prompt." - }, - "useFileSuffix": { - "type": "boolean", - "description": "Determines whether to use the file suffix in the prompt." - }, - "maxPromptTokens": { - "type": "number", - "description": "The maximum number of prompt tokens to use. A smaller number will yield faster completions, but less context." - }, - "debounceDelay": { - "type": "number", - "description": "The delay in milliseconds before triggering autocomplete after a keystroke." - }, - "maxSuffixPercentage": { - "type": "number", - "description": "The maximum percentage of the prompt that can be dedicated to the suffix." - }, - "prefixPercentage": { - "type": "number", - "description": "The percentage of the input that should be dedicated to the prefix." - }, - "transform": { - "type": "boolean", - "description": "Whether LLM output should be transformed to correct common model pitfalls." - }, - "template": { - "type": "string", - "description": "An optional template string to be used for autocomplete. It will be rendered with the Mustache templating language, and is passed the 'prefix' and 'suffix' variables." - }, - "multilineCompletions": { - "enum": [ - "always", - "never", - "auto" - ], - "description": "If set to true, Continue will only complete a single line at a time." - }, - "useCache": { - "type": "boolean", - "description": "Whether to cache completions" - }, - "onlyMyCode": { - "type": "boolean", - "description": "If set to true, Continue will not include any snippets from go to definition unless they are within your repository" - }, - "useOtherFiles": { - "type": "boolean", - "description": "Defaults to true. If set to false, Continue will not attempt to include snippets from other files." - }, - "disableInFiles": { - "description": "A list of files / glob patterns in which to disable tab autocomplete. For example, *.csv if you'd like to disable autocomplete in .csv files.", - "type": "array", - "items": { - "type": "string" - } - } - }, - "required": [] - }, - "ui": { - "type": "object", - "properties": { - "codeBlockToolbarPosition": { - "enum": [ - "top", - "bottom" - ], - "default": "top", - "description": "Whether to show the copy and apply code buttons at the top or bottom of code blocks in the sidebar." - }, - "fontSize": { - "type": "number" - }, - "displayRawMarkdown": { - "type": "boolean", - "description": "If set to true, we will display the model output as raw markdown.", - "default": false - }, - "showChatScrollbar": { - "title": "Show Chat Scrollbar", - "markdownDescription": "If set to `true`, a scrollbar will be displayed in the chat window to navigate through messages.", - "x-intellij-html-description": "If set to true, a scrollbar will be displayed in the chat window to navigate through messages.", - "default": false, - "type": "boolean" - } - } - }, - "analytics": { - "type": "object", - "properties": { - "provider": { - "type": "string", - "enum": [ - "posthog", - "logstash" - ], - "description": "The 3rd party analytics provider to use.", - "default": "posthog", - "markdownEnumDescriptions": [ - "### Posthog\nTo use Posthog, set up an account, obtain your client key, and enter it in the client key field.", - "### Logstash\nContinue's Logstash integration uses the TCP input at the specified URL" - ] - }, - "url": { - "type": "string", - "description": "The URL to which analytics will be sent" - }, - "clientKey": { - "type": "string", - "description": "The client key to use for analytics" - } - }, - "required": [ - "provider" - ], - "allOf": [ - { - "if": { - "properties": { - "provider": { - "enum": [ - "posthog" - ] - } - } - }, - "then": { - "required": [ - "clientKey" - ] - } - }, - { - "if": { - "properties": { - "provider": { - "enum": [ - "logstash" - ] - } - } - }, - "then": { - "required": [ - "url" - ] - } - } - ] - }, - "experimental": { - "type": "object", - "title": "Experimental", - "description": "Experimental properties are subject to change.", - "properties": { - "defaultContext": { - "type": "array", - "items": { - "allOf": [ - { - "$ref": "#/definitions/ContextProviderWithParams" - }, - { - "properties": { - "query": { - "type": "string", - "description": "Required for certain context providers, like 'url' in order to specify the input, or which of the dropdown items to select." - } - } - } - ] - } - }, - "modelRoles": { - "type": "object", - "properties": { - "inlineEdit": { - "description": "The 'title' property of the model you wish to use for inline edits", - "type": "string" - }, - "applyCodeBlock": { - "description": "The 'title' property of the model you wish to use for applying code blocks", - "type": "string" - }, - "repoMapFileSelection": { - "description": "The 'title' property of the model you wish to use for repo map file selections", - "type": "string" - } - } - }, - "readResponseTTS": { - "type": "boolean", - "default": true, - "description": "Automatically read LLM chat responses aloud using system TTS models" - }, - "promptPath": { - "type": "string" - }, - "quickActions": { - "type": "array", - "items": { - "type": "object", - "properties": { - "title": { - "type": "string", - "description": "The title of the quick action that will display in the Code Lens." - }, - "prompt": { - "type": "string", - "description": "The prompt that will be sent to the model when the quick action is invoked, with the function or class body concatenated." - }, - "sendToChat": { - "type": "boolean", - "description": "If true, the result of the quick action will be sent to the chat panel. If false, the streamed result will be inserted into the document.", - "default": false - } - }, - "required": [ - "prompt", - "title" - ] - }, - "description": "Quick actions are a way to add custom commands to the Code Lens of function and class declarations." - }, - "contextMenuPrompts": { - "type": "object", - "properties": { - "comment": { - "type": "string", - "default": "Write comments for this code. Do not change anything about the code itself." - }, - "docstring": { - "type": "string", - "default": "Write a docstring for this code. Do not change anything about the code itself." - }, - "fix": { - "type": "string", - "default": "Fix this code" - }, - "optimize": { - "type": "string", - "default": "Optimize this code" - }, - "fixGrammar": { - "type": "string", - "default": "If there are any grammar or spelling mistakes in this writing, fix them. Do not make other large changes to the writing." - } - } - } - } - }, - "mergeBehavior": { - "type": "string", - "enum": [ - "merge", - "overwrite" - ], - "default": "merge", - "title": "Merge behavior", - "markdownDescription": "If set to 'merge', .continuerc.json will be applied on top of config.json (arrays and objects are merged). If set to 'overwrite', then every top-level property of .continuerc.json will overwrite that property from config.json." - } - } - } - } -} \ No newline at end of file diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index 8d89156cc..2261f938e 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -280,7 +280,7 @@ export class VsCodeExtension { vscode.workspace.onDidDeleteFiles(async (event) => { this.core.invoke("index/forceReIndex", { - dirs: event.files.map((file) => file.fsPath) + dirs: event.files.map((file) => file.fsPath.split("/").slice(0, -1).join("/")) }) }) From 6284eeebef984ac1afd3846b606a7745c5dfb49d Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Thu, 7 Nov 2024 16:59:23 +0700 Subject: [PATCH 68/96] fix: cursor position --- .../context/root-path-context/RootPathContextService.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/autocomplete/context/root-path-context/RootPathContextService.test.ts b/core/autocomplete/context/root-path-context/RootPathContextService.test.ts index 87795611b..ccce0b6ac 100644 --- a/core/autocomplete/context/root-path-context/RootPathContextService.test.ts +++ b/core/autocomplete/context/root-path-context/RootPathContextService.test.ts @@ -74,7 +74,7 @@ export async function testRootPathContext( throw new Error("AST is undefined"); } - const treePath = await getTreePathAtCursor(ast, rangeToFill.start.character); + const treePath = await getTreePathAtCursor(ast, prefix.length); const snippets = await service.getContextForPath(startPath, treePath); expectedSnippets.forEach((expectedSnippet) => { From 38131a0e7fa205939c47d4d854aa15b39fcf8958 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 7 Nov 2024 02:28:57 -0800 Subject: [PATCH 69/96] openai prediction take 1 --- core/index.d.ts | 1 + core/llm/llms/OpenAI.ts | 24 +++++++++++++++++++++++- extensions/vscode/config_schema.json | 5 +++++ 3 files changed, 29 insertions(+), 1 deletion(-) diff --git a/core/index.d.ts b/core/index.d.ts index 5b0b892f6..d73385dbe 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -794,6 +794,7 @@ interface BaseCompletionOptions { keepAlive?: number; raw?: boolean; stream?: boolean; + predictionContent?: string; } export interface ModelCapability { diff --git a/core/llm/llms/OpenAI.ts b/core/llm/llms/OpenAI.ts index b626a9698..110e1e8ff 100644 --- a/core/llm/llms/OpenAI.ts +++ b/core/llm/llms/OpenAI.ts @@ -95,7 +95,14 @@ class OpenAI extends BaseLLM { ); } - protected _convertArgs(options: any, messages: ChatMessage[]) { + private supportsPrediction(model: string): boolean { + return [ + "gpt-4o-mini", + "gpt-4o" + ].includes(model); + } + + protected _convertArgs(options: CompletionOptions, messages: ChatMessage[]) { const url = new URL(this.apiBase!); const finalOptions: any = { messages: messages.map(this._convertMessage), @@ -135,6 +142,21 @@ class OpenAI extends BaseLLM { ); } + if (options.predictionContent && this.supportsPrediction(options.model)) { + if (finalOptions.presence_penalty) { // prediction doesn't support > 0 + finalOptions.presence_penalty = undefined; + } + if (finalOptions.frequency_penalty) { // prediction doesn't support > 0 + finalOptions.frequency_penalty = undefined; + } + finalOptions.max_completion_tokens = undefined; + + finalOptions.prediction = { + "type": "content", + "content": options.predictionContent + }; + } + return finalOptions; } diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index f18bdbb6a..3f4b90b19 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -65,6 +65,11 @@ "title": "Ollama keep_alive", "description": "The number of seconds after no requests are made to unload the model from memory. Defaults to 60*30 = 30min", "type": "integer" + }, + "predictionContent": { + "title": "Prediction", + "description": "(gpt-4o/gpt-4o-mini only) Prediction output which can greatly improve response times when large parts of the model response are known ahead of time. This is most common when you are regenerating a file with only minor changes to most of the content.", + "type": "string" } } }, From b3b7b5b9cab7048d8f84b51d6eb56d8b7408d60c Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 7 Nov 2024 02:46:29 -0800 Subject: [PATCH 70/96] prediction full implementation --- core/index.d.ts | 10 +++++- core/llm/llms/OpenAI.ts | 7 ++-- extensions/vscode/config_schema.json | 50 ++++++++++++++++++++++++++-- 3 files changed, 59 insertions(+), 8 deletions(-) diff --git a/core/index.d.ts b/core/index.d.ts index d73385dbe..ef8b7c128 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -780,6 +780,14 @@ export interface CustomCommand { description: string; } +interface Prediction { + type: "content" + content: string | { + type: "text" + text: string + }[] +} + interface BaseCompletionOptions { temperature?: number; topP?: number; @@ -794,7 +802,7 @@ interface BaseCompletionOptions { keepAlive?: number; raw?: boolean; stream?: boolean; - predictionContent?: string; + prediction?: Prediction; } export interface ModelCapability { diff --git a/core/llm/llms/OpenAI.ts b/core/llm/llms/OpenAI.ts index 110e1e8ff..168e0afff 100644 --- a/core/llm/llms/OpenAI.ts +++ b/core/llm/llms/OpenAI.ts @@ -142,7 +142,7 @@ class OpenAI extends BaseLLM { ); } - if (options.predictionContent && this.supportsPrediction(options.model)) { + if (options.prediction && this.supportsPrediction(options.model)) { if (finalOptions.presence_penalty) { // prediction doesn't support > 0 finalOptions.presence_penalty = undefined; } @@ -151,10 +151,7 @@ class OpenAI extends BaseLLM { } finalOptions.max_completion_tokens = undefined; - finalOptions.prediction = { - "type": "content", - "content": options.predictionContent - }; + finalOptions.prediction = options.prediction; } return finalOptions; diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index 3f4b90b19..e3736a3bb 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -66,10 +66,56 @@ "description": "The number of seconds after no requests are made to unload the model from memory. Defaults to 60*30 = 30min", "type": "integer" }, - "predictionContent": { + "prediction": { "title": "Prediction", "description": "(gpt-4o/gpt-4o-mini only) Prediction output which can greatly improve response times when large parts of the model response are known ahead of time. This is most common when you are regenerating a file with only minor changes to most of the content.", - "type": "string" + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "content" + ], + "description": "Currently only 'content' type supported" + }, + "content": { + "description": "Predicted output (usually contents of a file)", + "anyOf": [ + { + "type": "string", + "description": "Predicted output (usually contents of a file)" + }, + { + "type": "array", + "description": "Array of predicted output text items (usually pieces of a file)", + "items": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "text" + ], + "description": "Currently only 'text' supported" + }, + "text": { + "type": "string", + "description": "Predicted output item text" + } + }, + "required": [ + "type", + "text" + ] + } + } + ] + } + }, + "required": [ + "type", + "content" + ] } } }, From 71a151f399d514497ee917eca521863d07b2a270 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Thu, 7 Nov 2024 19:32:26 +0700 Subject: [PATCH 71/96] fix: test env path --- core/util/treeSitter.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/core/util/treeSitter.ts b/core/util/treeSitter.ts index 08cfe64d1..bf6891f23 100644 --- a/core/util/treeSitter.ts +++ b/core/util/treeSitter.ts @@ -115,6 +115,7 @@ export async function getLanguageForFile( return undefined; } let language = nameToLanguage.get(languageName); + if (!language) { language = await loadLanguageForFileExt(extension); nameToLanguage.set(languageName, language); @@ -149,7 +150,9 @@ export async function getQueryForFile( const sourcePath = path.join( __dirname, "..", - "tree-sitter", + ...(process.env.NODE_ENV === "test" + ? ["extensions", "vscode", "tree-sitter"] + : ["tree-sitter"]), queryType, `${fullLangName}.scm`, ); From 0e166fcf32ee637f5776c954432c720da9854ab3 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 7 Nov 2024 09:18:34 -0800 Subject: [PATCH 72/96] remove prediction from config_schema.json --- extensions/vscode/config_schema.json | 51 ---------------------------- 1 file changed, 51 deletions(-) diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index e3736a3bb..f18bdbb6a 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -65,57 +65,6 @@ "title": "Ollama keep_alive", "description": "The number of seconds after no requests are made to unload the model from memory. Defaults to 60*30 = 30min", "type": "integer" - }, - "prediction": { - "title": "Prediction", - "description": "(gpt-4o/gpt-4o-mini only) Prediction output which can greatly improve response times when large parts of the model response are known ahead of time. This is most common when you are regenerating a file with only minor changes to most of the content.", - "type": "object", - "properties": { - "type": { - "type": "string", - "enum": [ - "content" - ], - "description": "Currently only 'content' type supported" - }, - "content": { - "description": "Predicted output (usually contents of a file)", - "anyOf": [ - { - "type": "string", - "description": "Predicted output (usually contents of a file)" - }, - { - "type": "array", - "description": "Array of predicted output text items (usually pieces of a file)", - "items": { - "type": "object", - "properties": { - "type": { - "type": "string", - "enum": [ - "text" - ], - "description": "Currently only 'text' supported" - }, - "text": { - "type": "string", - "description": "Predicted output item text" - } - }, - "required": [ - "type", - "text" - ] - } - } - ] - } - }, - "required": [ - "type", - "content" - ] } } }, From 0f3bc0e5b5983daf1ce655aebf87fd0c6ba936e1 Mon Sep 17 00:00:00 2001 From: Sherman Boyd Date: Thu, 7 Nov 2024 12:41:04 -0800 Subject: [PATCH 73/96] Implemented fancy keys for all keyboard shortcut expressions. Added a margin to tag so it doesn't crowd text: especially parens --- docs/docs/actions/how-to-use-it.md | 8 ++++---- docs/docs/autocomplete/context-selection.md | 2 +- docs/docs/autocomplete/how-to-use-it.md | 6 +++--- docs/docs/chat/context-selection.md | 4 ++-- docs/docs/chat/how-it-works.md | 2 +- docs/docs/chat/how-to-use-it.md | 6 +++--- docs/docs/customize/deep-dives/autocomplete.md | 10 +++++----- docs/docs/customize/deep-dives/codebase.md | 2 +- docs/docs/customize/deep-dives/prompt-files.md | 2 +- docs/docs/edit/how-to-use-it.md | 8 ++++---- docs/docs/telemetry.md | 2 +- docs/docs/troubleshooting.md | 6 +++--- docs/src/css/custom.css | 1 + 13 files changed, 30 insertions(+), 29 deletions(-) diff --git a/docs/docs/actions/how-to-use-it.md b/docs/docs/actions/how-to-use-it.md index 3e7c04644..5be83b2e7 100644 --- a/docs/docs/actions/how-to-use-it.md +++ b/docs/docs/actions/how-to-use-it.md @@ -14,7 +14,7 @@ Actions are shortcuts for common use cases. For example, you might want to revie ### Slash commands -The most common way to invoke an action is with a slash command. These are shortcuts that can be activated by typing '/' in a chat session (press cmd/ctrl + L (VS Code) or cmd/ctrl + J (JetBrains)), and selecting from the dropdown. For example, the built-in '/edit' slash command lets you stream edits directly into your editor. +The most common way to invoke an action is with a slash command. These are shortcuts that can be activated by typing '/' in a chat session (press cmd/ctrl + L (VS Code) or cmd/ctrl + J (JetBrains)), and selecting from the dropdown. For example, the built-in '/edit' slash command lets you stream edits directly into your editor. ![slash-commands](/img/slash-commands.png) @@ -48,7 +48,7 @@ Write unit tests for the above selected code, following each of these instructio - Don't explain how to set up `jest` ``` -Now to use this prompt, you can highlight code and use `cmd/ctrl+L` to select it in the Continue sidebar. +Now to use this prompt, you can highlight code and use cmd/ctrl + L to select it in the Continue sidebar. Then, type "/" to see the list of slash commands and choose the one called "test". Press enter and the LLM will respond given the instructions from your prompt file. @@ -76,10 +76,10 @@ Right click actions let you highlight a desired region of code, right click, and #### Debug action -The debug action is a special built-in keyboard shortcut in the VS Code extension. Use `cmd/ctrl+shift+R` to instantly copy the contents of the current terminal into the chat sidebar and get debugging advice. +The debug action is a special built-in keyboard shortcut in the VS Code extension. Use cmd/ctrl + shift + R to instantly copy the contents of the current terminal into the chat sidebar and get debugging advice. #### Quick fixes -Whenever you see red/yellow underlines in your code indicating errors, you can place your cursor nearby and VS Code will display a lightbulb icon. Either clicking the lightbulb or using the keyboard shortcut `cmd/ctrl+.` will show a dropdown menu of quick fixes. One of these will be the “Ask Continue” action. Either click or use `cmd/ctrl+.` again and Continue will attempt to help solve the problem. +Whenever you see red/yellow underlines in your code indicating errors, you can place your cursor nearby and VS Code will display a lightbulb icon. Either clicking the lightbulb or using the keyboard shortcut cmd/ctrl + . will show a dropdown menu of quick fixes. One of these will be the “Ask Continue” action. Either click or use cmd/ctrl + . again and Continue will attempt to help solve the problem. ![ask-continue](/img/ask-continue.png) diff --git a/docs/docs/autocomplete/context-selection.md b/docs/docs/autocomplete/context-selection.md index e85e3d4bd..f237a3625 100644 --- a/docs/docs/autocomplete/context-selection.md +++ b/docs/docs/autocomplete/context-selection.md @@ -13,7 +13,7 @@ We will always include the code from your file prior to and after the cursor pos ### Definitions from the Language Server Protocol -Similar to how you can use `cmd/ctrl + click` in your editor, we use the same tool (the LSP) to power "go to definition". For example, if you are typing out a function call, we will include the function definition. Or, if you are writing code inside of a method, we will include the type definitions for any parameters or the return type. +Similar to how you can use cmd/ctrl + `click` in your editor, we use the same tool (the LSP) to power "go to definition". For example, if you are typing out a function call, we will include the function definition. Or, if you are writing code inside of a method, we will include the type definitions for any parameters or the return type. ### Imported files diff --git a/docs/docs/autocomplete/how-to-use-it.md b/docs/docs/autocomplete/how-to-use-it.md index 92a3db76e..5fd127ce5 100644 --- a/docs/docs/autocomplete/how-to-use-it.md +++ b/docs/docs/autocomplete/how-to-use-it.md @@ -14,12 +14,12 @@ Autocomplete provides inline code suggestions as you type. To enable it, simply ### Accepting a full suggestion -Accept a full suggestion by pressing `Tab` +Accept a full suggestion by pressing Tab ### Rejecting a full suggestion -Reject a full suggestion with `Esc` +Reject a full suggestion with Esc ### Partially accepting a suggestion -For more granular control, use `cmd/ctrl + →` to accept parts of the suggestion word-by-word. +For more granular control, use cmd/ctrl + → to accept parts of the suggestion word-by-word. diff --git a/docs/docs/chat/context-selection.md b/docs/docs/chat/context-selection.md index ebdb41185..072bc0128 100644 --- a/docs/docs/chat/context-selection.md +++ b/docs/docs/chat/context-selection.md @@ -11,11 +11,11 @@ Typing a question or instructions into the input box is the only required contex ## Highlighted code -The highlighted code you’ve selected by pressing `cmd/ctrl + L` (VS Code) or `cmd/ctrl + J` (JetBrains) will be included in your prompt alongside the input you provide. This is the only section of code that will be provided to the model unless you highlight additional sections or use one of the other selection methods below. +The highlighted code you’ve selected by pressing cmd/ctrl + L (VS Code) or cmd/ctrl + J (JetBrains) will be included in your prompt alongside the input you provide. This is the only section of code that will be provided to the model unless you highlight additional sections or use one of the other selection methods below. ## Active file -You can include the currently open file as context by pressing `cmd/ctrl + opt + enter` when you send your request. +You can include the currently open file as context by pressing cmd/ctrl + opt + enter when you send your request. ## Specific file diff --git a/docs/docs/chat/how-it-works.md b/docs/docs/chat/how-it-works.md index b5e8aaece..84c81582e 100644 --- a/docs/docs/chat/how-it-works.md +++ b/docs/docs/chat/how-it-works.md @@ -7,7 +7,7 @@ sidebar_position: 4 Using any selected code sections, all context that you have selected with @, and your input instructions, we prompt the model to provide a response in the sidebar. If you are asking a follow-up, then all earlier session context is also included. No other additional context is provided to the model. -The model response is then streamed directly back to the sidebar. Each code section included in the response will be placed into its own code block, which gives you buttons to either “Apply to current file”, “Insert at cursor”, or “Copy” for each section. When you press `cmd/ctrl + L` (VS Code) or `cmd/ctrl + J` (JetBrains) at the end of a session, all context is cleared and a new session is started, so that you can begin a new task. +The model response is then streamed directly back to the sidebar. Each code section included in the response will be placed into its own code block, which gives you buttons to either “Apply to current file”, “Insert at cursor”, or “Copy” for each section. When you press cmd/ctrl + L (VS Code) or cmd/ctrl + J (JetBrains) at the end of a session, all context is cleared and a new session is started, so that you can begin a new task. 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). diff --git a/docs/docs/chat/how-to-use-it.md b/docs/docs/chat/how-to-use-it.md index 509702b4f..112649aeb 100644 --- a/docs/docs/chat/how-to-use-it.md +++ b/docs/docs/chat/how-to-use-it.md @@ -20,7 +20,7 @@ You send it a question, and it replies with an answer. You tell it to solve a pr ## Highlight a code section to include as context -You select a code section with your mouse, press `cmd/ctrl + L` (VS Code) or `cmd/ctrl + J` (JetBrains) to send it to the LLM, and then ask for it to be explained to you or request it to be refactored in some way. +You select a code section with your mouse, press cmd/ctrl + L (VS Code) or cmd/ctrl + J (JetBrains) to send it to the LLM, and then ask for it to be explained to you or request it to be refactored in some way. ## Reference context with the @ symbol @@ -32,8 +32,8 @@ When the LLM replies with edits to a file, you can click the “Apply” button. ## Start a fresh session for a new task -Once you complete a task and want to start a new one, press `cmd/ctrl + L` (VS Code) or `cmd/ctrl + J` (JetBrains) to begin a new session, ensuring only relevant context for the next task is provided to the LLM. +Once you complete a task and want to start a new one, press cmd/ctrl + L (VS Code) or cmd/ctrl + J (JetBrains) to begin a new session, ensuring only relevant context for the next task is provided to the LLM. ## Switch between different models -If you have configured multiple models, you can switch between models using the dropdown or by pressing `cmd/ctrl + ’` +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/deep-dives/autocomplete.md b/docs/docs/customize/deep-dives/autocomplete.md index 9e406416d..bb7e0f770 100644 --- a/docs/docs/customize/deep-dives/autocomplete.md +++ b/docs/docs/customize/deep-dives/autocomplete.md @@ -103,8 +103,8 @@ Follow these steps to ensure that everything is set up correctly: 2. Make sure you have downloaded Ollama. 3. Run `ollama run starcoder2:3b` to verify that the model is downloaded. 4. Make sure that any other completion providers are disabled (e.g. Copilot), as they may interfere. -5. Check the output of the logs to find any potential errors (cmd/ctrl+shift+p -> "Toggle Developer Tools" -> "Console" tab in VS Code, ~/.continue/logs/core.log in JetBrains). -6. Check VS Code settings to make sure that `"editor.inlineSuggest.enabled"` is set to `true` (use cmd/ctrl+, then search for this and check the box) +5. Check the output of the logs to find any potential errors: cmd/ctrl + shift + P -> "Toggle Developer Tools" -> "Console" tab in VS Code, ~/.continue/logs/core.log in JetBrains. +6. Check VS Code settings to make sure that `"editor.inlineSuggest.enabled"` is set to `true` (use cmd/ctrl + , then search for this and check the box) 7. If you are still having issues, please let us know in our [Discord](https://discord.gg/vapESyrFmJ) and we'll help as soon as possible. ### Completions are slow @@ -122,8 +122,8 @@ 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 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`) -5. Now whenever you want to see a suggestion, you can press your key binding (e.g. `ctrl+space`) to trigger suggestions manually +4. Press the key combination you want to use to trigger suggestions (e.g. cmd/ctrl + space) +5. Now whenever you want to see a suggestion, you can press your key binding (e.g. cmd/ctrl + space) to trigger suggestions manually ### Is there a shortcut to accept one line at a time? @@ -137,7 +137,7 @@ Click the "Continue" button in the status panel at the bottom right of the scree Alternatively, open VS Code settings, search for "Continue" and uncheck the box for "Enable Tab Autocomplete". -You can also use the default shortcut to disable autocomplete directly: press `ctrl/cmd + K`, `ctrl/cmd + A`. This will turn off autocomplete without navigating through settings. +You can also use the default shortcut to disable autocomplete directly using a chord: press and hold ctrl/cmd + K (continue holding ctrl/cmd) and press ctrl/cmd + A. This will turn off autocomplete without navigating through settings. #### JetBrains diff --git a/docs/docs/customize/deep-dives/codebase.md b/docs/docs/customize/deep-dives/codebase.md index f106fea14..4da920943 100644 --- a/docs/docs/customize/deep-dives/codebase.md +++ b/docs/docs/customize/deep-dives/codebase.md @@ -75,7 +75,7 @@ Continue also supports a **global** `.continueignore` file that will be respecte 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". +If you need to force a refresh of the index, reload the VS Code window with cmd/ctrl + shift + p + "Reload Window". ## Repository map diff --git a/docs/docs/customize/deep-dives/prompt-files.md b/docs/docs/customize/deep-dives/prompt-files.md index 1c70d729c..928e01543 100644 --- a/docs/docs/customize/deep-dives/prompt-files.md +++ b/docs/docs/customize/deep-dives/prompt-files.md @@ -35,7 +35,7 @@ Write unit tests for the above selected code, following each of these instructio - Don't explain how to set up `jest` ``` -Now to use this prompt, you can highlight code and use `cmd/ctrl + L` to select it in the Continue sidebar. +Now to use this prompt, you can highlight code and use cmd/ctrl + L to select it in the Continue sidebar. Then, type "/" to see the list of slash commands and choose the one called "test". Press enter and the LLM will respond given the instructions from your prompt file. diff --git a/docs/docs/edit/how-to-use-it.md b/docs/docs/edit/how-to-use-it.md index 4dbed98d8..850c34b60 100644 --- a/docs/docs/edit/how-to-use-it.md +++ b/docs/docs/edit/how-to-use-it.md @@ -20,7 +20,7 @@ Edit is best used for small, quick changes such as: ## Highlight code and activate -Highlight the block of code you would like to modify, and press `cmd/ctrl + i` to activate the edit input. +Highlight the block of code you would like to modify, and press cmd/ctrl + i to activate the edit input. ## Describe code changes @@ -30,8 +30,8 @@ Describe the changes you would like the model to make to your highlighted code. Proposed changes appear as inline diffs within your highlighted text. -You can navigate through each proposed change, accepting or rejecting them using `cmd/ctrl + opt + y` (to accept) or `cmd/ctrl + opt + n` (to reject). +You can navigate through each proposed change, accepting or rejecting them using cmd/ctrl + opt + y (to accept) or cmd/ctrl + opt + n (to reject). -You can also accept or reject all changes at once using `cmd/ctrl + shift + enter` (to accept) or `cmd/ctrl + shift + delete` (to reject). +You can also accept or reject all changes at once using cmd/ctrl + shift + enter (to accept) or cmd/ctrl + shift + delete/backspace (to reject). -If you want to request a new suggestion for the same highlighted code section, you can use `cmd/ctrl + i` to re-prompt the model. +If you want to request a new suggestion for the same highlighted code section, you can use cmd/ctrl + i to re-prompt the model. diff --git a/docs/docs/telemetry.md b/docs/docs/telemetry.md index a72a6e77a..8e7152d01 100644 --- a/docs/docs/telemetry.md +++ b/docs/docs/telemetry.md @@ -46,6 +46,6 @@ To opt out, change the value of `allowAnonymousTelemetry` to `false`. Alternativ ### Steps to Disable Telemetry via VS Code Settings 1. Open VS Code. -2. Navigate to `File` > `Preferences` > `Settings` (or use the keyboard shortcut `Ctrl + ,` on Windows/Linux or `Cmd + ,` on macOS). +2. Navigate to `File` > `Preferences` > `Settings` (or use the keyboard shortcut ctrl + , on Windows/Linux or cmd + , on macOS). 3. In the search bar, type "Continue: Telemetry Enabled". 4. Uncheck the "Continue: Telemetry Enabled" checkbox. diff --git a/docs/docs/troubleshooting.md b/docs/docs/troubleshooting.md index d10d2c104..d4bbe69db 100644 --- a/docs/docs/troubleshooting.md +++ b/docs/docs/troubleshooting.md @@ -24,7 +24,7 @@ To solve many problems, the first step is reading the logs to find the relevant In order to view debug logs, which contain extra information, click the dropdown at the top that says "Default levels" and select "Verbose". ::: -1. `cmd+shift+p` (MacOS) / `ctrl+shift+p` (Windows) +1. cmd + shift + P for MacOS or ctrl + shift + P for Windows 2. Search for and then select "Developer: Toggle Developer Tools" 3. This will open the [Chrome DevTools window](https://developer.chrome.com/docs/devtools/) 4. Select the `Console` tab @@ -56,7 +56,7 @@ We are constantly making fixes and improvements to Continue, but the latest chan On JetBrains, the "pre-release" happens through their Early Access Program (EAP) channel. To download the latest EAP version, enable the EAP channel: -1. Open JetBrains settings (`cmd/ctrl + ,`) and go to "Plugins" +1. Open JetBrains settings (cmd/ctrl + ,) and go to "Plugins" 2. Click the gear icon at the top 3. Select "Manage Plugin Repositories..." 4. Add "[https://plugins.jetbrains.com/plugins/eap/list](https://plugins.jetbrains.com/plugins/eap/list)" to the list @@ -104,7 +104,7 @@ You may also set `requestOptions.caBundlePath` to an array of paths to multiple #### VS Code Proxy Settings -If you are using VS Code and require requests to be made through a proxy, you are likely already set up through VS Code's [Proxy Server Support](https://code.visualstudio.com/docs/setup/network#_proxy-server-support). To double-check that this is enabled, use cmd/ctrl+, to open settings and search for "Proxy Support". Unless it is set to "off", then VS Code is responsible for making the request to the proxy. +If you are using VS Code and require requests to be made through a proxy, you are likely already set up through VS Code's [Proxy Server Support](https://code.visualstudio.com/docs/setup/network#_proxy-server-support). To double-check that this is enabled, use cmd/ctrl + , to open settings and search for "Proxy Support". Unless it is set to "off", then VS Code is responsible for making the request to the proxy. #### code-server diff --git a/docs/src/css/custom.css b/docs/src/css/custom.css index 6002807cc..f0b798f64 100644 --- a/docs/src/css/custom.css +++ b/docs/src/css/custom.css @@ -47,6 +47,7 @@ kbd { display: inline-block; padding: 0.3em 0.4em; + margin: 0.1em .4em; font-family: var(--ifm-font-family-monospace); font-size: .8rem; font-weight: 500; From 885e7c138d725dfed88d9165df99f1f692c49fb8 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 7 Nov 2024 12:58:13 -0800 Subject: [PATCH 74/96] integer progress percentage --- .../More/IndexingProgress/IndexingProgressIndicator.tsx | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/gui/src/pages/More/IndexingProgress/IndexingProgressIndicator.tsx b/gui/src/pages/More/IndexingProgress/IndexingProgressIndicator.tsx index dbfb44f64..852cdf845 100644 --- a/gui/src/pages/More/IndexingProgress/IndexingProgressIndicator.tsx +++ b/gui/src/pages/More/IndexingProgress/IndexingProgressIndicator.tsx @@ -27,14 +27,13 @@ function IndexingProgressIndicator({ update }: IndexingProgressIndicatorProps) { return (
- {showProgress && {progressPercentage}%} + {showProgress && {progressPercentage.toFixed(0)}%} {Icon && (
)} From 0fac5aad1f5640bb9d4eff9841cd0dcb884a3579 Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 7 Nov 2024 15:13:23 -0800 Subject: [PATCH 75/96] predicted completions for Edit and Apply --- core/edit/streamDiffLines.ts | 18 ++++++++++-------- extensions/vscode/package-lock.json | 2 +- 2 files changed, 11 insertions(+), 9 deletions(-) diff --git a/core/edit/streamDiffLines.ts b/core/edit/streamDiffLines.ts index dbab5841c..48466d0d3 100644 --- a/core/edit/streamDiffLines.ts +++ b/core/edit/streamDiffLines.ts @@ -8,12 +8,7 @@ import { } from "../autocomplete/streamTransforms/lineStream.js"; import { streamDiff } from "../diff/streamDiff.js"; import { streamLines } from "../diff/util.js"; -import { - ChatMessage, - DiffLine, - ILLM, - LLMFullCompletionOptions, -} from "../index.js"; +import { ChatMessage, DiffLine, ILLM, Prediction } from "../index.js"; import { gptEditPrompt } from "../llm/templates/edit.js"; import { Telemetry } from "../util/posthog.js"; @@ -94,10 +89,17 @@ export async function* streamDiffLines( ); const inept = modelIsInept(llm.model); + const prediction: Prediction = { + type: "content", + content: highlighted, + }; + const completion = typeof prompt === "string" - ? llm.streamComplete(prompt, { raw: true }) - : llm.streamChat(prompt); + ? llm.streamComplete(prompt, { raw: true, prediction }) + : llm.streamChat(prompt, { + prediction, + }); let lines = streamLines(completion); diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 3baee50b0..466cd705e 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -12599,4 +12599,4 @@ } } } -} \ No newline at end of file +} From 18d09436b681423ab999b7321fc10c773d0d0a50 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 7 Nov 2024 15:19:05 -0800 Subject: [PATCH 76/96] get current file returns contents and untitled status --- core/config/promptFile.ts | 7 +- core/config/types.ts | 6 +- .../providers/CurrentFileContextProvider.ts | 12 ++- core/index.d.ts | 6 +- .../promptFiles/slashCommandFromPromptFile.ts | 8 +- core/protocol/ide.ts | 6 +- core/util/filesystem.ts | 10 +-- core/util/messageIde.ts | 2 +- .../continue/IdeProtocolClient.kt | 10 ++- .../continueintellijextension/continue/a test | 2 + extensions/vscode/package-lock.json | 2 +- extensions/vscode/src/VsCodeIde.ts | 74 ++++++++++++++++++- .../vscode/src/extension/VsCodeExtension.ts | 5 +- .../src/test/test-suites/ideUtils.test.ts | 7 -- extensions/vscode/src/util/ideUtils.ts | 57 +------------- gui/src/hooks/useChatHandler.ts | 24 +++--- 16 files changed, 127 insertions(+), 111 deletions(-) create mode 100644 extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/a test diff --git a/core/config/promptFile.ts b/core/config/promptFile.ts index ebbbd59ab..a22dfadde 100644 --- a/core/config/promptFile.ts +++ b/core/config/promptFile.ts @@ -152,15 +152,12 @@ async function renderPrompt(prompt: string, context: any, userInput: string) { // A few context providers that don't need to be in config.json to work in .prompt files const diff = await context.ide.getDiff(false); - const currentFilePath = await context.ide.getCurrentFile(); - const currentFile = currentFilePath - ? await context.ide.readFile(currentFilePath) - : undefined; + const currentFile = await context.ide.getCurrentFile(); return renderTemplatedString( prompt, context.ide.readFile.bind(context.ide), - { diff, currentFile, input: userInput }, + { diff, currentFile: currentFile?.contents, input: userInput }, helpers, ); } diff --git a/core/config/types.ts b/core/config/types.ts index ca8ee9bec..b886ea021 100644 --- a/core/config/types.ts +++ b/core/config/types.ts @@ -463,7 +463,11 @@ declare global { stepIndex: number, ): Promise; getOpenFiles(): Promise; - getCurrentFile(): Promise; + getCurrentFile(): Promise; getPinnedFiles(): Promise; getSearchResults(query: string): Promise; subprocess(command: string): Promise<[string, string]>; diff --git a/core/context/providers/CurrentFileContextProvider.ts b/core/context/providers/CurrentFileContextProvider.ts index 575350b49..5e75f85c8 100644 --- a/core/context/providers/CurrentFileContextProvider.ts +++ b/core/context/providers/CurrentFileContextProvider.ts @@ -24,17 +24,15 @@ class CurrentFileContextProvider extends BaseContextProvider { if (!currentFile) { return []; } - const contents = await ide.readFile(currentFile); + const baseName = getBasename(currentFile.path); return [ { - description: currentFile, - content: `This is the currently open file:\n\n\`\`\`${getBasename( - currentFile, - )}\n${contents}\n\`\`\``, - name: getBasename(currentFile), + description: currentFile.path, + content: `This is the currently open file:\n\n\`\`\`${baseName}\n${currentFile.contents}\n\`\`\``, + name: baseName, uri: { type: "file", - value: currentFile, + value: currentFile.path, }, }, ]; diff --git a/core/index.d.ts b/core/index.d.ts index 5b0b892f6..071d61814 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -494,7 +494,11 @@ export interface IDE { stepIndex: number, ): Promise; getOpenFiles(): Promise; - getCurrentFile(): Promise; + getCurrentFile(): Promise; getPinnedFiles(): Promise; getSearchResults(query: string): Promise; subprocess(command: string, cwd?: string): Promise<[string, string]>; diff --git a/core/promptFiles/slashCommandFromPromptFile.ts b/core/promptFiles/slashCommandFromPromptFile.ts index e81f13615..3df3cb8fe 100644 --- a/core/promptFiles/slashCommandFromPromptFile.ts +++ b/core/promptFiles/slashCommandFromPromptFile.ts @@ -38,12 +38,8 @@ export function extractUserInput(input: string, commandName: string): string { } export async function getDefaultVariables(context: any, userInput: string) { - const currentFilePath = await context.ide.getCurrentFile(); - const currentFile = currentFilePath - ? await context.ide.readFile(currentFilePath) - : undefined; - - return { currentFile, input: userInput }; + const currentFile = await context.ide.getCurrentFile(); + return { currentFile: currentFile?.contents, input: userInput }; } export async function renderPrompt( diff --git a/core/protocol/ide.ts b/core/protocol/ide.ts index eda6bebfb..d6b6a90d3 100644 --- a/core/protocol/ide.ts +++ b/core/protocol/ide.ts @@ -48,7 +48,11 @@ export type ToIdeFromWebviewOrCoreProtocol = { ]; getProblems: [{ filepath: string }, Problem[]]; getOpenFiles: [undefined, string[]]; - getCurrentFile: [undefined, string | undefined]; + getCurrentFile: [undefined, undefined | { + isUntitled: boolean; + path: string; + contents: string; + }]; getPinnedFiles: [undefined, string[]]; showLines: [{ filepath: string; startLine: number; endLine: number }, void]; readRangeInFile: [{ filepath: string; range: Range }, string]; diff --git a/core/util/filesystem.ts b/core/util/filesystem.ts index 0f64d912c..459e0adee 100644 --- a/core/util/filesystem.ts +++ b/core/util/filesystem.ts @@ -19,7 +19,7 @@ import { GetGhTokenArgs } from "../protocol/ide.js"; import { getContinueGlobalPath } from "./paths.js"; class FileSystemIde implements IDE { - constructor(private readonly workspaceDir: string) {} + constructor(private readonly workspaceDir: string) { } showToast( type: ToastType, message: string, @@ -205,6 +205,10 @@ class FileSystemIde implements IDE { }); } + getCurrentFile(): Promise { + return Promise.resolve(undefined); + } + showDiff( filepath: string, newContents: string, @@ -221,10 +225,6 @@ class FileSystemIde implements IDE { return Promise.resolve([]); } - getCurrentFile(): Promise { - return Promise.resolve(""); - } - getPinnedFiles(): Promise { return Promise.resolve([]); } diff --git a/core/util/messageIde.ts b/core/util/messageIde.ts index 1fab1c6b9..75c980809 100644 --- a/core/util/messageIde.ts +++ b/core/util/messageIde.ts @@ -177,7 +177,7 @@ export class MessageIde implements IDE { return this.request("getOpenFiles", undefined); } - getCurrentFile(): Promise { + getCurrentFile() { return this.request("getCurrentFile", undefined); } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt index 17c89ec85..17a8da024 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt @@ -1006,11 +1006,17 @@ class IdeProtocolClient( // return openFiles.intersect(pinnedFiles).toList() } - private fun currentFile(): String? { + private fun currentFile(): Map? { val fileEditorManager = FileEditorManager.getInstance(project) val editor = fileEditorManager.selectedTextEditor val virtualFile = editor?.document?.let { FileDocumentManager.getInstance().getFile(it) } - return virtualFile?.path + return virtualFile?.let { + mapOf( + "filePath" to it.path, + "fileContents" to editor.document.text, + "isUntitled" to false + ) + } } suspend fun showToast(type: String, content: String, buttonTexts: Array = emptyArray()): String? = diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/a test b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/a test new file mode 100644 index 000000000..246284309 --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/a test @@ -0,0 +1,2 @@ +asdfasdfasdfasd +her's new co \ No newline at end of file diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 3baee50b0..466cd705e 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -12599,4 +12599,4 @@ } } } -} \ No newline at end of file +} diff --git a/extensions/vscode/src/VsCodeIde.ts b/extensions/vscode/src/VsCodeIde.ts index c36516018..5c5e617f4 100644 --- a/extensions/vscode/src/VsCodeIde.ts +++ b/extensions/vscode/src/VsCodeIde.ts @@ -255,6 +255,7 @@ class VsCodeIde implements IDE { return tags; } + getIdeInfo(): Promise { return Promise.resolve({ ideType: "vscode", @@ -266,6 +267,7 @@ class VsCodeIde implements IDE { .version, }); } + readRangeInFile(filepath: string, range: Range): Promise { return this.ideUtils.readRangeInFile( filepath, @@ -342,7 +344,7 @@ class VsCodeIde implements IDE { type === vscode.FileType.SymbolicLink) && filename === ".continuerc.json" ) { - const contents = await this.ideUtils.readFile( + const contents = await this.readFile( vscode.Uri.joinPath(workspaceDir, filename).fsPath, ); configs.push(JSON.parse(contents)); @@ -421,8 +423,66 @@ class VsCodeIde implements IDE { async saveFile(filepath: string): Promise { await this.ideUtils.saveFile(filepath); } + + private static MAX_BYTES = 100000; + async readFile(filepath: string): Promise { - return await this.ideUtils.readFile(filepath); + try { + filepath = this.ideUtils.getAbsolutePath(filepath); + const uri = uriFromFilePath(filepath); + + // First, check whether it's a notebook document + // Need to iterate over the cells to get full contents + const notebook = + vscode.workspace.notebookDocuments.find( + (doc) => doc.uri.toString() === uri.toString(), + ) ?? + (uri.fsPath.endsWith("ipynb") + ? await vscode.workspace.openNotebookDocument(uri) + : undefined); + if (notebook) { + return notebook + .getCells() + .map((cell) => cell.document.getText()) + .join("\n\n"); + } + + // Check if the document is an untitled (new and unsaved) document + const untitledDocs = vscode.workspace.textDocuments.filter( + (doc) => doc.isUntitled && doc, + ); + const untitledDoc = vscode.workspace.textDocuments.find( + (doc) => doc.isUntitled && doc.uri.fsPath === uri.fsPath + ); + if (untitledDoc) { + return untitledDoc.getText(); + } + + // Check whether it's an open document + const openTextDocument = vscode.workspace.textDocuments.find( + (doc) => doc.uri.fsPath === uri.fsPath, + ); + if (openTextDocument !== undefined) { + return openTextDocument.getText(); + } + + const fileStats = await vscode.workspace.fs.stat( + uriFromFilePath(filepath), + ); + if (fileStats.size > 10 * VsCodeIde.MAX_BYTES) { + return ""; + } + + const bytes = await vscode.workspace.fs.readFile(uri); + + // Truncate the buffer to the first MAX_BYTES + const truncatedBytes = bytes.slice(0, VsCodeIde.MAX_BYTES); + const contents = new TextDecoder().decode(truncatedBytes); + return contents; + } catch (e) { + console.warn("Error reading file", e); + return ""; + } } async showDiff( filepath: string, @@ -436,8 +496,13 @@ class VsCodeIde implements IDE { return await this.ideUtils.getOpenFiles(); } - async getCurrentFile(): Promise { - return vscode.window.activeTextEditor?.document.uri.fsPath; + async getCurrentFile() { + if (!vscode.window.activeTextEditor) return undefined + return { + isUntitled: vscode.window.activeTextEditor.document.isUntitled, + path: vscode.window.activeTextEditor.document.uri.fsPath, + contents: vscode.window.activeTextEditor.document.getText() + } } async getPinnedFiles(): Promise { @@ -572,3 +637,4 @@ class VsCodeIde implements IDE { } export { VsCodeIde }; + diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index 2eda0c192..e9f9cbad7 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -278,7 +278,7 @@ export class VsCodeExtension { // Reindex the workspaces this.core.invoke("index/forceReIndex", undefined); } else { - // Reindex the file + // Reindex the filex const indexer = await this.core.codebaseIndexerPromise; indexer.refreshFile(filepath); } @@ -329,8 +329,7 @@ export class VsCodeExtension { // Register a content provider for the readonly virtual documents const documentContentProvider = new (class - implements vscode.TextDocumentContentProvider - { + implements vscode.TextDocumentContentProvider { // emitter and its event onDidChangeEmitter = new vscode.EventEmitter(); onDidChange = this.onDidChangeEmitter.event; diff --git a/extensions/vscode/src/test/test-suites/ideUtils.test.ts b/extensions/vscode/src/test/test-suites/ideUtils.test.ts index adae3fab4..f994b3810 100644 --- a/extensions/vscode/src/test/test-suites/ideUtils.test.ts +++ b/extensions/vscode/src/test/test-suites/ideUtils.test.ts @@ -59,13 +59,6 @@ describe("IDE Utils", () => { assert(regex.test(uniqueId)); }); - test("readFile", async () => { - const testPyContents = await utils.readFile(testPyPath); - assert(testPyContents === "print('Hello World!')"); - const testJsContents = await utils.readFile(testJsPath); - assert(testJsContents === "console.log('Hello World!')"); - }); - test.skip("getTerminalContents", async () => { await new Promise((resolve) => setTimeout(resolve, 1000)); const terminal = vscode.window.createTerminal(); diff --git a/extensions/vscode/src/util/ideUtils.ts b/extensions/vscode/src/util/ideUtils.ts index 6ebb9c1a1..2dd9cd330 100644 --- a/extensions/vscode/src/util/ideUtils.ts +++ b/extensions/vscode/src/util/ideUtils.ts @@ -177,8 +177,7 @@ export class VsCodeIdeUtils { vscode.workspace .openTextDocument( vscode.Uri.parse( - `${ - VsCodeExtension.continueVirtualDocumentScheme + `${VsCodeExtension.continueVirtualDocumentScheme }:${encodeURIComponent(name)}?${encodeURIComponent(contents)}`, ), ) @@ -291,56 +290,6 @@ export class VsCodeIdeUtils { } } - private static MAX_BYTES = 100000; - - async readFile(filepath: string): Promise { - try { - filepath = this.getAbsolutePath(filepath); - const uri = uriFromFilePath(filepath); - - // First, check whether it's a notebook document - // Need to iterate over the cells to get full contents - const notebook = - vscode.workspace.notebookDocuments.find( - (doc) => doc.uri.toString() === uri.toString(), - ) ?? - (uri.fsPath.endsWith("ipynb") - ? await vscode.workspace.openNotebookDocument(uri) - : undefined); - if (notebook) { - return notebook - .getCells() - .map((cell) => cell.document.getText()) - .join("\n\n"); - } - - // Check whether it's an open document - const openTextDocument = vscode.workspace.textDocuments.find( - (doc) => doc.uri.fsPath === uri.fsPath, - ); - if (openTextDocument !== undefined) { - return openTextDocument.getText(); - } - - const fileStats = await vscode.workspace.fs.stat( - uriFromFilePath(filepath), - ); - if (fileStats.size > 10 * VsCodeIdeUtils.MAX_BYTES) { - return ""; - } - - const bytes = await vscode.workspace.fs.readFile(uri); - - // Truncate the buffer to the first MAX_BYTES - const truncatedBytes = bytes.slice(0, VsCodeIdeUtils.MAX_BYTES); - const contents = new TextDecoder().decode(truncatedBytes); - return contents; - } catch (e) { - console.warn("Error reading file", e); - return ""; - } - } - async readRangeInFile( filepath: string, range: vscode.Range, @@ -352,8 +301,8 @@ export class VsCodeIdeUtils { return `${lines .slice(range.start.line, range.end.line) .join("\n")}\n${lines[ - range.end.line < lines.length - 1 ? range.end.line : lines.length - 1 - ].slice(0, range.end.character)}`; + range.end.line < lines.length - 1 ? range.end.line : lines.length - 1 + ].slice(0, range.end.character)}`; } async getTerminalContents(commands = -1): Promise { diff --git a/gui/src/hooks/useChatHandler.ts b/gui/src/hooks/useChatHandler.ts index c90c044dc..f961e62c1 100644 --- a/gui/src/hooks/useChatHandler.ts +++ b/gui/src/hooks/useChatHandler.ts @@ -57,13 +57,13 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { const active = useSelector((store: RootState) => store.state.active); const activeRef = useRef(active); - const {saveSession} = useHistory(dispatch); + const { saveSession } = useHistory(dispatch); const [save, triggerSave] = useState(false); useEffect(() => { saveSession(false); }, [save]); - + useEffect(() => { activeRef.current = active; @@ -217,31 +217,29 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { if (!modifiers.noContext) { const usingFreeTrial = defaultModel?.provider === "free-trial"; - const currentFilePath = await ideMessenger.ide.getCurrentFile(); - if (typeof currentFilePath === "string") { - let currentFileContents = await ideMessenger.ide.readFile( - currentFilePath, - ); + const currentFile = await ideMessenger.ide.getCurrentFile(); + if (currentFile) { + let currentFileContents = currentFile.contents if (usingFreeTrial) { - currentFileContents = currentFileContents + currentFileContents = currentFile.contents .split("\n") .slice(0, 1000) .join("\n"); } selectedContextItems.unshift({ content: `The following file is currently open. Don't reference it if it's not relevant to the user's message.\n\n\`\`\`${getRelativePath( - currentFilePath, + currentFile.path, await ideMessenger.ide.getWorkspaceDirs(), )}\n${currentFileContents}\n\`\`\``, - name: `Active file: ${getBasename(currentFilePath)}`, - description: currentFilePath, + name: `Active file: ${getBasename(currentFile.path)}`, + description: currentFile.path, id: { - itemId: currentFilePath, + itemId: currentFile.path, providerTitle: "file", }, uri: { type: "file", - value: currentFilePath, + value: currentFile.path, }, }); } From 8ffa1f0f757794ac920a6a6a594f604a6ebbeeb0 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 7 Nov 2024 15:27:52 -0800 Subject: [PATCH 77/96] untitled active file working --- extensions/vscode/src/VsCodeIde.ts | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/extensions/vscode/src/VsCodeIde.ts b/extensions/vscode/src/VsCodeIde.ts index 5c5e617f4..caf365805 100644 --- a/extensions/vscode/src/VsCodeIde.ts +++ b/extensions/vscode/src/VsCodeIde.ts @@ -447,17 +447,6 @@ class VsCodeIde implements IDE { .join("\n\n"); } - // Check if the document is an untitled (new and unsaved) document - const untitledDocs = vscode.workspace.textDocuments.filter( - (doc) => doc.isUntitled && doc, - ); - const untitledDoc = vscode.workspace.textDocuments.find( - (doc) => doc.isUntitled && doc.uri.fsPath === uri.fsPath - ); - if (untitledDoc) { - return untitledDoc.getText(); - } - // Check whether it's an open document const openTextDocument = vscode.workspace.textDocuments.find( (doc) => doc.uri.fsPath === uri.fsPath, From 779bc84938497facb22eeef320dab012b8ebf0cb Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 7 Nov 2024 15:58:05 -0800 Subject: [PATCH 78/96] broken on jetbrains --- core/config/promptFile.ts | 26 ++++++++++++------- core/config/types.ts | 2 +- core/promptFiles/handlebarUtils.ts | 4 +-- core/promptFiles/renderTemplatedString.ts | 2 +- .../promptFiles/slashCommandFromPromptFile.ts | 12 ++++++--- 5 files changed, 29 insertions(+), 17 deletions(-) diff --git a/core/config/promptFile.ts b/core/config/promptFile.ts index a22dfadde..728090fcc 100644 --- a/core/config/promptFile.ts +++ b/core/config/promptFile.ts @@ -1,11 +1,12 @@ import Handlebars from "handlebars"; import path from "path"; import * as YAML from "yaml"; -import type { IDE, SlashCommand } from ".."; +import type { ChatHistory, ChatHistoryItem, ChatMessage, ContextItem, ContinueSDK, IContextProvider, IDE, SlashCommand } from ".."; import { walkDir } from "../indexing/walkDir"; import { stripImages } from "../llm/images"; import { renderTemplatedString } from "../promptFiles/renderTemplatedString"; import { getBasename } from "../util/index"; +import { BaseContextProvider } from "../context"; export const DEFAULT_PROMPTS_FOLDER = ".prompts"; @@ -147,25 +148,32 @@ function extractUserInput(input: string, commandName: string): string { return input; } -async function renderPrompt(prompt: string, context: any, userInput: string) { +async function renderPrompt(prompt: string, context: ContinueSDK, userInput: string) { const helpers = getContextProviderHelpers(context); // A few context providers that don't need to be in config.json to work in .prompt files const diff = await context.ide.getDiff(false); const currentFile = await context.ide.getCurrentFile(); + const inputData: Record = { + diff, + input: userInput, + }; + if (currentFile) { + inputData.currentFile = currentFile.path; + } return renderTemplatedString( prompt, context.ide.readFile.bind(context.ide), - { diff, currentFile: currentFile?.contents, input: userInput }, + inputData, helpers, ); } function getContextProviderHelpers( - context: any, + context: ContinueSDK, ): Array<[string, Handlebars.HelperDelegate]> | undefined { - return context.config.contextProviders?.map((provider: any) => [ + return context.config.contextProviders?.map((provider: IContextProvider) => [ provider.description.title, async (helperContext: any) => { const items = await provider.getContextItems(helperContext, { @@ -179,16 +187,16 @@ function getContextProviderHelpers( selectedCode: context.selectedCode, }); - items.forEach((item: any) => + items.forEach((item) => context.addContextItem(createContextItem(item, provider)), ); - return items.map((item: any) => item.content).join("\n\n"); + return items.map((item) => item.content).join("\n\n"); }, ]); } -function createContextItem(item: any, provider: any) { +function createContextItem(item: ContextItem, provider: IContextProvider) { return { ...item, id: { @@ -199,7 +207,7 @@ function createContextItem(item: any, provider: any) { } function updateChatHistory( - history: any[], + history: ChatMessage[], commandName: string, renderedPrompt: string, systemMessage?: string, diff --git a/core/config/types.ts b/core/config/types.ts index b886ea021..f457812d1 100644 --- a/core/config/types.ts +++ b/core/config/types.ts @@ -463,7 +463,7 @@ declare global { stepIndex: number, ): Promise; getOpenFiles(): Promise; - getCurrentFile(): Promise Promise, - inputData: any, + inputData: Record, ctxProviderNames: string[], ): Promise<[string, any]> { const [newTemplate, vars] = replaceFilepaths(template, ctxProviderNames); @@ -95,7 +95,7 @@ export async function prepareTemplateAndData( return [newTemplate, data]; } -export function compileAndRenderTemplate(template: string, data: any): string { +export function compileAndRenderTemplate(template: string, data: Record): string { const templateFn = Handlebars.compile(template); return templateFn(data); } diff --git a/core/promptFiles/renderTemplatedString.ts b/core/promptFiles/renderTemplatedString.ts index d31cce0b9..bcc645ace 100644 --- a/core/promptFiles/renderTemplatedString.ts +++ b/core/promptFiles/renderTemplatedString.ts @@ -8,7 +8,7 @@ import { export async function renderTemplatedString( template: string, readFile: (filepath: string) => Promise, - inputData: any, + inputData: Record, availableHelpers?: Array<[string, Handlebars.HelperDelegate]>, ): Promise { const helperPromises = availableHelpers diff --git a/core/promptFiles/slashCommandFromPromptFile.ts b/core/promptFiles/slashCommandFromPromptFile.ts index 3df3cb8fe..af865078e 100644 --- a/core/promptFiles/slashCommandFromPromptFile.ts +++ b/core/promptFiles/slashCommandFromPromptFile.ts @@ -1,4 +1,4 @@ -import { SlashCommand } from ".."; +import { ContinueSDK, SlashCommand } from ".."; import { stripImages } from "../llm/images"; import { getContextProviderHelpers } from "./getContextProviderHelpers"; import { renderTemplatedString } from "./renderTemplatedString"; @@ -37,14 +37,18 @@ export function extractUserInput(input: string, commandName: string): string { return input; } -export async function getDefaultVariables(context: any, userInput: string) { +export async function getDefaultVariables(context: ContinueSDK, userInput: string): Promise> { const currentFile = await context.ide.getCurrentFile(); - return { currentFile: currentFile?.contents, input: userInput }; + const vars: Record = { input: userInput }; + if (currentFile) { + vars.currentFile = currentFile.path; + } + return vars; } export async function renderPrompt( prompt: string, - context: any, + context: ContinueSDK, userInput: string, ) { const helpers = getContextProviderHelpers(context); From 35abf4be940e31371d323497115b0be591467f96 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 7 Nov 2024 16:20:12 -0800 Subject: [PATCH 79/96] fix jetbrains bug --- .../continueintellijextension/continue/IdeProtocolClient.kt | 4 ++-- gui/src/hooks/useChatHandler.ts | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt index 17a8da024..b773026bd 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt @@ -1012,8 +1012,8 @@ class IdeProtocolClient( val virtualFile = editor?.document?.let { FileDocumentManager.getInstance().getFile(it) } return virtualFile?.let { mapOf( - "filePath" to it.path, - "fileContents" to editor.document.text, + "path" to it.path, + "contents" to editor.document.text, "isUntitled" to false ) } diff --git a/gui/src/hooks/useChatHandler.ts b/gui/src/hooks/useChatHandler.ts index f961e62c1..cafd4ce4c 100644 --- a/gui/src/hooks/useChatHandler.ts +++ b/gui/src/hooks/useChatHandler.ts @@ -153,7 +153,7 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { clearInterval(checkActiveInterval); } }, 100); - + debugger for await (const update of ideMessenger.streamRequest( "command/run", { From 1740992a9b63876c9fcb9ee983d007094692b026 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Thu, 7 Nov 2024 16:20:44 -0800 Subject: [PATCH 80/96] Delete extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/a test --- .../continuedev/continueintellijextension/continue/a test | 2 -- 1 file changed, 2 deletions(-) delete mode 100644 extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/a test diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/a test b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/a test deleted file mode 100644 index 246284309..000000000 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/a test +++ /dev/null @@ -1,2 +0,0 @@ -asdfasdfasdfasd -her's new co \ No newline at end of file From 25f05d95da651a1cbd84375265dfb72cb4f9ced6 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 7 Nov 2024 16:34:43 -0800 Subject: [PATCH 81/96] clean up get current file --- extensions/vscode/src/extension/VsCodeExtension.ts | 2 +- gui/src/hooks/useChatHandler.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index e9f9cbad7..54b2cc67e 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -278,7 +278,7 @@ export class VsCodeExtension { // Reindex the workspaces this.core.invoke("index/forceReIndex", undefined); } else { - // Reindex the filex + // Reindex the file const indexer = await this.core.codebaseIndexerPromise; indexer.refreshFile(filepath); } diff --git a/gui/src/hooks/useChatHandler.ts b/gui/src/hooks/useChatHandler.ts index cafd4ce4c..f961e62c1 100644 --- a/gui/src/hooks/useChatHandler.ts +++ b/gui/src/hooks/useChatHandler.ts @@ -153,7 +153,7 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { clearInterval(checkActiveInterval); } }, 100); - debugger + for await (const update of ideMessenger.streamRequest( "command/run", { From f4e5b103f782be211f6c7a57c97d965c8a0d8beb Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 7 Nov 2024 17:05:56 -0800 Subject: [PATCH 82/96] prevent duplicate code blocks --- gui/src/components/mainInput/TipTapEditor.tsx | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/gui/src/components/mainInput/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor.tsx index 01ee8dea6..49fe9d547 100644 --- a/gui/src/components/mainInput/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor.tsx @@ -700,9 +700,11 @@ function TipTapEditor(props: TipTapEditorProps) { ); const rangeStr = `(${rif.range.start.line + 1}-${rif.range.end.line + 1 })`; + + const itemName = `${basename} ${rangeStr}`; const item: ContextItemWithId = { content: rif.contents, - name: `${basename} ${rangeStr}`, + name: itemName, // Description is passed on to the LLM to give more context on file path description: `${relativePath} ${rangeStr}`, id: { @@ -717,6 +719,9 @@ function TipTapEditor(props: TipTapEditorProps) { let index = 0; for (const el of editor.getJSON().content) { + if (el.attrs?.item?.name === itemName) { + return; // Prevent duplicate code blocks + } if (el.type === "codeBlock") { index += 2; } else { From 648d4bfa4b29491f52cf8026f6a77d51d3888b86 Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 7 Nov 2024 20:59:17 -0800 Subject: [PATCH 83/96] address edit feedback --- extensions/vscode/src/commands.ts | 1077 +++++++++++++++-------------- gui/src/components/index.ts | 21 +- gui/src/pages/edit.tsx | 21 +- 3 files changed, 581 insertions(+), 538 deletions(-) diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index 11c280678..c33d71aea 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -1,5 +1,5 @@ /* eslint-disable @typescript-eslint/naming-convention */ -import { ContextMenuConfig, IDE } from "core"; +import { ContextMenuConfig } from "core"; import { CompletionProvider } from "core/autocomplete/completionProvider"; import { RangeInFileWithContents } from "core/commands/util"; import { ConfigHandler } from "core/config/ConfigHandler"; @@ -33,8 +33,8 @@ import { QuickEdit, QuickEditShowParams } from "./quickEdit/QuickEditQuickPick"; import { Battery } from "./util/battery"; import { getFullyQualifiedPath } from "./util/util"; import { uriFromFilePath } from "./util/vscode"; -import type { VsCodeWebviewProtocol } from "./webviewProtocol"; import { VsCodeIde } from "./VsCodeIde"; +import type { VsCodeWebviewProtocol } from "./webviewProtocol"; let fullScreenPanel: vscode.WebviewPanel | undefined; @@ -226,180 +226,196 @@ const commandsMap: ( core, editDecorationManager, ) => { - /** - * Streams an inline edit to the vertical diff manager. - * - * This function retrieves the configuration, determines the appropriate model title, - * increments the FTC count, and then streams an edit to the - * vertical diff manager. - * - * @param promptName - The key for the prompt in the context menu configuration. - * @param fallbackPrompt - The prompt to use if the configured prompt is not available. - * @param [onlyOneInsertion] - Optional. If true, only one insertion will be made. - * @param [range] - Optional. The range to edit if provided. - * @returns - */ - async function streamInlineEdit( - promptName: keyof ContextMenuConfig, - fallbackPrompt: string, - onlyOneInsertion?: boolean, - range?: vscode.Range, - ) { - const config = await configHandler.loadConfig(); + /** + * Streams an inline edit to the vertical diff manager. + * + * This function retrieves the configuration, determines the appropriate model title, + * increments the FTC count, and then streams an edit to the + * vertical diff manager. + * + * @param promptName - The key for the prompt in the context menu configuration. + * @param fallbackPrompt - The prompt to use if the configured prompt is not available. + * @param [onlyOneInsertion] - Optional. If true, only one insertion will be made. + * @param [range] - Optional. The range to edit if provided. + * @returns + */ + async function streamInlineEdit( + promptName: keyof ContextMenuConfig, + fallbackPrompt: string, + onlyOneInsertion?: boolean, + range?: vscode.Range, + ) { + const config = await configHandler.loadConfig(); - const defaultModelTitle = await sidebar.webviewProtocol.request( - "getDefaultModelTitle", + const defaultModelTitle = await sidebar.webviewProtocol.request( + "getDefaultModelTitle", + undefined, + ); + + const modelTitle = + getModelByRole(config, "inlineEdit")?.title ?? defaultModelTitle; + + sidebar.webviewProtocol.request("incrementFtc", undefined); + + await verticalDiffManager.streamEdit( + config.experimental?.contextMenuPrompts?.[promptName] ?? fallbackPrompt, + modelTitle, + undefined, + onlyOneInsertion, + undefined, + range, + ); + } + + return { + "continue.acceptDiff": async (newFilepath?: string | vscode.Uri) => { + captureCommandTelemetry("acceptDiff"); + + let fullPath = newFilepath; + + if (fullPath instanceof vscode.Uri) { + fullPath = fullPath.fsPath; + } else if (fullPath) { + fullPath = getFullyQualifiedPath(ide, fullPath); + } else { + console.warn(`Unable to resolve filepath: ${newFilepath}`); + } + + verticalDiffManager.clearForFilepath(fullPath, true); + await diffManager.acceptDiff(fullPath); + await sidebar.webviewProtocol.request("setEditStatus", { + status: "done", + }); + }, + "continue.rejectDiff": async (newFilepath?: string | vscode.Uri) => { + captureCommandTelemetry("rejectDiff"); + + let fullPath = newFilepath; + + if (fullPath instanceof vscode.Uri) { + fullPath = fullPath.fsPath; + } else if (fullPath) { + fullPath = getFullyQualifiedPath(ide, fullPath); + } else { + console.warn(`Unable to resolve filepath: ${newFilepath}`); + } + + verticalDiffManager.clearForFilepath(fullPath, false); + await diffManager.rejectDiff(fullPath); + await sidebar.webviewProtocol.request("setEditStatus", { + status: "done", + }); + }, + "continue.acceptVerticalDiffBlock": (filepath?: string, index?: number) => { + captureCommandTelemetry("acceptVerticalDiffBlock"); + verticalDiffManager.acceptRejectVerticalDiffBlock(true, filepath, index); + }, + "continue.rejectVerticalDiffBlock": (filepath?: string, index?: number) => { + captureCommandTelemetry("rejectVerticalDiffBlock"); + verticalDiffManager.acceptRejectVerticalDiffBlock(false, filepath, index); + }, + "continue.quickFix": async ( + range: vscode.Range, + diagnosticMessage: string, + ) => { + captureCommandTelemetry("quickFix"); + + const prompt = `Please explain the cause of this error and how to solve it: ${diagnosticMessage}`; + + addCodeToContextFromRange(range, sidebar.webviewProtocol, prompt); + + vscode.commands.executeCommand("continue.continueGUIView.focus"); + }, + // Passthrough for telemetry purposes + "continue.defaultQuickAction": async (args: QuickEditShowParams) => { + captureCommandTelemetry("defaultQuickAction"); + vscode.commands.executeCommand("continue.quickEdit", args); + }, + "continue.customQuickActionSendToChat": async ( + prompt: string, + range: vscode.Range, + ) => { + captureCommandTelemetry("customQuickActionSendToChat"); + + addCodeToContextFromRange(range, sidebar.webviewProtocol, prompt); + + vscode.commands.executeCommand("continue.continueGUIView.focus"); + }, + "continue.customQuickActionStreamInlineEdit": async ( + prompt: string, + range: vscode.Range, + ) => { + captureCommandTelemetry("customQuickActionStreamInlineEdit"); + + streamInlineEdit("docstring", prompt, false, range); + }, + "continue.codebaseForceReIndex": async () => { + core.invoke("index/forceReIndex", undefined); + }, + "continue.rebuildCodebaseIndex": async () => { + core.invoke("index/forceReIndex", { shouldClearIndexes: true }); + }, + "continue.docsIndex": async () => { + core.invoke("context/indexDocs", { reIndex: false }); + }, + "continue.docsReIndex": async () => { + core.invoke("context/indexDocs", { reIndex: true }); + }, + "continue.focusContinueInput": async () => { + const historyLength = await sidebar.webviewProtocol.request( + "getWebviewHistoryLength", + undefined, + ); + const isContinueInputFocused = await sidebar.webviewProtocol.request( + "isContinueInputFocused", undefined, ); - const modelTitle = - getModelByRole(config, "inlineEdit")?.title ?? defaultModelTitle; - - sidebar.webviewProtocol.request("incrementFtc", undefined); - - await verticalDiffManager.streamEdit( - config.experimental?.contextMenuPrompts?.[promptName] ?? fallbackPrompt, - modelTitle, - undefined, - onlyOneInsertion, - undefined, - range, - ); - } - - return { - "continue.acceptDiff": async (newFilepath?: string | vscode.Uri) => { - captureCommandTelemetry("acceptDiff"); - - let fullPath = newFilepath; - - if (fullPath instanceof vscode.Uri) { - fullPath = fullPath.fsPath; - } else if (fullPath) { - fullPath = getFullyQualifiedPath(ide, fullPath); - } else { - console.warn(`Unable to resolve filepath: ${newFilepath}`); - } - - verticalDiffManager.clearForFilepath(fullPath, true); - await diffManager.acceptDiff(fullPath); - await sidebar.webviewProtocol.request("setEditStatus", { - status: "done", - }); - }, - "continue.rejectDiff": async (newFilepath?: string | vscode.Uri) => { - captureCommandTelemetry("rejectDiff"); - - let fullPath = newFilepath; - - if (fullPath instanceof vscode.Uri) { - fullPath = fullPath.fsPath; - } else if (fullPath) { - fullPath = getFullyQualifiedPath(ide, fullPath); - } else { - console.warn(`Unable to resolve filepath: ${newFilepath}`); - return; - } - - verticalDiffManager.clearForFilepath(fullPath, false); - await diffManager.rejectDiff(fullPath); - await sidebar.webviewProtocol.request("setEditStatus", { - status: "done", - }); - }, - "continue.acceptVerticalDiffBlock": (filepath?: string, index?: number) => { - captureCommandTelemetry("acceptVerticalDiffBlock"); - verticalDiffManager.acceptRejectVerticalDiffBlock(true, filepath, index); - }, - "continue.rejectVerticalDiffBlock": (filepath?: string, index?: number) => { - captureCommandTelemetry("rejectVerticalDiffBlock"); - verticalDiffManager.acceptRejectVerticalDiffBlock(false, filepath, index); - }, - "continue.quickFix": async ( - range: vscode.Range, - diagnosticMessage: string, - ) => { - captureCommandTelemetry("quickFix"); - - const prompt = `Please explain the cause of this error and how to solve it: ${diagnosticMessage}`; - - addCodeToContextFromRange(range, sidebar.webviewProtocol, prompt); - - vscode.commands.executeCommand("continue.continueGUIView.focus"); - }, - // Passthrough for telemetry purposes - "continue.defaultQuickAction": async (args: QuickEditShowParams) => { - captureCommandTelemetry("defaultQuickAction"); - vscode.commands.executeCommand("continue.quickEdit", args); - }, - "continue.customQuickActionSendToChat": async ( - prompt: string, - range: vscode.Range, - ) => { - captureCommandTelemetry("customQuickActionSendToChat"); - - addCodeToContextFromRange(range, sidebar.webviewProtocol, prompt); - - vscode.commands.executeCommand("continue.continueGUIView.focus"); - }, - "continue.customQuickActionStreamInlineEdit": async ( - prompt: string, - range: vscode.Range, - ) => { - captureCommandTelemetry("customQuickActionStreamInlineEdit"); - - streamInlineEdit("docstring", prompt, false, range); - }, - "continue.codebaseForceReIndex": async () => { - core.invoke("index/forceReIndex", undefined); - }, - "continue.rebuildCodebaseIndex": async () => { - core.invoke("index/forceReIndex", { shouldClearIndexes: true }); - }, - "continue.docsIndex": async () => { - core.invoke("context/indexDocs", { reIndex: false }); - }, - "continue.docsReIndex": async () => { - core.invoke("context/indexDocs", { reIndex: true }); - }, - "continue.focusContinueInput": async () => { - const historyLength = await sidebar.webviewProtocol.request("getWebviewHistoryLength", undefined); - const isContinueInputFocused = await sidebar.webviewProtocol.request("isContinueInputFocused", undefined); - - if (isContinueInputFocused) { - if (historyLength === 0) { - hideGUI(); - } else { - sidebar.webviewProtocol?.request("focusContinueInput", undefined); - } - } else { - focusGUI(); - sidebar.webviewProtocol?.request("focusContinueInput", undefined); - await addHighlightedCodeToContext(sidebar.webviewProtocol); - } - }, - "continue.focusContinueInputWithoutClear": async () => { - const isContinueInputFocused = await sidebar.webviewProtocol.request("isContinueInputFocused", undefined); - - if (isContinueInputFocused) { + if (isContinueInputFocused) { + if (historyLength === 0) { hideGUI(); } else { - focusGUI(); - - sidebar.webviewProtocol?.request("focusContinueInputWithoutClear", undefined); - - await addHighlightedCodeToContext(sidebar.webviewProtocol); + sidebar.webviewProtocol?.request("focusContinueInput", undefined); } - }, - "continue.edit": async () => { - captureCommandTelemetry("edit"); + } else { + focusGUI(); + sidebar.webviewProtocol?.request("focusContinueInput", undefined); + await addHighlightedCodeToContext(sidebar.webviewProtocol); + } + }, + "continue.focusContinueInputWithoutClear": async () => { + const isContinueInputFocused = await sidebar.webviewProtocol.request( + "isContinueInputFocused", + undefined, + ); + + if (isContinueInputFocused) { + hideGUI(); + } else { focusGUI(); - const editor = vscode.window.activeTextEditor; - if (!editor) { - return; - } + sidebar.webviewProtocol?.request( + "focusContinueInputWithoutClear", + undefined, + ); + await addHighlightedCodeToContext(sidebar.webviewProtocol); + } + }, + "continue.edit": async () => { + captureCommandTelemetry("edit"); + focusGUI(); + + const editor = vscode.window.activeTextEditor; + if (!editor) { + return; + } + + const existingDiff = await verticalDiffManager.getHandlerForFile( + editor.document.fileName, + ); + if (!existingDiff) { + // If there's a diff currently being applied, then we just toggle focus back to the input editDecorationManager.setDecoration( editor, new vscode.Range(editor.selection.start, editor.selection.end), @@ -419,396 +435,399 @@ const commandsMap: ( setTimeout(() => { sidebar.webviewProtocol?.request("focusContinueInput", undefined); }, 30); - }, - "continue.exitEditMode": async () => { - captureCommandTelemetry("exitEditMode"); - await sidebar.webviewProtocol?.request("exitEditMode", undefined); - }, - "continue.quickEdit": async (args: QuickEditShowParams) => { - let linesOfCode = undefined; - if (args.range) { - linesOfCode = args.range.end.line - args.range.start.line; - } - captureCommandTelemetry("quickEdit", { - linesOfCode, + } else { + sidebar.webviewProtocol?.request("focusContinueInput", undefined); + } + }, + "continue.exitEditMode": async () => { + captureCommandTelemetry("exitEditMode"); + await sidebar.webviewProtocol?.request("exitEditMode", undefined); + }, + "continue.quickEdit": async (args: QuickEditShowParams) => { + let linesOfCode = undefined; + if (args.range) { + linesOfCode = args.range.end.line - args.range.start.line; + } + captureCommandTelemetry("quickEdit", { + linesOfCode, + }); + quickEdit.show(args); + }, + "continue.writeCommentsForCode": async () => { + captureCommandTelemetry("writeCommentsForCode"); + + streamInlineEdit( + "comment", + "Write comments for this code. Do not change anything about the code itself.", + ); + }, + "continue.writeDocstringForCode": async () => { + captureCommandTelemetry("writeDocstringForCode"); + + streamInlineEdit( + "docstring", + "Write a docstring for this code. Do not change anything about the code itself.", + true, + ); + }, + "continue.fixCode": async () => { + captureCommandTelemetry("fixCode"); + + streamInlineEdit( + "fix", + "Fix this code. If it is already 100% correct, simply rewrite the code.", + ); + }, + "continue.optimizeCode": async () => { + captureCommandTelemetry("optimizeCode"); + streamInlineEdit("optimize", "Optimize this code"); + }, + "continue.fixGrammar": async () => { + captureCommandTelemetry("fixGrammar"); + streamInlineEdit( + "fixGrammar", + "If there are any grammar or spelling mistakes in this writing, fix them. Do not make other large changes to the writing.", + ); + }, + "continue.viewLogs": async () => { + captureCommandTelemetry("viewLogs"); + + // Open ~/.continue/continue.log + const logFile = path.join(os.homedir(), ".continue", "continue.log"); + // Make sure the file/directory exist + if (!fs.existsSync(logFile)) { + fs.mkdirSync(path.dirname(logFile), { recursive: true }); + fs.writeFileSync(logFile, ""); + } + + const uri = vscode.Uri.file(logFile); + await vscode.window.showTextDocument(uri); + }, + "continue.debugTerminal": async () => { + captureCommandTelemetry("debugTerminal"); + + const terminalContents = await ide.getTerminalContents(); + + vscode.commands.executeCommand("continue.continueGUIView.focus"); + + sidebar.webviewProtocol?.request("userInput", { + input: `I got the following error, can you please help explain how to fix it?\n\n${terminalContents.trim()}`, + }); + }, + "continue.hideInlineTip": () => { + vscode.workspace + .getConfiguration(EXTENSION_NAME) + .update("showInlineTip", false, vscode.ConfigurationTarget.Global); + }, + + // Commands without keyboard shortcuts + "continue.addModel": () => { + captureCommandTelemetry("addModel"); + + vscode.commands.executeCommand("continue.continueGUIView.focus"); + sidebar.webviewProtocol?.request("addModel", undefined); + }, + "continue.openSettingsUI": () => { + vscode.commands.executeCommand("continue.continueGUIView.focus"); + sidebar.webviewProtocol?.request("openSettings", undefined); + }, + "continue.sendMainUserInput": (text: string) => { + sidebar.webviewProtocol?.request("userInput", { + input: text, + }); + }, + "continue.selectRange": (startLine: number, endLine: number) => { + if (!vscode.window.activeTextEditor) { + return; + } + vscode.window.activeTextEditor.selection = new vscode.Selection( + startLine, + 0, + endLine, + 0, + ); + }, + "continue.foldAndUnfold": ( + foldSelectionLines: number[], + unfoldSelectionLines: number[], + ) => { + vscode.commands.executeCommand("editor.unfold", { + selectionLines: unfoldSelectionLines, + }); + vscode.commands.executeCommand("editor.fold", { + selectionLines: foldSelectionLines, + }); + }, + "continue.sendToTerminal": (text: string) => { + captureCommandTelemetry("sendToTerminal"); + ide.runCommand(text); + }, + "continue.newSession": () => { + sidebar.webviewProtocol?.request("newSession", undefined); + }, + "continue.viewHistory": () => { + sidebar.webviewProtocol?.request("viewHistory", undefined); + }, + "continue.focusContinueSessionId": async ( + sessionId: string | undefined, + ) => { + if (!sessionId) { + sessionId = await vscode.window.showInputBox({ + prompt: "Enter the Session ID", }); - quickEdit.show(args); - }, - "continue.writeCommentsForCode": async () => { - captureCommandTelemetry("writeCommentsForCode"); + } + sidebar.webviewProtocol?.request("focusContinueSessionId", { sessionId }); + }, + "continue.applyCodeFromChat": () => { + sidebar.webviewProtocol.request("applyCodeFromChat", undefined); + }, + "continue.toggleFullScreen": () => { + focusGUI(); - streamInlineEdit( - "comment", - "Write comments for this code. Do not change anything about the code itself.", - ); - }, - "continue.writeDocstringForCode": async () => { - captureCommandTelemetry("writeDocstringForCode"); + // Check if full screen is already open by checking open tabs + const fullScreenTab = getFullScreenTab(); - streamInlineEdit( - "docstring", - "Write a docstring for this code. Do not change anything about the code itself.", - true, - ); - }, - "continue.fixCode": async () => { - captureCommandTelemetry("fixCode"); + if (fullScreenTab && fullScreenPanel) { + // Full screen open, but not focused - focus it + fullScreenPanel.reveal(); + return; + } - streamInlineEdit( - "fix", - "Fix this code. If it is already 100% correct, simply rewrite the code.", - ); - }, - "continue.optimizeCode": async () => { - captureCommandTelemetry("optimizeCode"); - streamInlineEdit("optimize", "Optimize this code"); - }, - "continue.fixGrammar": async () => { - captureCommandTelemetry("fixGrammar"); - streamInlineEdit( - "fixGrammar", - "If there are any grammar or spelling mistakes in this writing, fix them. Do not make other large changes to the writing.", - ); - }, - "continue.viewLogs": async () => { - captureCommandTelemetry("viewLogs"); + // Full screen not open - open it + captureCommandTelemetry("openFullScreen"); - // Open ~/.continue/continue.log - const logFile = path.join(os.homedir(), ".continue", "continue.log"); - // Make sure the file/directory exist - if (!fs.existsSync(logFile)) { - fs.mkdirSync(path.dirname(logFile), { recursive: true }); - fs.writeFileSync(logFile, ""); - } + // Create the full screen panel + let panel = vscode.window.createWebviewPanel( + "continue.continueGUIView", + "Continue", + vscode.ViewColumn.One, + { + retainContextWhenHidden: true, + }, + ); + fullScreenPanel = panel; - const uri = vscode.Uri.file(logFile); - await vscode.window.showTextDocument(uri); - }, - "continue.debugTerminal": async () => { - captureCommandTelemetry("debugTerminal"); + // Add content to the panel + panel.webview.html = sidebar.getSidebarContent( + extensionContext, + panel, + undefined, + undefined, + true, + ); - const terminalContents = await ide.getTerminalContents(); + // When panel closes, reset the webview and focus + panel.onDidDispose( + () => { + sidebar.resetWebviewProtocolWebview(); + vscode.commands.executeCommand("continue.focusContinueInput"); + }, + null, + extensionContext.subscriptions, + ); - vscode.commands.executeCommand("continue.continueGUIView.focus"); + vscode.commands.executeCommand("workbench.action.copyEditorToNewWindow"); + }, + "continue.openConfigJson": () => { + ide.openFile(getConfigJsonPath()); + }, + "continue.selectFilesAsContext": async ( + firstUri: vscode.Uri, + uris: vscode.Uri[], + ) => { + if (uris === undefined) { + throw new Error("No files were selected"); + } - sidebar.webviewProtocol?.request("userInput", { - input: `I got the following error, can you please help explain how to fix it?\n\n${terminalContents.trim()}`, - }); - }, - "continue.hideInlineTip": () => { - vscode.workspace - .getConfiguration(EXTENSION_NAME) - .update("showInlineTip", false, vscode.ConfigurationTarget.Global); - }, + vscode.commands.executeCommand("continue.continueGUIView.focus"); - // Commands without keyboard shortcuts - "continue.addModel": () => { - captureCommandTelemetry("addModel"); - - vscode.commands.executeCommand("continue.continueGUIView.focus"); - sidebar.webviewProtocol?.request("addModel", undefined); - }, - "continue.openSettingsUI": () => { - vscode.commands.executeCommand("continue.continueGUIView.focus"); - sidebar.webviewProtocol?.request("openSettings", undefined); - }, - "continue.sendMainUserInput": (text: string) => { - sidebar.webviewProtocol?.request("userInput", { - input: text, - }); - }, - "continue.selectRange": (startLine: number, endLine: number) => { - if (!vscode.window.activeTextEditor) { - return; - } - vscode.window.activeTextEditor.selection = new vscode.Selection( - startLine, - 0, - endLine, - 0, - ); - }, - "continue.foldAndUnfold": ( - foldSelectionLines: number[], - unfoldSelectionLines: number[], - ) => { - vscode.commands.executeCommand("editor.unfold", { - selectionLines: unfoldSelectionLines, - }); - vscode.commands.executeCommand("editor.fold", { - selectionLines: foldSelectionLines, - }); - }, - "continue.sendToTerminal": (text: string) => { - captureCommandTelemetry("sendToTerminal"); - ide.runCommand(text); - }, - "continue.newSession": () => { - sidebar.webviewProtocol?.request("newSession", undefined); - }, - "continue.viewHistory": () => { - sidebar.webviewProtocol?.request("viewHistory", undefined); - }, - "continue.focusContinueSessionId": async ( - sessionId: string | undefined, - ) => { - if (!sessionId) { - sessionId = await vscode.window.showInputBox({ - prompt: "Enter the Session ID", - }); - } - sidebar.webviewProtocol?.request("focusContinueSessionId", { sessionId }); - }, - "continue.applyCodeFromChat": () => { - sidebar.webviewProtocol.request("applyCodeFromChat", undefined); - }, - "continue.toggleFullScreen": () => { - focusGUI(); - - // Check if full screen is already open by checking open tabs - const fullScreenTab = getFullScreenTab(); - - if (fullScreenTab && fullScreenPanel) { - // Full screen open, but not focused - focus it - fullScreenPanel.reveal(); - return; - } - - // Full screen not open - open it - captureCommandTelemetry("openFullScreen"); - - // Create the full screen panel - let panel = vscode.window.createWebviewPanel( - "continue.continueGUIView", - "Continue", - vscode.ViewColumn.One, - { - retainContextWhenHidden: true, - }, - ); - fullScreenPanel = panel; - - // Add content to the panel - panel.webview.html = sidebar.getSidebarContent( - extensionContext, - panel, - undefined, - undefined, - true, - ); - - // When panel closes, reset the webview and focus - panel.onDidDispose( - () => { - sidebar.resetWebviewProtocolWebview(); - vscode.commands.executeCommand("continue.focusContinueInput"); - }, - null, - extensionContext.subscriptions, - ); - - vscode.commands.executeCommand("workbench.action.copyEditorToNewWindow"); - }, - "continue.openConfigJson": () => { - ide.openFile(getConfigJsonPath()); - }, - "continue.selectFilesAsContext": async ( - firstUri: vscode.Uri, - uris: vscode.Uri[], - ) => { - if (uris === undefined) { - throw new Error("No files were selected"); - } - - vscode.commands.executeCommand("continue.continueGUIView.focus"); - - for (const uri of uris) { - // If it's a folder, add the entire folder contents recursively by using walkDir (to ignore ignored files) - const isDirectory = await vscode.workspace.fs - .stat(uri) - ?.then((stat) => stat.type === vscode.FileType.Directory); - if (isDirectory) { - for await (const filepath of walkDirAsync(uri.fsPath, ide)) { - addEntireFileToContext( - uriFromFilePath(filepath), - false, - sidebar.webviewProtocol, - ); - } - } else { - addEntireFileToContext(uri, false, sidebar.webviewProtocol); + for (const uri of uris) { + // If it's a folder, add the entire folder contents recursively by using walkDir (to ignore ignored files) + const isDirectory = await vscode.workspace.fs + .stat(uri) + ?.then((stat) => stat.type === vscode.FileType.Directory); + if (isDirectory) { + for await (const filepath of walkDirAsync(uri.fsPath, ide)) { + addEntireFileToContext( + uriFromFilePath(filepath), + false, + sidebar.webviewProtocol, + ); } + } else { + addEntireFileToContext(uri, false, sidebar.webviewProtocol); } - }, - "continue.logAutocompleteOutcome": ( - completionId: string, - completionProvider: CompletionProvider, - ) => { - completionProvider.accept(completionId); - }, - "continue.toggleTabAutocompleteEnabled": () => { - captureCommandTelemetry("toggleTabAutocompleteEnabled"); + } + }, + "continue.logAutocompleteOutcome": ( + completionId: string, + completionProvider: CompletionProvider, + ) => { + completionProvider.accept(completionId); + }, + "continue.toggleTabAutocompleteEnabled": () => { + captureCommandTelemetry("toggleTabAutocompleteEnabled"); - const config = vscode.workspace.getConfiguration(EXTENSION_NAME); - const enabled = config.get("enableTabAutocomplete"); - const pauseOnBattery = config.get( - "pauseTabAutocompleteOnBattery", + const config = vscode.workspace.getConfiguration(EXTENSION_NAME); + const enabled = config.get("enableTabAutocomplete"); + const pauseOnBattery = config.get( + "pauseTabAutocompleteOnBattery", + ); + if (!pauseOnBattery || battery.isACConnected()) { + config.update( + "enableTabAutocomplete", + !enabled, + vscode.ConfigurationTarget.Global, ); - if (!pauseOnBattery || battery.isACConnected()) { + } else { + if (enabled) { + const paused = getStatusBarStatus() === StatusBarStatus.Paused; + if (paused) { + setupStatusBar(StatusBarStatus.Enabled); + } else { + config.update( + "enableTabAutocomplete", + false, + vscode.ConfigurationTarget.Global, + ); + } + } else { + setupStatusBar(StatusBarStatus.Paused); config.update( "enableTabAutocomplete", - !enabled, + true, vscode.ConfigurationTarget.Global, ); - } else { - if (enabled) { - const paused = getStatusBarStatus() === StatusBarStatus.Paused; - if (paused) { - setupStatusBar(StatusBarStatus.Enabled); - } else { - config.update( - "enableTabAutocomplete", - false, - vscode.ConfigurationTarget.Global, - ); - } - } else { - setupStatusBar(StatusBarStatus.Paused); - config.update( - "enableTabAutocomplete", - true, - vscode.ConfigurationTarget.Global, - ); - } } - }, - "continue.openTabAutocompleteConfigMenu": async () => { - captureCommandTelemetry("openTabAutocompleteConfigMenu"); + } + }, + "continue.openTabAutocompleteConfigMenu": async () => { + captureCommandTelemetry("openTabAutocompleteConfigMenu"); - const config = vscode.workspace.getConfiguration(EXTENSION_NAME); - const quickPick = vscode.window.createQuickPick(); - const autocompleteModels = - (await configHandler.loadConfig())?.tabAutocompleteModels ?? []; + const config = vscode.workspace.getConfiguration(EXTENSION_NAME); + const quickPick = vscode.window.createQuickPick(); + const autocompleteModels = + (await configHandler.loadConfig())?.tabAutocompleteModels ?? []; - let selected = new GlobalContext().get("selectedTabAutocompleteModel"); - if ( - !selected || - !autocompleteModels.some((model) => model.title === selected) - ) { - selected = autocompleteModels[0].title; - } + let selected = new GlobalContext().get("selectedTabAutocompleteModel"); + if ( + !selected || + !autocompleteModels.some((model) => model.title === selected) + ) { + selected = autocompleteModels[0].title; + } - // Toggle between Disabled, Paused, and Enabled - const pauseOnBattery = - config.get("pauseTabAutocompleteOnBattery") && - !battery.isACConnected(); - const currentStatus = getStatusBarStatus(); + // Toggle between Disabled, Paused, and Enabled + const pauseOnBattery = + config.get("pauseTabAutocompleteOnBattery") && + !battery.isACConnected(); + const currentStatus = getStatusBarStatus(); - let targetStatus: StatusBarStatus | undefined; - if (pauseOnBattery) { - // Cycle from Disabled -> Paused -> Enabled - targetStatus = - currentStatus === StatusBarStatus.Paused - ? StatusBarStatus.Enabled - : currentStatus === StatusBarStatus.Disabled - ? StatusBarStatus.Paused - : StatusBarStatus.Disabled; - } else { - // Toggle between Disabled and Enabled - targetStatus = - currentStatus === StatusBarStatus.Disabled - ? StatusBarStatus.Enabled + let targetStatus: StatusBarStatus | undefined; + if (pauseOnBattery) { + // Cycle from Disabled -> Paused -> Enabled + targetStatus = + currentStatus === StatusBarStatus.Paused + ? StatusBarStatus.Enabled + : currentStatus === StatusBarStatus.Disabled + ? StatusBarStatus.Paused : StatusBarStatus.Disabled; - } - quickPick.items = [ - { - label: "$(question) Open help center", - }, - { - label: "$(comment) Open chat (Cmd+L)", - }, - { - label: "$(screen-full) Open full screen chat (Cmd+K Cmd+M)", - }, - { - label: quickPickStatusText(targetStatus), - }, - { - label: "$(gear) Configure autocomplete options", - }, - { - label: "$(feedback) Give feedback", - }, - { - kind: vscode.QuickPickItemKind.Separator, - label: "Switch model", - }, - ...autocompleteModels.map((model) => ({ - label: getAutocompleteStatusBarTitle(selected, model), - description: getAutocompleteStatusBarDescription(selected, model), - })), - ]; - quickPick.onDidAccept(() => { - const selectedOption = quickPick.selectedItems[0].label; - const targetStatus = - getStatusBarStatusFromQuickPickItemLabel(selectedOption); + } else { + // Toggle between Disabled and Enabled + targetStatus = + currentStatus === StatusBarStatus.Disabled + ? StatusBarStatus.Enabled + : StatusBarStatus.Disabled; + } + quickPick.items = [ + { + label: "$(question) Open help center", + }, + { + label: "$(comment) Open chat (Cmd+L)", + }, + { + label: "$(screen-full) Open full screen chat (Cmd+K Cmd+M)", + }, + { + label: quickPickStatusText(targetStatus), + }, + { + label: "$(gear) Configure autocomplete options", + }, + { + label: "$(feedback) Give feedback", + }, + { + kind: vscode.QuickPickItemKind.Separator, + label: "Switch model", + }, + ...autocompleteModels.map((model) => ({ + label: getAutocompleteStatusBarTitle(selected, model), + description: getAutocompleteStatusBarDescription(selected, model), + })), + ]; + quickPick.onDidAccept(() => { + const selectedOption = quickPick.selectedItems[0].label; + const targetStatus = + getStatusBarStatusFromQuickPickItemLabel(selectedOption); - if (targetStatus !== undefined) { - setupStatusBar(targetStatus); - config.update( - "enableTabAutocomplete", - targetStatus === StatusBarStatus.Enabled, - vscode.ConfigurationTarget.Global, - ); - } else if ( - selectedOption === "$(gear) Configure autocomplete options" - ) { - ide.openFile(getConfigJsonPath()); - } else if ( - autocompleteModels.some((model) => model.title === selectedOption) - ) { - new GlobalContext().update( - "selectedTabAutocompleteModel", - selectedOption, - ); - configHandler.reloadConfig(); - } else if (selectedOption === "$(feedback) Give feedback") { - vscode.commands.executeCommand("continue.giveAutocompleteFeedback"); - } else if (selectedOption === "$(comment) Open chat (Cmd+L)") { - vscode.commands.executeCommand("continue.focusContinueInput"); - } else if ( - selectedOption === - "$(screen-full) Open full screen chat (Cmd+K Cmd+M)" - ) { - vscode.commands.executeCommand("continue.toggleFullScreen"); - } else if (selectedOption === "$(question) Open help center") { - focusGUI(); - vscode.commands.executeCommand("continue.navigateTo", "/more"); - } - quickPick.dispose(); - }); - quickPick.show(); - }, - "continue.giveAutocompleteFeedback": async () => { - const feedback = await vscode.window.showInputBox({ - ignoreFocusOut: true, - prompt: - "Please share what went wrong with the last completion. The details of the completion as well as this message will be sent to the Continue team in order to improve.", - }); - if (feedback) { - const client = await continueServerClientPromise; - const completionsPath = getDevDataFilePath("autocomplete"); - - const lastLines = await readLastLines.read(completionsPath, 2); - client.sendFeedback(feedback, lastLines); + if (targetStatus !== undefined) { + setupStatusBar(targetStatus); + config.update( + "enableTabAutocomplete", + targetStatus === StatusBarStatus.Enabled, + vscode.ConfigurationTarget.Global, + ); + } else if ( + selectedOption === "$(gear) Configure autocomplete options" + ) { + ide.openFile(getConfigJsonPath()); + } else if ( + autocompleteModels.some((model) => model.title === selectedOption) + ) { + new GlobalContext().update( + "selectedTabAutocompleteModel", + selectedOption, + ); + configHandler.reloadConfig(); + } else if (selectedOption === "$(feedback) Give feedback") { + vscode.commands.executeCommand("continue.giveAutocompleteFeedback"); + } else if (selectedOption === "$(comment) Open chat (Cmd+L)") { + vscode.commands.executeCommand("continue.focusContinueInput"); + } else if ( + selectedOption === + "$(screen-full) Open full screen chat (Cmd+K Cmd+M)" + ) { + vscode.commands.executeCommand("continue.toggleFullScreen"); + } else if (selectedOption === "$(question) Open help center") { + focusGUI(); + vscode.commands.executeCommand("continue.navigateTo", "/more"); } - }, - "continue.navigateTo": (path: string) => { - sidebar.webviewProtocol?.request("navigateTo", { path }); - focusGUI(); - }, - }; + quickPick.dispose(); + }); + quickPick.show(); + }, + "continue.giveAutocompleteFeedback": async () => { + const feedback = await vscode.window.showInputBox({ + ignoreFocusOut: true, + prompt: + "Please share what went wrong with the last completion. The details of the completion as well as this message will be sent to the Continue team in order to improve.", + }); + if (feedback) { + const client = await continueServerClientPromise; + const completionsPath = getDevDataFilePath("autocomplete"); + + const lastLines = await readLastLines.read(completionsPath, 2); + client.sendFeedback(feedback, lastLines); + } + }, + "continue.navigateTo": (path: string) => { + sidebar.webviewProtocol?.request("navigateTo", { path }); + focusGUI(); + }, }; +}; export function registerAllCommands( context: vscode.ExtensionContext, diff --git a/gui/src/components/index.ts b/gui/src/components/index.ts index 0a4ceb5e3..7a04bf43a 100644 --- a/gui/src/components/index.ts +++ b/gui/src/components/index.ts @@ -18,6 +18,10 @@ export const VSC_INPUT_BORDER_FOCUS_VAR = "--vscode-focusBorder"; export const VSC_BADGE_BACKGROUND_VAR = "--vscode-badge-background"; export const VSC_BADGE_FOREGROUND_VAR = "--vscode-badge-foreground"; export const VSC_SIDEBAR_BORDER_VAR = "--vscode-sideBar-border"; +export const VSC_DIFF_REMOVED_LINE_BACKGROUND_VAR = + "--vscode-diffEditor-removedLineBackground"; +export const VSC_DIFF_INSERTED_LINE_BACKGROUND_VAR = + "--vscode-diffEditor-insertedLineBackground"; export const VSC_THEME_COLOR_VARS = [ VSC_INPUT_BACKGROUND_VAR, @@ -35,6 +39,8 @@ export const VSC_THEME_COLOR_VARS = [ VSC_BADGE_BACKGROUND_VAR, VSC_SIDEBAR_BORDER_VAR, VSC_BADGE_FOREGROUND_VAR, + VSC_DIFF_REMOVED_LINE_BACKGROUND_VAR, + VSC_DIFF_INSERTED_LINE_BACKGROUND_VAR, ]; export const defaultBorderRadius = "5px"; @@ -56,6 +62,8 @@ export const vscInputBorderFocus = `var(${VSC_INPUT_BORDER_FOCUS_VAR}, ${lightGr export const vscBadgeBackground = `var(${VSC_BADGE_BACKGROUND_VAR}, #1bbe84)`; export const vscBadgeForeground = `var(${VSC_BADGE_FOREGROUND_VAR}, #fff)`; export const vscSidebarBorder = `var(${VSC_SIDEBAR_BORDER_VAR}, transparent)`; +export const vscDiffRemovedLineBackground = `var(${VSC_DIFF_REMOVED_LINE_BACKGROUND_VAR}, #808080)`; +export const vscDiffInsertedLineBackground = `var(${VSC_DIFF_INSERTED_LINE_BACKGROUND_VAR}, #28a745)`; if (typeof document !== "undefined") { for (const colorVar of VSC_THEME_COLOR_VARS) { @@ -101,20 +109,25 @@ export function parseColorForHex(colorVar: string): string { colorVar, ); if (value.startsWith("#")) { + console.log("OAIJFIOJOOJOIO", colorVar, value, value.slice(0, 7)); return value.slice(0, 7); } - // Parse rgb - const rgb = value - .slice(4, -1) + // Parse rgb/rgba + const rgbValues = value + .slice(value.startsWith("rgba") ? 5 : 4, -1) .split(",") + .map((x) => x.trim()) + .filter((_, i) => i < 3) // Only take the first 3 values (RGB, ignore alpha) .map((x) => parseInt(x, 10)); + let hex = "#" + - rgb + rgbValues .map((x) => x.toString(16)) .map((x) => (x.length === 1 ? "0" + x : x)) .join(""); + return hex; } diff --git a/gui/src/pages/edit.tsx b/gui/src/pages/edit.tsx index f05648875..9629d4d66 100644 --- a/gui/src/pages/edit.tsx +++ b/gui/src/pages/edit.tsx @@ -7,7 +7,14 @@ import { useContext, useEffect, useState } from "react"; import { useDispatch, useSelector } from "react-redux"; import { useNavigate } from "react-router-dom"; import styled from "styled-components"; -import { defaultBorderRadius, lightGray, vscForeground } from "../components"; +import { + defaultBorderRadius, + lightGray, + parseColorForHex, + VSC_DIFF_INSERTED_LINE_BACKGROUND_VAR, + VSC_DIFF_REMOVED_LINE_BACKGROUND_VAR, + vscForeground, +} from "../components"; import FileIcon from "../components/FileIcon"; import { NewSessionButton } from "../components/mainInput/NewSessionButton"; import resolveEditorContent from "../components/mainInput/resolveInput"; @@ -162,7 +169,7 @@ function Edit() { placeholder={ ["streaming", "accepting"].includes(editModeState.editStatus) ? "Enter instructions for edit" - : "Enter follow-up instructions" + : "Enter instructions for edit" } border={`1px solid #aa0`} availableContextProviders={availableContextProviders.filter( @@ -203,7 +210,9 @@ function Edit() {
{ ideMessenger.request("edit/acceptReject", { accept: false, @@ -217,7 +226,9 @@ function Edit() { { ideMessenger.request("edit/acceptReject", { accept: true, @@ -240,7 +251,7 @@ function Edit() { className="mr-auto flex items-center gap-2" > - Back to chat + Back to Chat
From 3e4c75bf461c36c2200ac2922670bb76a612b292 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Fri, 8 Nov 2024 16:18:37 +0700 Subject: [PATCH 84/96] fix: remove debugger statement --- .../filtering/streamTransforms/StreamTransformPipeline.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts b/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts index 08a318a59..88ae0c352 100644 --- a/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts +++ b/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts @@ -26,7 +26,6 @@ export class StreamTransformPipeline { charGenerator = stopAtStopTokens(generator, stopTokens); for (const charFilter of helper.lang.charFilters ?? []) { - debugger; charGenerator = charFilter({ chars: charGenerator, prefix, From 52caeda487c3a1da5696a79423fc60d4362b5f74 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 8 Nov 2024 09:09:46 -0800 Subject: [PATCH 85/96] lmstudio embeddings p1 --- core/index.d.ts | 1 + core/indexing/embeddings/LMStudio.ts | 13 +++++++++++++ .../customize/model-providers/more/textgenwebui.md | 2 +- 3 files changed, 15 insertions(+), 1 deletion(-) create mode 100644 core/indexing/embeddings/LMStudio.ts diff --git a/core/index.d.ts b/core/index.d.ts index ef8b7c128..1c14820af 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -834,6 +834,7 @@ export type EmbeddingsProviderName = | "ollama" | "openai" | "cohere" + | "lmstudio" | "free-trial" | "gemini" | "continue-proxy" diff --git a/core/indexing/embeddings/LMStudio.ts b/core/indexing/embeddings/LMStudio.ts new file mode 100644 index 000000000..af5e390fb --- /dev/null +++ b/core/indexing/embeddings/LMStudio.ts @@ -0,0 +1,13 @@ +import { EmbeddingsProviderName, EmbedOptions } from "../.."; +import OpenAIEmbeddingsProvider from "./OpenAIEmbeddingsProvider"; + +class LMStudioEmbeddingsProvider extends OpenAIEmbeddingsProvider { + static providerName: EmbeddingsProviderName = "lmstudio"; + + static defaultOptions: Partial | undefined = { + apiBase: "http://localhost:1234/v1", + model: "BAAI/bge-en-icl", + }; +} + +export default LMStudioEmbeddingsProvider; \ No newline at end of file diff --git a/docs/docs/customize/model-providers/more/textgenwebui.md b/docs/docs/customize/model-providers/more/textgenwebui.md index 9abf2b9e8..723079735 100644 --- a/docs/docs/customize/model-providers/more/textgenwebui.md +++ b/docs/docs/customize/model-providers/more/textgenwebui.md @@ -8,7 +8,7 @@ TextGenWebUI is a comprehensive, open-source language model UI and local server. { "title": "Text Generation WebUI", "provider": "text-gen-webui", - "apiBase": "http://localhost:5000", + "apiBase": "http://localhost:5000/v1", "model": "MODEL_NAME" } ] From 4683ce871cdceda3ade1b2d9110582c38ce7e75d Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 8 Nov 2024 09:09:46 -0800 Subject: [PATCH 86/96] lmstudio embeddings p1 --- core/index.d.ts | 1 + core/indexing/embeddings/LMStudio.ts | 13 +++++++++++++ .../customize/model-providers/more/textgenwebui.md | 2 +- 3 files changed, 15 insertions(+), 1 deletion(-) create mode 100644 core/indexing/embeddings/LMStudio.ts diff --git a/core/index.d.ts b/core/index.d.ts index ef8b7c128..1c14820af 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -834,6 +834,7 @@ export type EmbeddingsProviderName = | "ollama" | "openai" | "cohere" + | "lmstudio" | "free-trial" | "gemini" | "continue-proxy" diff --git a/core/indexing/embeddings/LMStudio.ts b/core/indexing/embeddings/LMStudio.ts new file mode 100644 index 000000000..af5e390fb --- /dev/null +++ b/core/indexing/embeddings/LMStudio.ts @@ -0,0 +1,13 @@ +import { EmbeddingsProviderName, EmbedOptions } from "../.."; +import OpenAIEmbeddingsProvider from "./OpenAIEmbeddingsProvider"; + +class LMStudioEmbeddingsProvider extends OpenAIEmbeddingsProvider { + static providerName: EmbeddingsProviderName = "lmstudio"; + + static defaultOptions: Partial | undefined = { + apiBase: "http://localhost:1234/v1", + model: "BAAI/bge-en-icl", + }; +} + +export default LMStudioEmbeddingsProvider; \ No newline at end of file diff --git a/docs/docs/customize/model-providers/more/textgenwebui.md b/docs/docs/customize/model-providers/more/textgenwebui.md index 9abf2b9e8..723079735 100644 --- a/docs/docs/customize/model-providers/more/textgenwebui.md +++ b/docs/docs/customize/model-providers/more/textgenwebui.md @@ -8,7 +8,7 @@ TextGenWebUI is a comprehensive, open-source language model UI and local server. { "title": "Text Generation WebUI", "provider": "text-gen-webui", - "apiBase": "http://localhost:5000", + "apiBase": "http://localhost:5000/v1", "model": "MODEL_NAME" } ] From 400d608a287e681c9fecde9f51a7c9c68ee79374 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 8 Nov 2024 10:46:49 -0800 Subject: [PATCH 87/96] docs and config schema --- core/indexing/embeddings/LMStudio.ts | 2 +- core/indexing/embeddings/index.ts | 4 +++- .../customize/model-providers/more/lmstudio.md | 15 +++++++++++++++ extensions/vscode/config_schema.json | 7 ++++++- 4 files changed, 25 insertions(+), 3 deletions(-) diff --git a/core/indexing/embeddings/LMStudio.ts b/core/indexing/embeddings/LMStudio.ts index af5e390fb..f5ec128d3 100644 --- a/core/indexing/embeddings/LMStudio.ts +++ b/core/indexing/embeddings/LMStudio.ts @@ -6,7 +6,7 @@ class LMStudioEmbeddingsProvider extends OpenAIEmbeddingsProvider { static defaultOptions: Partial | undefined = { apiBase: "http://localhost:1234/v1", - model: "BAAI/bge-en-icl", + model: "nomic-ai/nomic-embed-text-v1.5-GGUF", }; } diff --git a/core/indexing/embeddings/index.ts b/core/indexing/embeddings/index.ts index 7b62340e1..b0508d3fd 100644 --- a/core/indexing/embeddings/index.ts +++ b/core/indexing/embeddings/index.ts @@ -17,6 +17,7 @@ import VoyageEmbeddingsProvider from "./VoyageEmbeddingsProvider.js"; import VertexEmbeddingsProvider from "./VertexEmbeddingsProvider.js"; import WatsonxEmbeddingsProvider from "./WatsonxEmbeddingsProvider.js"; import NebiusEmbeddingsProvider from "./NebiusEmbeddingsProvider.js"; +import LMStudioEmbeddingsProvider from "./LMStudio.js"; type EmbeddingsProviderConstructor = new ( ...args: any[] @@ -42,5 +43,6 @@ export const allEmbeddingsProviders: Record< mistral: MistralEmbeddingsProvider, nebius: NebiusEmbeddingsProvider, vertexai: VertexEmbeddingsProvider, - watsonx: WatsonxEmbeddingsProvider + watsonx: WatsonxEmbeddingsProvider, + lmstudio: LMStudioEmbeddingsProvider }; diff --git a/docs/docs/customize/model-providers/more/lmstudio.md b/docs/docs/customize/model-providers/more/lmstudio.md index 7448ebd01..466ccaaed 100644 --- a/docs/docs/customize/model-providers/more/lmstudio.md +++ b/docs/docs/customize/model-providers/more/lmstudio.md @@ -14,6 +14,21 @@ } ``` +### Embeddings model + +LMStudio supports embeddings endpoints, and comes with the `nomic-ai/nomic-embed-text-v1.5-GGUF` model (as of Nov 2024, check your models) + +```json title="config.json" +{ + "embeddingsProvider": [ + { + "provider": "lmstudio", + "model": "nomic-ai/nomic-embed-text-v1.5-GGUF" + } + ] +} +``` + ## Setting up a remote instance To configure a remote instance of LM Studio, add the `"apiBase"` property to your model in config.json: diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index f18bdbb6a..8dff320fd 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -2717,13 +2717,18 @@ "openai", "cohere", "free-trial", + "continue-proxy", "gemini", "voyage", "nvidia", "bedrock", "sagemaker", "nebius", - "vertexai" + "vertexai", + "deepinfra", + "mistral", + "watsonx", + "lmstudio" ] }, "model": { From d764dddf75b373315ab6fd31d07b057f15d8ca88 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 8 Nov 2024 10:55:43 -0800 Subject: [PATCH 88/96] embeddings docs fixes --- .../model-providers/more/lmstudio.md | 10 ++++---- .../customize/model-providers/more/nvidia.md | 12 ++++------ docs/docs/customize/model-types/embeddings.md | 24 +++++++++++++++++++ 3 files changed, 33 insertions(+), 13 deletions(-) diff --git a/docs/docs/customize/model-providers/more/lmstudio.md b/docs/docs/customize/model-providers/more/lmstudio.md index 466ccaaed..a901f811a 100644 --- a/docs/docs/customize/model-providers/more/lmstudio.md +++ b/docs/docs/customize/model-providers/more/lmstudio.md @@ -20,12 +20,10 @@ LMStudio supports embeddings endpoints, and comes with the `nomic-ai/nomic-embed ```json title="config.json" { - "embeddingsProvider": [ - { - "provider": "lmstudio", - "model": "nomic-ai/nomic-embed-text-v1.5-GGUF" - } - ] + "embeddingsProvider": { + "provider": "lmstudio", + "model": "nomic-ai/nomic-embed-text-v1.5-GGUF" + } } ``` diff --git a/docs/docs/customize/model-providers/more/nvidia.md b/docs/docs/customize/model-providers/more/nvidia.md index e59f131b7..049ff7754 100644 --- a/docs/docs/customize/model-providers/more/nvidia.md +++ b/docs/docs/customize/model-providers/more/nvidia.md @@ -37,13 +37,11 @@ We recommend configuring **NVIDIA Retrieval QA Mistral 7B** as your embeddings m ```json title="config.json" { - "embeddingsProvider": [ - { - "provider": "nvidia", - "model": "nvidia/nv-embedqa-mistral-7b-v2", - "apiKey": "[API_KEY]" - } - ] + "embeddingsProvider": { + "provider": "nvidia", + "model": "nvidia/nv-embedqa-mistral-7b-v2", + "apiKey": "[API_KEY]" + } } ``` diff --git a/docs/docs/customize/model-types/embeddings.md b/docs/docs/customize/model-types/embeddings.md index 4bcc88785..882c5da79 100644 --- a/docs/docs/customize/model-types/embeddings.md +++ b/docs/docs/customize/model-types/embeddings.md @@ -13,6 +13,10 @@ In Continue, embeddings are generated during indexing and then used by [@Codebas `transformers.js` is used as a default embeddings model in VS Code. In JetBrains, there currently is no default. ::: +:::info[Free Trial] +The free trial supports embeddings (provider: `free-trial`) +::: + ## Recommended embedding models If you have the ability to use any model, we recommend `voyage-code-2`, which is listed below along with the rest of the options for embeddings models. @@ -77,3 +81,23 @@ See [here](../model-providers/top-level/gemini.md#embeddings-model) for instruct ### Vertex See [here](../model-providers/top-level/vertexai.md#embeddings-model) for instructions on how to use Vertex for embeddings. + +### Mistral + +See [here](../model-providers/top-level/mistral.md#embeddings-model) for instructions on how to use Mistral for embeddings. + +### NVIDIA + +See [here](../model-providers/more/nvidia.md#embeddings-model) for instructions on how to use NVIDIA for embeddings. + +### Bedrock + +See [here](../model-providers/top-level/bedrock.md#embeddings-model) for instructions on how to use Bedrock for embeddings. + +### WatsonX + +See [here](../model-providers/more/watsonx.md#embeddings-model) for instructions on how to use WatsonX for embeddings. + +### LMStudio + +See [here](../model-providers/more/lmstudio.md#embeddings-model) for instructions on how to use LMStudio for embeddings. From 9ce9fcbd6fcd854f864c41e592599ad86faa039f Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 8 Nov 2024 11:16:48 -0800 Subject: [PATCH 89/96] smooth scroll to bottom on session id change --- gui/src/pages/gui/Chat.tsx | 38 +++++++++++++++++++++++++++----------- 1 file changed, 27 insertions(+), 11 deletions(-) diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 6ca0cc167..27e9be2cd 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -136,7 +136,6 @@ export function Chat() { const { streamResponse } = useChatHandler(dispatch, ideMessenger); 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); @@ -148,7 +147,7 @@ export function Chat() { const { saveSession, getLastSessionId, loadLastSession } = useHistory(dispatch); - const scrollToBottom = useCallback(() => { + const snapToBottom = useCallback(() => { if (!topGuiDivRef.current) return; const elem = topGuiDivRef.current; elem.scrollTop = elem.scrollHeight - elem.clientHeight; @@ -156,9 +155,26 @@ export function Chat() { setIsAtBottom(true); }, [topGuiDivRef, setIsAtBottom]); + const smoothScrollToBottom = useCallback(async () => { + if (!topGuiDivRef.current) return; + const elem = topGuiDivRef.current + elem.scrollTo({ + top: elem.scrollHeight - elem.clientHeight, + behavior: 'smooth' + }) + + setIsAtBottom(true); + }, [topGuiDivRef, setIsAtBottom]); + useEffect(() => { - if (active) scrollToBottom(); - }, [active, scrollToBottom]); + if (active) snapToBottom(); + }, [active, snapToBottom]); + + useEffect(() => { + setTimeout(() => { + smoothScrollToBottom(); + }, 250) + }, [smoothScrollToBottom, state.sessionId]); useEffect(() => { // Cmd + Backspace to delete current step @@ -284,8 +300,8 @@ export function Chat() { } }, [ - sessionState.history, - sessionState.contextItems, + state.history, + state.contextItems, defaultModel, state, streamResponse, @@ -370,11 +386,11 @@ export function Chat() { : true : stepsOpen[index]! } - onToggle={() => {}} + onToggle={() => { }} > {}} + onUserInput={(input: string) => { }} item={item} - onReverse={() => {}} + onReverse={() => { }} onRetry={() => { streamResponse( state.history[index - 1].editorState, state.history[index - 1].modifiers ?? - defaultInputModifiers, + defaultInputModifiers, ideMessenger, index - 1, ); From 7e1e88158a1062fa30dc5d4dc8a7ae5484628a62 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 8 Nov 2024 11:49:47 -0800 Subject: [PATCH 90/96] update changelog --- .changes/unreleased/Added-20241108-113942.yaml | 4 ++++ .changes/unreleased/Added-20241108-114100.yaml | 4 ++++ .changes/unreleased/Added-20241108-114423.yaml | 4 ++++ .changes/unreleased/Added-20241108-114437.yaml | 4 ++++ .changes/unreleased/Added-20241108-114450.yaml | 4 ++++ .changes/unreleased/Added-20241108-114612.yaml | 4 ++++ .changes/unreleased/Added-20241108-114622.yaml | 4 ++++ .changes/unreleased/Added-20241108-114649.yaml | 4 ++++ .changes/unreleased/Added-20241108-114753.yaml | 4 ++++ .changes/unreleased/Added-20241108-114813.yaml | 4 ++++ .changes/unreleased/Changed-20241108-114549.yaml | 4 ++++ .changes/unreleased/Changed-20241108-114850.yaml | 4 ++++ .changes/unreleased/Fixed-20241108-114322.yaml | 4 ++++ .changes/unreleased/Fixed-20241108-114707.yaml | 4 ++++ .changes/unreleased/Fixed-20241108-114905.yaml | 4 ++++ extensions/intellij/CHANGELOG.md | 2 ++ extensions/vscode/CHANGELOG.md | 15 +++++++++++++++ 17 files changed, 77 insertions(+) create mode 100644 .changes/unreleased/Added-20241108-113942.yaml create mode 100644 .changes/unreleased/Added-20241108-114100.yaml create mode 100644 .changes/unreleased/Added-20241108-114423.yaml create mode 100644 .changes/unreleased/Added-20241108-114437.yaml create mode 100644 .changes/unreleased/Added-20241108-114450.yaml create mode 100644 .changes/unreleased/Added-20241108-114612.yaml create mode 100644 .changes/unreleased/Added-20241108-114622.yaml create mode 100644 .changes/unreleased/Added-20241108-114649.yaml create mode 100644 .changes/unreleased/Added-20241108-114753.yaml create mode 100644 .changes/unreleased/Added-20241108-114813.yaml create mode 100644 .changes/unreleased/Changed-20241108-114549.yaml create mode 100644 .changes/unreleased/Changed-20241108-114850.yaml create mode 100644 .changes/unreleased/Fixed-20241108-114322.yaml create mode 100644 .changes/unreleased/Fixed-20241108-114707.yaml create mode 100644 .changes/unreleased/Fixed-20241108-114905.yaml diff --git a/.changes/unreleased/Added-20241108-113942.yaml b/.changes/unreleased/Added-20241108-113942.yaml new file mode 100644 index 000000000..987643345 --- /dev/null +++ b/.changes/unreleased/Added-20241108-113942.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Added +body: OpenAI predicted outputs support +time: 2024-11-08T11:39:42.277047-08:00 diff --git a/.changes/unreleased/Added-20241108-114100.yaml b/.changes/unreleased/Added-20241108-114100.yaml new file mode 100644 index 000000000..af7cb5444 --- /dev/null +++ b/.changes/unreleased/Added-20241108-114100.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Added +body: Improve codebase retrieval with BM25 +time: 2024-11-08T11:41:00.002716-08:00 diff --git a/.changes/unreleased/Added-20241108-114423.yaml b/.changes/unreleased/Added-20241108-114423.yaml new file mode 100644 index 000000000..fc3a6eaf7 --- /dev/null +++ b/.changes/unreleased/Added-20241108-114423.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Added +body: Support for Grok from xAI +time: 2024-11-08T11:44:23.761084-08:00 diff --git a/.changes/unreleased/Added-20241108-114437.yaml b/.changes/unreleased/Added-20241108-114437.yaml new file mode 100644 index 000000000..fab18b954 --- /dev/null +++ b/.changes/unreleased/Added-20241108-114437.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Added +body: Chat enhancements including sticking input to bottom +time: 2024-11-08T11:44:37.408176-08:00 diff --git a/.changes/unreleased/Added-20241108-114450.yaml b/.changes/unreleased/Added-20241108-114450.yaml new file mode 100644 index 000000000..14644f3e9 --- /dev/null +++ b/.changes/unreleased/Added-20241108-114450.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Added +body: New UI for cmd+I in sidebar +time: 2024-11-08T11:44:50.682952-08:00 diff --git a/.changes/unreleased/Added-20241108-114612.yaml b/.changes/unreleased/Added-20241108-114612.yaml new file mode 100644 index 000000000..68d8b27d1 --- /dev/null +++ b/.changes/unreleased/Added-20241108-114612.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Added +body: Support for Nebius LLM provider +time: 2024-11-08T11:46:12.94828-08:00 diff --git a/.changes/unreleased/Added-20241108-114622.yaml b/.changes/unreleased/Added-20241108-114622.yaml new file mode 100644 index 000000000..e91ddb398 --- /dev/null +++ b/.changes/unreleased/Added-20241108-114622.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Added +body: Support for Ask Sage LLM provider +time: 2024-11-08T11:46:22.626907-08:00 diff --git a/.changes/unreleased/Added-20241108-114649.yaml b/.changes/unreleased/Added-20241108-114649.yaml new file mode 100644 index 000000000..0e7a0c9d0 --- /dev/null +++ b/.changes/unreleased/Added-20241108-114649.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Added +body: Improved reference for config.json +time: 2024-11-08T11:46:49.648545-08:00 diff --git a/.changes/unreleased/Added-20241108-114753.yaml b/.changes/unreleased/Added-20241108-114753.yaml new file mode 100644 index 000000000..8cb7f1805 --- /dev/null +++ b/.changes/unreleased/Added-20241108-114753.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Added +body: New @web context provider +time: 2024-11-08T11:47:53.447346-08:00 diff --git a/.changes/unreleased/Added-20241108-114813.yaml b/.changes/unreleased/Added-20241108-114813.yaml new file mode 100644 index 000000000..cd5ba1067 --- /dev/null +++ b/.changes/unreleased/Added-20241108-114813.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Added +body: Updates for llama3.2 +time: 2024-11-08T11:48:13.830692-08:00 diff --git a/.changes/unreleased/Changed-20241108-114549.yaml b/.changes/unreleased/Changed-20241108-114549.yaml new file mode 100644 index 000000000..d340736b6 --- /dev/null +++ b/.changes/unreleased/Changed-20241108-114549.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Changed +body: Improved @docs crawler +time: 2024-11-08T11:45:49.381554-08:00 diff --git a/.changes/unreleased/Changed-20241108-114850.yaml b/.changes/unreleased/Changed-20241108-114850.yaml new file mode 100644 index 000000000..ab6c2a037 --- /dev/null +++ b/.changes/unreleased/Changed-20241108-114850.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Changed +body: Many improvements to make autocomplete more eager +time: 2024-11-08T11:48:50.486502-08:00 diff --git a/.changes/unreleased/Fixed-20241108-114322.yaml b/.changes/unreleased/Fixed-20241108-114322.yaml new file mode 100644 index 000000000..e896eac4d --- /dev/null +++ b/.changes/unreleased/Fixed-20241108-114322.yaml @@ -0,0 +1,4 @@ +project: extensions/intellij +kind: Fixed +body: OSR-related fixes for non-Mac users +time: 2024-11-08T11:43:22.623155-08:00 diff --git a/.changes/unreleased/Fixed-20241108-114707.yaml b/.changes/unreleased/Fixed-20241108-114707.yaml new file mode 100644 index 000000000..95c70c844 --- /dev/null +++ b/.changes/unreleased/Fixed-20241108-114707.yaml @@ -0,0 +1,4 @@ +project: extensions/intellij +kind: Fixed +body: Fixes for inline edit in JetBrains +time: 2024-11-08T11:47:07.953304-08:00 diff --git a/.changes/unreleased/Fixed-20241108-114905.yaml b/.changes/unreleased/Fixed-20241108-114905.yaml new file mode 100644 index 000000000..eb590eeb4 --- /dev/null +++ b/.changes/unreleased/Fixed-20241108-114905.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Fixed +body: Brought back the Apply button for all code blocks +time: 2024-11-08T11:49:05.021499-08:00 diff --git a/extensions/intellij/CHANGELOG.md b/extensions/intellij/CHANGELOG.md index 0eb45541f..7745d5c91 100644 --- a/extensions/intellij/CHANGELOG.md +++ b/extensions/intellij/CHANGELOG.md @@ -8,6 +8,8 @@ and is generated by [Changie](https://github.com/miniscruff/changie). Pre-release Changes ### Fixed * Off-screen rendering to solve white flash on load and lack of changing cursor type +* OSR-related fixes for non-Mac users +* Fixes for inline edit in JetBrains ## 0.0.72 - 2024-10-04 ### Added diff --git a/extensions/vscode/CHANGELOG.md b/extensions/vscode/CHANGELOG.md index 030da9bcc..88925e7f4 100644 --- a/extensions/vscode/CHANGELOG.md +++ b/extensions/vscode/CHANGELOG.md @@ -9,6 +9,21 @@ Pre-release Changes ### Added * New Edit mode in sidebar (cmd/ctrl+I) * Significantly faster and more accurate docs crawler by default +* OpenAI predicted outputs support +* Improve codebase retrieval with BM25 +* Support for Grok from xAI +* Chat enhancements including sticking input to bottom +* New UI for cmd+I in sidebar +* Support for Nebius LLM provider +* Support for Ask Sage LLM provider +* Improved reference for config.json +* New @web context provider +* Updates for llama3.2 +### Changed +* Improved @docs crawler +* Many improvements to make autocomplete more eager +### Fixed +* Brought back the Apply button for all code blocks ## 0.8.55 - 2024-10-25 ### Added From 7c0474fbf71e13b85eb23904844d5405f5251068 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 8 Nov 2024 13:07:45 -0800 Subject: [PATCH 91/96] bump down package.json --- extensions/vscode/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 231f856c1..c38d47b0d 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -2,7 +2,7 @@ "name": "continue", "icon": "media/icon.png", "author": "Continue Dev, Inc", - "version": "0.9.227", + "version": "0.9.226", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" From f779bf0bfbd239b11e5de4aef24086d5b2855c2d Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 8 Nov 2024 13:40:26 -0800 Subject: [PATCH 92/96] fix type errors --- core/core.ts | 7 ++++--- extensions/vscode/package.json | 2 +- extensions/vscode/src/stubs/remoteConfig.ts | 15 ++++++++++++++- 3 files changed, 19 insertions(+), 5 deletions(-) diff --git a/core/core.ts b/core/core.ts index a3f59ec8e..c26b786ac 100644 --- a/core/core.ts +++ b/core/core.ts @@ -1,3 +1,5 @@ +import ignore from "ignore"; +import path from "path"; import { v4 as uuidv4 } from "uuid"; import type { ContextItemId, IDE, IndexingProgressUpdate } from "."; import { CompletionProvider } from "./autocomplete/completionProvider"; @@ -17,6 +19,7 @@ import { ControlPlaneClient } from "./control-plane/client"; import { streamDiffLines } from "./edit/streamDiffLines"; import { CodebaseIndexer, PauseToken } from "./indexing/CodebaseIndexer"; import DocsService from "./indexing/docs/DocsService"; +import { defaultIgnoreFile } from "./indexing/ignore.js"; import Ollama from "./llm/llms/Ollama"; import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; import { GlobalContext } from "./util/GlobalContext"; @@ -29,9 +32,6 @@ import type { IMessenger, Message } from "./util/messenger"; import { editConfigJson, setupInitialDotContinueDirectory } from "./util/paths"; import { Telemetry } from "./util/posthog"; import { TTS } from "./util/tts"; -import ignore from "ignore"; -import { defaultIgnoreFile } from "./indexing/ignore.js"; -import path from "path"; export class Core { // implements IMessenger @@ -401,6 +401,7 @@ export class Core { }); break; } + // @ts-ignore yield { content: next.value.content }; next = await gen.next(); } diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 231f856c1..c38d47b0d 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -2,7 +2,7 @@ "name": "continue", "icon": "media/icon.png", "author": "Continue Dev, Inc", - "version": "0.9.227", + "version": "0.9.226", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" diff --git a/extensions/vscode/src/stubs/remoteConfig.ts b/extensions/vscode/src/stubs/remoteConfig.ts index 24c197bd8..eb3cba824 100644 --- a/extensions/vscode/src/stubs/remoteConfig.ts +++ b/extensions/vscode/src/stubs/remoteConfig.ts @@ -67,6 +67,18 @@ export class RemoteConfigSync { }; } + private canParse(url: string): boolean { + if ((URL as any).canParse) { + return (URL as any).canParse(url); + } + try { + new URL(url); + return true; + } catch (e) { + return false; + } + } + async setup() { if ( this.userToken === null || @@ -75,7 +87,7 @@ export class RemoteConfigSync { ) { return; } - if (!URL.canParse(this.remoteConfigServerUrl)) { + if (!this.canParse(this.remoteConfigServerUrl)) { vscode.window.showErrorMessage( "The value set for 'remoteConfigServerUrl' is not valid: ", this.remoteConfigServerUrl, @@ -92,6 +104,7 @@ export class RemoteConfigSync { private setInterval() { if (this.syncInterval !== undefined) { + // @ts-ignore clearInterval(this.syncInterval); } this.syncInterval = setInterval( From 1095182f952e4912ecd2f691675ba3ff4144ad84 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 8 Nov 2024 14:49:05 -0800 Subject: [PATCH 93/96] use options showWhateverWeHaveAtXMs --- .../filtering/streamTransforms/StreamTransformPipeline.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts b/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts index 88ae0c352..8d7f3e23f 100644 --- a/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts +++ b/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts @@ -1,4 +1,5 @@ import { streamLines } from "../../../diff/util"; +import { DEFAULT_AUTOCOMPLETE_OPTS } from "../../../util/parameters"; import { HelperVars } from "../../util/HelperVars"; import { stopAtStopTokens } from "./charStream"; import { @@ -56,7 +57,11 @@ export class StreamTransformPipeline { fullStop, ); - lineGenerator = showWhateverWeHaveAtXMs(lineGenerator, 250); + lineGenerator = showWhateverWeHaveAtXMs( + lineGenerator, + helper.options.showWhateverWeHaveAtXMs ?? + (DEFAULT_AUTOCOMPLETE_OPTS.showWhateverWeHaveAtXMs as number), + ); const finalGenerator = streamWithNewLines(lineGenerator); for await (const update of finalGenerator) { From b47db1c3db8c90192b05ce28fc94564b2e8eac72 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 8 Nov 2024 16:12:06 -0800 Subject: [PATCH 94/96] allow editing main input while streaming active --- gui/src/components/mainInput/TipTapEditor.tsx | 77 ++++++++++--------- 1 file changed, 39 insertions(+), 38 deletions(-) diff --git a/gui/src/components/mainInput/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor.tsx index 01ee8dea6..6e2a55f90 100644 --- a/gui/src/components/mainInput/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor.tsx @@ -51,10 +51,6 @@ import { isJetBrains, isMetaEquivalentKeyPressed, } from "../../util"; -import { - handleJetBrainsMetaKeyPress, - handleMetaKeyPress, -} from "./handleMetaKeyPress"; import { CodeBlockExtension } from "./CodeBlockExtension"; import { SlashCommand } from "./CommandsExtension"; import InputToolbar, { ToolbarOptions } from "./InputToolbar"; @@ -64,6 +60,10 @@ import { getContextProviderDropdownOptions, getSlashCommandDropdownOptions, } from "./getSuggestion"; +import { + handleJetBrainsMetaKeyPress, + handleMetaKeyPress, +} from "./handleMetaKeyPress"; import { ComboBoxItem } from "./types"; const InputBoxDiv = styled.div<{ border?: string }>` @@ -248,8 +248,8 @@ function TipTapEditor(props: TipTapEditorProps) { const timer = setTimeout(() => { setHasDefaultModel( !!defaultModel && - defaultModel.apiKey !== undefined && - defaultModel.apiKey !== "", + defaultModel.apiKey !== undefined && + defaultModel.apiKey !== "", ); }, 3500); @@ -452,38 +452,38 @@ function TipTapEditor(props: TipTapEditorProps) { Text, props.availableContextProviders.length ? Mention.configure({ - HTMLAttributes: { - class: "mention", - }, - suggestion: getContextProviderDropdownOptions( - availableContextProvidersRef, - getSubmenuContextItemsRef, - enterSubmenu, - onClose, - onOpen, - inSubmenuRef, - ideMessenger, - ), - renderHTML: (props) => { - return `@${props.node.attrs.label || props.node.attrs.id}`; - }, - }) + HTMLAttributes: { + class: "mention", + }, + suggestion: getContextProviderDropdownOptions( + availableContextProvidersRef, + getSubmenuContextItemsRef, + enterSubmenu, + onClose, + onOpen, + inSubmenuRef, + ideMessenger, + ), + renderHTML: (props) => { + return `@${props.node.attrs.label || props.node.attrs.id}`; + }, + }) : undefined, props.availableSlashCommands.length ? SlashCommand.configure({ - HTMLAttributes: { - class: "mention", - }, - suggestion: getSlashCommandDropdownOptions( - availableSlashCommandsRef, - onClose, - onOpen, - ideMessenger, - ), - renderText: (props) => { - return props.node.attrs.label; - }, - }) + HTMLAttributes: { + class: "mention", + }, + suggestion: getSlashCommandDropdownOptions( + availableSlashCommandsRef, + onClose, + onOpen, + ideMessenger, + ), + renderText: (props) => { + return props.node.attrs.label; + }, + }) : undefined, CodeBlockExtension, ], @@ -532,7 +532,7 @@ function TipTapEditor(props: TipTapEditorProps) { } } }, - editable: !active, + editable: !active || props.isMainInput, }); const [shouldHideToolbar, setShouldHideToolbar] = useState(false); @@ -698,8 +698,9 @@ function TipTapEditor(props: TipTapEditorProps) { rif.filepath, await ideMessenger.ide.getWorkspaceDirs(), ); - const rangeStr = `(${rif.range.start.line + 1}-${rif.range.end.line + 1 - })`; + const rangeStr = `(${rif.range.start.line + 1}-${ + rif.range.end.line + 1 + })`; const item: ContextItemWithId = { content: rif.contents, name: `${basename} ${rangeStr}`, From 56caf96c6cd59b209101db68ef1de6f2fbd08e9f Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 8 Nov 2024 16:31:12 -0800 Subject: [PATCH 95/96] display range --- gui/src/components/markdown/CodeBlockToolbar.tsx | 7 +++++-- gui/src/components/markdown/PreWithToolbar.tsx | 2 ++ 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/gui/src/components/markdown/CodeBlockToolbar.tsx b/gui/src/components/markdown/CodeBlockToolbar.tsx index 6851a1a4c..c9eef3470 100644 --- a/gui/src/components/markdown/CodeBlockToolbar.tsx +++ b/gui/src/components/markdown/CodeBlockToolbar.tsx @@ -19,6 +19,7 @@ import { } from ".."; import { IdeMessengerContext } from "../../context/IdeMessenger"; import { useWebviewListener } from "../../hooks/useWebviewListener"; +import { defaultModelSelector } from "../../redux/selectors/modelSelectors"; import { incrementNextCodeBlockToApplyIndex, updateApplyState, @@ -29,7 +30,6 @@ import ButtonWithTooltip from "../ButtonWithTooltip"; import FileIcon from "../FileIcon"; import { CopyButton as CopyButtonHeader } from "./CopyButton"; import { ToolbarButtonWithTooltip } from "./ToolbarButtonWithTooltip"; -import { defaultModelSelector } from "../../redux/selectors/modelSelectors"; const ToolbarDiv = styled.div` display: flex; @@ -266,7 +266,10 @@ function CodeBlockToolBar(props: CodeBlockToolBarProps) { onClick={onClickHeader} > - {getBasename(props.filepath)} + + {getBasename(props.filepath)} + {props.range && ` ${props.range}`} +
diff --git a/gui/src/components/markdown/PreWithToolbar.tsx b/gui/src/components/markdown/PreWithToolbar.tsx index f626dfb90..75304f4e5 100644 --- a/gui/src/components/markdown/PreWithToolbar.tsx +++ b/gui/src/components/markdown/PreWithToolbar.tsx @@ -77,6 +77,7 @@ function PreWithToolbar(props: { bottom={toolbarBottom} language={props.language} filepath={props.filepath} + range={props.range} /> ) : ( hovering && ( @@ -85,6 +86,7 @@ function PreWithToolbar(props: { text={copyValue} bottom={toolbarBottom} language={props.language} + range={props.range} /> ) )} From d468853656db4c13d8b281878f29f19e61f8e4be Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 10 Nov 2024 00:43:57 -0800 Subject: [PATCH 96/96] fix config_schema --- extensions/vscode/config_schema.json | 60 ---------------------------- 1 file changed, 60 deletions(-) diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index 605e3f5ad..4dc7eb1a4 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -1729,7 +1729,6 @@ "highlights", "outline", "postgres", - "mssql", "code", "currentFile", "url", @@ -2179,65 +2178,6 @@ } } }, - { - "if": { - "properties": { - "name": { - "enum": ["mssql"] - } - } - }, - "then": { - "properties": { - "params": { - "properties": { - "server": { - "title": "Host", - "description": "Database host", - "default": "localhost", - "type": "string" - }, - "port": { - "title": "Port", - "description": "Database port", - "default": 5432, - "type": "integer" - }, - "user": { - "title": "User", - "description": "Database user", - "default": "postgres", - "type": "string" - }, - "password": { - "title": "Password", - "description": "Database password", - "type": "string" - }, - "database": { - "title": "Database", - "description": "Database name", - "default": "postgres", - "type": "string" - }, - "schema": { - "title": "Schema", - "description": "Database schema", - "default": "public", - "type": "string" - }, - "sampleRows": { - "title": "Sample Rows", - "description": "Number of rows to sample from the database", - "default": 3, - "type": "integer" - } - } - } - }, - "required": ["host", "port", "user", "password", "database"] - } - }, { "if": { "properties": {