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/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts new file mode 100644 index 000000000..cb162043a --- /dev/null +++ b/core/autocomplete/CompletionProvider.ts @@ -0,0 +1,304 @@ +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 { 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"; +import { shouldPrefilter } from "./prefiltering/index.js"; +import { renderPrompt } from "./templating/index.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(); + +// 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 = [ + // From Ollama + "unexpected server status", +]; + +export type GetLspDefinitionsFunction = ( + filepath: string, + contents: string, + cursorIndex: number, + ide: IDE, + lang: AutocompleteLanguageInfo, +) => Promise; + +export class CompletionProvider { + 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, + private readonly ide: IDE, + private readonly _injectedGetLlm: () => Promise, + private readonly _onError: (e: any) => void, + private readonly getDefinitionsFromLsp: GetLspDefinitionsFunction, + ) { + this.completionStreamer = new CompletionStreamer(this.onError.bind(this)); + this.contextRetrievalService = new ContextRetrievalService(this.ide); + } + + private async _prepareLlm(): 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; + } + + 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; + } + + private onError(e: any) { + if ( + ERRORS_TO_IGNORE.some((err) => + typeof e === "string" ? e.includes(err) : e?.message?.includes(err), + ) + ) { + return; + } + + console.warn("Error generating autocompletion: ", e); + if (!this.errorsShown.has(e.message)) { + this.errorsShown.add(e.message); + this._onError(e); + } + } + + public cancel() { + this.loggingService.cancel(); + } + + public accept(completionId: string) { + const outcome = this.loggingService.accept(completionId); + if (!outcome) { + return; + } + this.bracketMatchingService.handleAcceptedCompletion( + outcome.completion, + outcome.filepath, + ); + } + + public markDisplayed(completionId: string, outcome: AutocompleteOutcome) { + this.loggingService.markDisplayed(completionId, outcome); + } + + private async _getAutocompleteOptions() { + const config = await this.configHandler.loadConfig(); + const options = { + ...DEFAULT_AUTOCOMPLETE_OPTS, + ...config.tabAutocompleteOptions, + }; + return options; + } + + public async provideInlineCompletionItems( + input: AutocompleteInput, + token: AbortSignal | undefined, + ): 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 helper = await HelperVars.create( + input, + options, + llm.model, + this.ide, + ); + + if (await shouldPrefilter(helper, this.ide)) { + return undefined; + } + + // Create abort signal if not given + if (!token) { + const controller = this.loggingService.createAbortController( + input.completionId, + ); + token = controller.signal; + } + + ////////// + + // 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); + + let snippets = await constructAutocompletePrompt( + helper, + extraSnippets, + this.contextRetrievalService, + ); + + const { prompt, prefix, suffix, 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(helper.prunedPrefix) + : undefined; + let cacheHit = false; + if (cachedCompletion) { + // Cache + cacheHit = true; + completion = cachedCompletion; + } else { + const multiline = + !helper.options.transform || shouldCompleteMultiline(helper); + + 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: helper.prunedPrefix, + suffix: helper.prunedSuffix, + 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 () => { + if (!outcome.cacheHit) { + (await this.autocompleteCache).put(outcome.prefix, completionToCache); + } + }, 100); + + return outcome; + } catch (e: any) { + this.onError(e); + } finally { + this.loggingService.deleteAbortController(input.completionId); + } + } + + private async _getExtraSnippets( + helper: HelperVars, + ): Promise { + let extraSnippets = helper.options.useOtherFiles + ? ((await Promise.race([ + this.getDefinitionsFromLsp( + helper.input.filepath, + helper.fullPrefix + helper.fullSuffix, + helper.fullPrefix.length, + this.ide, + helper.lang, + ), + new Promise((resolve) => { + setTimeout(() => resolve([]), 100); + }), + ])) as AutocompleteSnippet[]) + : []; + + const workspaceDirs = await this.ide.getWorkspaceDirs(); + if (helper.options.onlyMyCode) { + extraSnippets = extraSnippets.filter((snippet) => { + return workspaceDirs.some((dir) => snippet.filepath.startsWith(dir)); + }); + } + + return extraSnippets; + } +} 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/READEME.md b/core/autocomplete/READEME.md new file mode 100644 index 000000000..d5e822273 --- /dev/null +++ b/core/autocomplete/READEME.md @@ -0,0 +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/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/classification/shouldCompleteMultiline.ts b/core/autocomplete/classification/shouldCompleteMultiline.ts new file mode 100644 index 000000000..75cfdcd70 --- /dev/null +++ b/core/autocomplete/classification/shouldCompleteMultiline.ts @@ -0,0 +1,53 @@ +import { AutocompleteLanguageInfo } from "../constants/AutocompleteLanguageInfo"; +import { HelperVars } from "../util/HelperVars"; + +function isMidlineCompletion(prefix: string, suffix: string): boolean { + return !suffix.startsWith("\n"); +} + +function shouldCompleteMultilineBasedOnLanguage( + language: AutocompleteLanguageInfo, + prefix: string, + suffix: string, +) { + return language.useMultiline?.({ prefix, suffix }) ?? true; +} + +export function shouldCompleteMultiline(helper: HelperVars) { + switch (helper.options.multilineCompletions) { + case "always": + return true; + case "never": + return false; + default: + 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; + // } + + // Don't complete multi-line for single-line comments + if ( + helper.lang.singleLineComment && + helper.fullPrefix + .split("\n") + .slice(-1)[0] + ?.trimStart() + .startsWith(helper.lang.singleLineComment) + ) { + return false; + } + + return shouldCompleteMultilineBasedOnLanguage( + helper.lang, + helper.prunedPrefix, + helper.prunedSuffix, + ); +} diff --git a/core/autocomplete/completionProvider.ts b/core/autocomplete/completionProvider.ts deleted file mode 100644 index 4fae89003..000000000 --- a/core/autocomplete/completionProvider.ts +++ /dev/null @@ -1,811 +0,0 @@ -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 { logDevData } from "../util/devdata.js"; -import { getBasename, getLastNPathParts } from "../util/index.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 AutocompleteLruCache from "./cache.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 { - avoidPathLineAndEmptyComments, - skipPrefixes, - stopAtLines, - 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 { 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; -} - -const autocompleteCache = AutocompleteLruCache.get(); - -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]; - -// 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 = [ - // From Ollama - "unexpected server status", -]; - -const LOCAL_PROVIDERS: ModelProvider[] = [ - "ollama", - "lmstudio", - "llama.cpp", - "llamafile", - "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, - cursorIndex: number, - ide: IDE, - lang: AutocompleteLanguageInfo, -) => Promise; - -export class CompletionProvider { - private static debounceTimeout: NodeJS.Timeout | undefined = undefined; - private static debouncing = false; - private static lastUUID: string | undefined = undefined; - - constructor( - private readonly configHandler: ConfigHandler, - private readonly ide: IDE, - private readonly getLlm: () => Promise, - private readonly _onError: (e: any) => void, - private readonly getDefinitionsFromLsp: GetLspDefinitionsFunction, - ) { - this.generatorReuseManager = new GeneratorReuseManager( - this.onError.bind(this), - ); - this.importDefinitionsService = new ImportDefinitionsService(this.ide); - this.rootPathContextService = new RootPathContextService( - this.importDefinitionsService, - this.ide, - ); - } - - private importDefinitionsService: ImportDefinitionsService; - private rootPathContextService: RootPathContextService; - private generatorReuseManager: GeneratorReuseManager; - private autocompleteCache = AutocompleteLruCache.get(); - public errorsShown: Set = new Set(); - private bracketMatchingService = new BracketMatchingService(); - // private nearbyDefinitionsService = new NearbyDefinitionsService(); - - 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), - ) - ) { - return; - } - if (!this.errorsShown.has(e.message)) { - this.errorsShown.add(e.message); - this._onError(e); - } - } - - public cancel() { - this._abortControllers.forEach((abortController, id) => { - abortController.abort(); - }); - this._abortControllers.clear(); - } - - // 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); - } - - 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._outcomes.delete(completionId); - - 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 async provideInlineCompletionItems( - input: AutocompleteInput, - token: AbortSignal | undefined, - ): Promise { - try { - // Debounce - const uuid = uuidv4(); - CompletionProvider.lastUUID = uuid; - - const config = await this.configHandler.loadConfig(); - const options = { - ...DEFAULT_AUTOCOMPLETE_OPTS, - ...config.tabAutocompleteOptions, - }; - - // 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 (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; - } - } - - // Create abort signal if not given - if (!token) { - const controller = new AbortController(); - token = controller.signal; - this._abortControllers.set(input.completionId, controller); - } - - // Allow disabling autocomplete from config.json - if (options.disable) { - return undefined; - } - - // 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); - } - - // 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 overrride) - 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) { - 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 () => { - if (!outcome.cacheHit) { - (await this.autocompleteCache).put(outcome.prefix, completionToCache); - } - }, 100); - - return outcome; - } catch (e: any) { - this.onError(e); - } finally { - this._abortControllers.delete(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; - 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._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 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, - 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); - - 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, { - 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 }, - }); - - // 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( - filepath, - fullPrefix + fullSuffix, - fullPrefix.length, - this.ide, - lang, - ), - new Promise((resolve) => { - setTimeout(() => resolve([]), 100); - }), - ])) as AutocompleteSnippet[]) - : []; - - const workspaceDirs = await this.ide.getWorkspaceDirs(); - if (options.onlyMyCode) { - extrasSnippets = extrasSnippets.filter((snippet) => { - return workspaceDirs.some((dir) => snippet.filepath.startsWith(dir)); - }); - } - - let { prefix, suffix, completeMultiline, snippets } = - await constructAutocompletePrompt( - filepath, - pos.line, - fullPrefix, - fullSuffix, - clipboardText, - lang, - options, - recentlyEditedRanges, - recentlyEditedFiles, - llm.model, - extrasSnippets, - this.importDefinitionsService, - this.rootPathContextService, - ); - - // If prefix is manually passed - if (manuallyPassPrefix) { - prefix = manuallyPassPrefix; - 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, - ); - } - - // Completion - let completion = ""; - - const cache = await autocompleteCache; - const cachedCompletion = options.useCache - ? await cache.get(prefix) - : undefined; - let cacheHit = false; - if (cachedCompletion) { - // Cache - cacheHit = true; - completion = cachedCompletion; - } else { - const stop = [ - ...(completionOptions?.stop || []), - // ...multilineStops, - ...commonStops, - ...(llm.model.toLowerCase().includes("starcoder2") - ? STARCODER2_T_ARTIFACTS - : []), - ...(lang.stopWords ?? []), - // ...lang.topLevelKeywords.map((word) => `\n${word}`), - ]; - - const multiline = - !options.transform || - this.isMultiline({ - 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, - }) - : llm.streamComplete(prompt, { - ...completionOptions, - raw: true, - stop, - }), - 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; - } - }; - let charGenerator = generatorWithCancellation(); - - if (options.transform) { - // charGenerator = noFirstCharNewline(charGenerator); - // charGenerator = onlyWhitespaceAfterEndOfLine( - // charGenerator, - // lang.endOfLine, - // fullStop, - // ); - charGenerator = stopAtStopTokens(charGenerator, stop); - charGenerator = - this.bracketMatchingService.stopOnUnmatchedClosingBracket( - charGenerator, - 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); - - 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 = options.transform - ? postprocessCompletion({ - completion, - prefix, - suffix, - llm, - }) - : completion; - - if (!processedCompletion) { - return undefined; - } - completion = processedCompletion; - } - - const time = Date.now() - startTime; - return { - time, - completion, - prefix, - suffix, - prompt, - modelProvider: llm.providerName, - modelName: llm.model, - completionOptions, - cacheHit, - filepath: input.filepath, - completionId: input.completionId, - gitRepo: await this.ide.getRepoName(input.filepath), - uniqueId: await this.ide.getUniqueId(), - ...options, - }; - } -} diff --git a/core/autocomplete/languages.ts b/core/autocomplete/constants/AutocompleteLanguageInfo.ts similarity index 85% rename from core/autocomplete/languages.ts rename to core/autocomplete/constants/AutocompleteLanguageInfo.ts index be414098a..18bbf2ff9 100644 --- a/core/autocomplete/languages.ts +++ b/core/autocomplete/constants/AutocompleteLanguageInfo.ts @@ -1,16 +1,18 @@ -import { LineFilter } from "./streamTransforms/lineStream"; +import { BracketMatchingService } from "../filtering/BracketMatchingService"; +import { + CharacterFilter, + 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; + charFilters?: CharacterFilter[]; + useMultiline?: (args: { prefix: string; suffix: string }) => boolean; } // TypeScript @@ -256,10 +258,8 @@ export const YAML: AutocompleteLanguageInfo = { } else { seenListItem = true; } - yield line; - } else { - yield line; } + yield line; } }, // Don't allow consecutive lines of same key @@ -268,18 +268,39 @@ 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; } } }, ], }; +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: [], @@ -289,7 +310,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 +322,7 @@ export const Markdown: AutocompleteLanguageInfo = { return false; } } - return undefined; + return true; }, }; @@ -309,6 +330,7 @@ export const LANGUAGES: { [extension: string]: AutocompleteLanguageInfo } = { ts: Typescript, js: Typescript, tsx: Typescript, + json: Json, jsx: Typescript, ipynb: Python, py: Python, @@ -346,3 +368,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 17b78fa01..2c5d43f42 100644 --- a/core/autocomplete/constructPrompt.ts +++ b/core/autocomplete/constructPrompt.ts @@ -1,215 +1,87 @@ -import { RangeInFileWithContents } from "../commands/util.js"; -import { TabAutocompleteOptions } from "../index.js"; - -import { - countTokens, - pruneLinesFromBottom, - pruneLinesFromTop, -} from "../llm/countTokens.js"; -import { AstPath, getAst, getTreePathAtCursor } from "./ast.js"; -import { - AutocompleteLanguageInfo, - LANGUAGES, - Typescript, -} from "./languages.js"; +import { Position, Range } from "../index.js"; +import { ContextRetrievalService } from "./context/ContextRetrievalService.js"; import { fillPromptWithSnippets, - getSymbolsForSnippet, - rankSnippets, + rankAndOrderSnippets, removeRangeFromSnippets, type AutocompleteSnippet, -} from "./ranking.js"; -import { RecentlyEditedRange, findMatchingRange } from "./recentlyEdited.js"; -import { ImportDefinitionsService } from "./services/ImportDefinitionsService.js"; -import { RootPathContextService } from "./services/RootPathContextService.js"; -import { shouldCompleteMultiline } from "./shouldCompleteMultiline.js"; +} from "./context/ranking/index.js"; +import { HelperVars } from "./util/HelperVars.js"; -export function languageForFilepath( - filepath: string, -): AutocompleteLanguageInfo { - return LANGUAGES[filepath.split(".").slice(-1)[0]] || Typescript; +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( - 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, -): Promise<{ - prefix: string; - suffix: string; - useFim: boolean; - completeMultiline: boolean; - snippets: AutocompleteSnippet[]; -}> { - // Construct basic prefix - const maxPrefixTokens = options.maxPromptTokens * options.prefixPercentage; - const prefix = pruneLinesFromTop(fullPrefix, maxPrefixTokens, modelName); - - // Construct suffix - const maxSuffixTokens = Math.min( - options.maxPromptTokens - countTokens(prefix, modelName), - options.maxSuffixPercentage * options.maxPromptTokens, + contextRetrievalService: ContextRetrievalService, +): Promise { + let snippets = await contextRetrievalService.retrieveCandidateSnippets( + helper, + extraSnippets, ); - const suffix = pruneLinesFromBottom(fullSuffix, maxSuffixTokens, modelName); - // Calculate AST Path - let treePath: AstPath | undefined; - try { - const ast = await getAst(filepath, fullPrefix + fullSuffix); - if (ast) { - treePath = await getTreePathAtCursor(ast, fullPrefix.length); - } - } catch (e) { - console.error("Failed to parse AST", e); - } - - // Find external snippets - let snippets: AutocompleteSnippet[] = []; - - if (options.useOtherFiles) { - snippets.push(...extraSnippets); - - const windowAroundCursor = - fullPrefix.slice( - -options.slidingWindowSize * options.slidingWindowPrefixPercentage, - ) + - fullSuffix.slice( - options.slidingWindowSize * (1 - 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 (options.useRecentlyEdited) { - const currentLinePrefix = prefix.trim().split("\n").slice(-1)[0]; - if (currentLinePrefix?.length > options.recentLinePrefixMatchMinLength) { - const matchingRange = findMatchingRange( - recentlyEditedRanges, - currentLinePrefix, - ); - if (matchingRange) { - snippets.push({ - ...matchingRange, - contents: matchingRange.lines.join("\n"), - score: 0.8, - }); - } - } - } - - // Use imports - if (options.useImports) { - const importSnippets = []; - const fileInfo = importDefinitionsService.get(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) => !language.topLevelKeywords.includes(symbol)); - for (const symbol of symbols) { - const rifs = imports[symbol]; - if (Array.isArray(rifs)) { - importSnippets.push(...rifs); - } - } - } - snippets.push(...importSnippets); - } - - if (options.useRootPathContext && treePath) { - const ctx = await rootPathContextService.getContextForPath( - filepath, - treePath, - ); - snippets.push(...ctx); - } - - // Filter out empty snippets and ones that are already in the prefix/suffix - snippets = snippets - .map((snippet) => ({ ...snippet })) - .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 = - options.maxPromptTokens * 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: cursorLine - prefixLines - buffer, - character: 0, - }, - end: { - line: cursorLine + suffixLines + buffer, - character: 0, - }, - }; - let finalSnippets = removeRangeFromSnippets( - scoredSnippets, - 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, - ); - finalSnippets = fillPromptWithSnippets( - scoredSnippets, - maxSnippetTokens, - modelName, - ); - - snippets = finalSnippets; - } - - return { - prefix, - suffix, - useFim: true, - completeMultiline: await shouldCompleteMultiline( - treePath, - fullPrefix, - fullSuffix, - language, - ), + snippets = filterSnippetsAlreadyInCaretWindow( snippets, - }; + helper.prunedCaretWindow, + ); + + const scoredSnippets = rankAndOrderSnippets(snippets, helper); + + // This might be redundant with filterSnippetsAlreadyInCaretWindow + let finalSnippets = removeRangeFromSnippets( + scoredSnippets, + helper.filepath.split("://").slice(-1)[0], + getRangeOfPrefixAndSuffixWithBuffer( + helper.prunedPrefix, + helper.prunedSuffix, + helper.pos, + ), + ); + + // Filter snippets below similarity threshold + finalSnippets = finalSnippets.filter( + (snippet) => + snippet.score >= helper.options.recentlyEditedSimilarityThreshold, + ); + + finalSnippets = fillPromptWithSnippets( + scoredSnippets, + helper.maxSnippetTokens, + helper.modelName, + ); + + return finalSnippets; } diff --git a/core/autocomplete/context/ContextRetrievalService.ts b/core/autocomplete/context/ContextRetrievalService.ts new file mode 100644 index 000000000..a12d1962e --- /dev/null +++ b/core/autocomplete/context/ContextRetrievalService.ts @@ -0,0 +1,123 @@ +import { IDE } from "../.."; +import { HelperVars } from "../util/HelperVars"; +import { RecentlyEditedRange } from "../util/types"; +import { ImportDefinitionsService } from "./ImportDefinitionsService"; +import { AutocompleteSnippet, getSymbolsForSnippet } from "./ranking"; +import { RootPathContextService } from "./root-path-context/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 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( + helper: HelperVars, + ): AutocompleteSnippet[] { + if (helper.options.useRecentlyEdited === false) { + return []; + } + + const currentLinePrefix = helper.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; + } + + findMatchingRange( + recentlyEditedRanges: RecentlyEditedRange[], + linePrefix: string, + ): RecentlyEditedRange | undefined { + return recentlyEditedRanges.find((recentlyEditedRange) => { + return recentlyEditedRange.lines.some((line) => + line.startsWith(linePrefix), + ); + }); + } +} 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/ranking.ts b/core/autocomplete/context/ranking/index.ts similarity index 89% rename from core/autocomplete/ranking.ts rename to core/autocomplete/context/ranking/index.ts index 48e01d5ff..e761d994e 100644 --- a/core/autocomplete/ranking.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 { RangeInFileWithContents } from "../../../commands/util.js"; +import { Range } from "../../../index.js"; +import { countTokens } from "../../../llm/countTokens.js"; +import { HelperVars } from "../../util/HelperVars.js"; export type AutocompleteSnippet = RangeInFileWithContents & { score?: number; @@ -41,10 +42,20 @@ 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[], - 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), @@ -119,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/slidingWindow.ts b/core/autocomplete/context/ranking/slidingWindow.ts similarity index 91% rename from core/autocomplete/slidingWindow.ts rename to core/autocomplete/context/ranking/slidingWindow.ts index 72aa1a5ee..54ec763f2 100644 --- a/core/autocomplete/slidingWindow.ts +++ b/core/autocomplete/context/ranking/slidingWindow.ts @@ -1,5 +1,5 @@ -import { RangeInFileWithContents } from "../commands/util.js"; -import { AutocompleteSnippet, jaccardSimilarity } from "./ranking.js"; +import { RangeInFileWithContents } from "../../../commands/util.js"; +import { AutocompleteSnippet, jaccardSimilarity } from "./index.js"; function* slidingWindow( content: string, 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..ccce0b6ac --- /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, prefix.length); + 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/services/RootPathContextService.ts b/core/autocomplete/context/root-path-context/RootPathContextService.ts similarity index 93% rename from core/autocomplete/services/RootPathContextService.ts rename to core/autocomplete/context/root-path-context/RootPathContextService.ts index 69426aab8..ba99b2e83 100644 --- a/core/autocomplete/services/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 "../ast"; +import { IDE } from "../../.."; +import { getQueryForFile, TSQueryType } from "../../../util/treeSitter"; +import { AstPath } from "../../util/ast"; +import { ImportDefinitionsService } from "../ImportDefinitionsService"; import { AutocompleteSnippet } from "../ranking"; -import { ImportDefinitionsService } from "./ImportDefinitionsService"; 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; +} diff --git a/core/autocomplete/filter.ts b/core/autocomplete/filter.ts deleted file mode 100644 index 5b2b66df0..000000000 --- a/core/autocomplete/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/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/filtering/streamTransforms/StreamTransformPipeline.ts b/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts new file mode 100644 index 000000000..8d7f3e23f --- /dev/null +++ b/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts @@ -0,0 +1,87 @@ +import { streamLines } from "../../../diff/util"; +import { DEFAULT_AUTOCOMPLETE_OPTS } from "../../../util/parameters"; +import { HelperVars } from "../../util/HelperVars"; +import { stopAtStopTokens } from "./charStream"; +import { + avoidEmptyComments, + avoidPathLine, + showWhateverWeHaveAtXMs, + skipPrefixes, + stopAtLines, + stopAtRepeatingLines, + stopAtSimilarLine, + streamWithNewLines, +} from "./lineStream"; + +export class StreamTransformPipeline { + async *transform( + generator: AsyncGenerator, + prefix: string, + suffix: string, + multiline: boolean, + stopTokens: string[], + fullStop: () => void, + helper: HelperVars, + ): AsyncGenerator { + let charGenerator = generator; + + charGenerator = stopAtStopTokens(generator, stopTokens); + for (const charFilter of helper.lang.charFilters ?? []) { + charGenerator = charFilter({ + chars: charGenerator, + prefix, + suffix, + filepath: helper.filepath, + multiline, + }); + } + + let lineGenerator = streamLines(charGenerator); + + 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, + helper.options.showWhateverWeHaveAtXMs ?? + (DEFAULT_AUTOCOMPLETE_OPTS.showWhateverWeHaveAtXMs as number), + ); + + const finalGenerator = streamWithNewLines(lineGenerator); + for await (const update of finalGenerator) { + yield update; + } + } + + private getLineBelowCursor(helper: HelperVars): string { + let lineBelowCursor = ""; + let i = 1; + while ( + lineBelowCursor.trim() === "" && + helper.pos.line + i <= helper.fileLines.length - 1 + ) { + lineBelowCursor = + helper.fileLines[ + Math.min(helper.pos.line + i, helper.fileLines.length - 1) + ]; + i++; + } + return lineBelowCursor; + } +} diff --git a/core/autocomplete/charStream.test.ts b/core/autocomplete/filtering/streamTransforms/charStream.test.ts similarity index 98% rename from core/autocomplete/charStream.test.ts rename to core/autocomplete/filtering/streamTransforms/charStream.test.ts index b5504ad63..7ab8923fc 100644 --- a/core/autocomplete/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/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 94% rename from core/autocomplete/lineStream.test.ts rename to core/autocomplete/filtering/streamTransforms/lineStream.test.ts index ace94eaa4..810ab9eec 100644 --- a/core/autocomplete/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; @@ -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/streamTransforms/lineStream.ts b/core/autocomplete/filtering/streamTransforms/lineStream.ts similarity index 89% rename from core/autocomplete/streamTransforms/lineStream.ts rename to core/autocomplete/filtering/streamTransforms/lineStream.ts index 5990bbf3c..0f49cea55 100644 --- a/core/autocomplete/streamTransforms/lineStream.ts +++ b/core/autocomplete/filtering/streamTransforms/lineStream.ts @@ -1,12 +1,20 @@ 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; 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() @@ -14,14 +22,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(); @@ -122,27 +122,45 @@ 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, + 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 (!comment || line.trim() !== comment) { + yield line; + } + } +} + /** * Transforms a LineStream by adding newline characters between lines. * @@ -168,9 +186,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 { @@ -180,10 +196,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; } /** @@ -210,9 +223,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()) { @@ -220,6 +233,11 @@ export async function* stopAtSimilarLine( continue; } + if (nextLine === line) { + fullStop(); + break; + } + if (lineIsRepeated(nextLine, trimmedLine)) { fullStop(); break; @@ -510,3 +528,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/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/filter.test.ts b/core/autocomplete/filtering/test/filter.test.ts new file mode 100644 index 000000000..62ef65512 --- /dev/null +++ b/core/autocomplete/filtering/test/filter.test.ts @@ -0,0 +1,49 @@ +import { + AutocompleteFileringTestInput, + testAutocompleteFiltering, +} from "./util"; +import { TEST_CASES_WITH_DIFF, TEST_CASES_WITHOUT_DIFF } from "./testCases"; +import { setUpTestDir, tearDownTestDir } from "../../../test/util/testDir"; + +const filterTestCases = (tests: AutocompleteFileringTestInput[]) => { + if (tests.some((test) => test.options?.only)) { + return tests.filter((test) => test.options?.only); + } + + return tests; +}; + +describe("llms/Mock", () => { + beforeAll(async () => { + tearDownTestDir(); + setUpTestDir(); + }); + + afterAll(async () => { + tearDownTestDir(); + }); + + describe("Autocomplete Filtering Tests", () => { + beforeEach(async () => { + await new Promise((resolve) => setTimeout(resolve, 50)); + }); + + describe("Should return unmodified LLM output", () => { + it.each(filterTestCases(TEST_CASES_WITHOUT_DIFF))( + "$description", + async (testCase) => { + await testAutocompleteFiltering(testCase); + }, + ); + }); + + describe("Should return modified LLM output", () => { + it.each(filterTestCases(TEST_CASES_WITH_DIFF))( + "$description", + async (testCase) => { + await testAutocompleteFiltering(testCase); + }, + ); + }); + }); +}); diff --git a/core/autocomplete/test/testCases.ts b/core/autocomplete/filtering/test/testCases.ts similarity index 93% rename from core/autocomplete/test/testCases.ts rename to core/autocomplete/filtering/test/testCases.ts index 2deeec9de..683dbc7bc 100644 --- a/core/autocomplete/test/testCases.ts +++ b/core/autocomplete/filtering/test/testCases.ts @@ -1,7 +1,243 @@ -import { dedent } from "../../util"; +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`, + }, + { + 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[] = [ { description: "should pass", filename: "test.js", @@ -412,32 +648,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 +721,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 +733,49 @@ 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", + 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 +877,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 +906,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 +918,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", @@ -801,40 +931,6 @@ function sayHello() { 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", @@ -986,28 +1082,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 +1827,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/test/util.ts b/core/autocomplete/filtering/test/util.ts similarity index 88% rename from core/autocomplete/test/util.ts rename to core/autocomplete/filtering/test/util.ts index 60e7b3f93..5a9b61a72 100644 --- a/core/autocomplete/test/util.ts +++ b/core/autocomplete/filtering/test/util.ts @@ -1,8 +1,9 @@ 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 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|>"; diff --git a/core/autocomplete/generation/CompletionStreamer.ts b/core/autocomplete/generation/CompletionStreamer.ts new file mode 100644 index 000000000..3f46f5033 --- /dev/null +++ b/core/autocomplete/generation/CompletionStreamer.ts @@ -0,0 +1,68 @@ +import { CompletionOptions, ILLM } from "../.."; +import { StreamTransformPipeline } from "../filtering/streamTransforms/StreamTransformPipeline"; +import { HelperVars } from "../util/HelperVars"; +import { GeneratorReuseManager } from "./GeneratorReuseManager"; + +export class CompletionStreamer { + private streamTransformPipeline = new StreamTransformPipeline(); + private generatorReuseManager: GeneratorReuseManager; + + constructor(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 transformedGenerator = helper.options.transform + ? this.streamTransformPipeline.transform( + initialGenerator, + prefix, + suffix, + multiline, + completionOptions?.stop || [], + fullStop, + helper, + ) + : initialGenerator; + + for await (const update of transformedGenerator) { + yield update; + } + } +} 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 71% rename from core/autocomplete/postprocessing.ts rename to core/autocomplete/postprocessing/index.ts index cb3ada459..127874d68 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 @@ -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; } @@ -69,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] !== " ") { @@ -81,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 new file mode 100644 index 000000000..a7343817d --- /dev/null +++ b/core/autocomplete/prefiltering/index.ts @@ -0,0 +1,78 @@ +import path from "node:path"; +import { IDE } from "../.."; +import { getBasename } from "../../util"; +import { getConfigJsonPath } from "../../util/paths"; +import { HelperVars } from "../util/HelperVars"; + +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(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( + helper: HelperVars, + ide: IDE, +): Promise { + // Allow disabling autocomplete from config.json + if (helper.options.disable) { + return true; + } + + // Check whether we're in the continue config.json file + if (helper.filepath === getConfigJsonPath()) { + return true; + } + + // Check whether autocomplete is disabled for this file + if ( + await isDisabledForFile(helper.filepath, helper.options.disableInFiles, ide) + ) { + return true; + } + + // if ( + // helper.options.transform && + // (await shouldLanguageSpecificPrefilter(helper)) + // ) { + // return true; + // } + + return false; +} 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/retrieval.ts b/core/autocomplete/retrieval.ts deleted file mode 100644 index 422b377bd..000000000 --- a/core/autocomplete/retrieval.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { BranchAndDir, Chunk } from "../index.js"; -import { FullTextSearchCodebaseIndex } from "../indexing/FullTextSearchCodebaseIndex.js"; - -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/shouldCompleteMultiline.ts b/core/autocomplete/shouldCompleteMultiline.ts deleted file mode 100644 index af244992e..000000000 --- a/core/autocomplete/shouldCompleteMultiline.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { AstPath } from "./ast"; -import { AutocompleteLanguageInfo } from "./languages"; - -const BLOCK_TYPES = ["body", "statement_block"]; - -function isMidlineCompletion(prefix: string, suffix: string): boolean { - return !suffix.startsWith("\n"); -} - -export async function shouldCompleteMultiline( - treePath: AstPath | undefined, - fullPrefix: string, - fullSuffix: string, - language: AutocompleteLanguageInfo, -): Promise { - // Don't complete multi-line if you are mid-line - if (isMidlineCompletion(fullPrefix, fullSuffix)) { - return false; - } - - // Don't complete multi-line for single-line comments - if ( - fullPrefix - .split("\n") - .slice(-1)[0] - ?.trimStart() - .startsWith(language.singleLineComment) - ) { - return false; - } - - return true; -} diff --git a/core/autocomplete/templates.ts b/core/autocomplete/templating/AutocompleteTemplate.ts similarity index 97% rename from core/autocomplete/templates.ts rename to core/autocomplete/templating/AutocompleteTemplate.ts index cda8b8a2d..ae8cf1487 100644 --- a/core/autocomplete/templates.ts +++ b/core/autocomplete/templating/AutocompleteTemplate.ts @@ -1,10 +1,10 @@ // 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 { +export interface AutocompleteTemplate { compilePrefixSuffix?: ( prefix: string, suffix: string, diff --git a/core/autocomplete/templating/constructPrefixSuffix.ts b/core/autocomplete/templating/constructPrefixSuffix.ts new file mode 100644 index 000000000..d4024bf06 --- /dev/null +++ b/core/autocomplete/templating/constructPrefixSuffix.ts @@ -0,0 +1,44 @@ +import { IDE } from "../.."; +import { getRangeInString } from "../../util/ranges"; +import { languageForFilepath } from "../constants/AutocompleteLanguageInfo"; + +import { AutocompleteInput } from "../util/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/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 new file mode 100644 index 000000000..05a10bbed --- /dev/null +++ b/core/autocomplete/templating/index.ts @@ -0,0 +1,149 @@ +import Handlebars from "handlebars"; +import { CompletionOptions } from "../.."; +import { getBasename, getLastNPathParts } from "../../util"; +import { AutocompleteLanguageInfo } from "../constants/AutocompleteLanguageInfo"; +import { AutocompleteSnippet } from "../context/ranking"; +import { HelperVars } from "../util/HelperVars"; +import { + AutocompleteTemplate, + getTemplateForModel, +} from "./AutocompleteTemplate"; +import { getStopTokens } from "./getStopTokens"; + +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"); +} +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; +} + +function getTemplate(helper: HelperVars): AutocompleteTemplate { + if (helper.options.template) { + return { + template: helper.options.template, + completionOptions: {}, + compilePrefixSuffix: undefined, + }; + } + return getTemplateForModel(helper.modelName); +} + +export function renderPrompt( + snippets: AutocompleteSnippet[], + workspaceDirs: string[], + helper: HelperVars, +): { + 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) { + [prefix, suffix] = compilePrefixSuffix( + prefix, + suffix, + helper.filepath, + reponame, + snippets, + ); + } + + // Templates can be passed as a Handlebars template string or a function + if (typeof template === "string") { + prompt = renderStringTemplate( + template, + prefix, + suffix, + snippets, + helper.lang, + helper.filepath, + reponame, + ); + } else { + prompt = template( + prefix, + suffix, + helper.filepath, + reponame, + helper.lang.name, + snippets, + ); + } + + const stopTokens = getStopTokens( + completionOptions, + helper.lang, + helper.modelName, + ); + + completionOptions = { + ...completionOptions, + stop: stopTokens, + }; + + return { prompt, prefix, suffix, completionOptions }; +} 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/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/util/AutocompleteDebouncer.ts b/core/autocomplete/util/AutocompleteDebouncer.ts new file mode 100644 index 000000000..f8bcc474f --- /dev/null +++ b/core/autocomplete/util/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/util/AutocompleteLoggingService.ts b/core/autocomplete/util/AutocompleteLoggingService.ts new file mode 100644 index 000000000..7fd3d24cb --- /dev/null +++ b/core/autocomplete/util/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/cache.ts b/core/autocomplete/util/AutocompleteLruCache.ts similarity index 92% rename from core/autocomplete/cache.ts rename to core/autocomplete/util/AutocompleteLruCache.ts index c04770a4c..ec9478c8a 100644 --- a/core/autocomplete/cache.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/util/HelperVars.ts b/core/autocomplete/util/HelperVars.ts new file mode 100644 index 000000000..a6ecb21a9 --- /dev/null +++ b/core/autocomplete/util/HelperVars.ts @@ -0,0 +1,175 @@ +import { IDE, TabAutocompleteOptions } from "../.."; +import { + countTokens, + pruneLinesFromBottom, + pruneLinesFromTop, +} from "../../llm/countTokens"; +import { + AutocompleteLanguageInfo, + languageForFilepath, +} from "../constants/AutocompleteLanguageInfo"; +import { constructInitialPrefixSuffix } from "../templating/constructPrefixSuffix"; +import { AstPath, getAst, getTreePathAtCursor } from "./ast"; +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; + treePath: AstPath | undefined; + + 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, + public readonly options: TabAutocompleteOptions, + public readonly modelName: string, + private readonly ide: IDE, + ) { + this.lang = languageForFilepath(input.filepath); + } + + private 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"); + + // 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; + + const { prunedPrefix, prunedSuffix } = this.prunePrefixSuffix(); + this._prunedPrefix = prunedPrefix; + this._prunedSuffix = prunedSuffix; + + 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( + input: AutocompleteInput, + options: TabAutocompleteOptions, + modelName: string, + ide: IDE, + ): Promise { + const instance = new HelperVars(input, options, modelName, ide); + await instance.init(); + 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; + } + get pos() { + return this.input.pos; + } + get maxSnippetTokens() { + return this.options.maxPromptTokens * this.options.maxSnippetPercentage; + } + get prunedCaretWindow() { + return this.prunedPrefix + this.prunedSuffix; + } + + // 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; + } + + 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; + } + + 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; + } +} 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/autocomplete/util/types.ts b/core/autocomplete/util/types.ts new file mode 100644 index 000000000..44ee9fab1 --- /dev/null +++ b/core/autocomplete/util/types.ts @@ -0,0 +1,43 @@ +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; + 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/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/commands/slash/index.ts b/core/commands/slash/index.ts index 18008e251..544673901 100644 --- a/core/commands/slash/index.ts +++ b/core/commands/slash/index.ts @@ -2,6 +2,7 @@ import GenerateTerminalCommand from "./cmd"; import CommitMessageCommand from "./commit"; import DraftIssueCommand from "./draftIssue"; import HttpSlashCommand from "./http"; +import MultiFileEditSlashCommand from "./multifileEdit"; import OnboardSlashCommand from "./onboard"; import ReviewMessageCommand from "./review"; import ShareSlashCommand from "./share"; @@ -14,4 +15,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..ffda6b703 --- /dev/null +++ b/core/commands/slash/multifileEdit.ts @@ -0,0 +1,108 @@ +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 = { + name: "multifile-edit", + description: "Edit multiple files in the codebase at once", + 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(ide as VsCodeIde, filepath); + + 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); + } + }, +}; + +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: + +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 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. + `; +} + +export default MultiFileEditSlashCommand; 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/config/promptFile.ts b/core/config/promptFile.ts index 1cee2875f..44646ec95 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/v1/renderTemplatedString"; import { getBasename } from "../util/index"; +import { BaseContextProvider } from "../context"; export const DEFAULT_PROMPTS_FOLDER = ".prompts"; @@ -147,28 +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 currentFilePath = await context.ide.getCurrentFile(); - const currentFile = currentFilePath - ? await context.ide.readFile(currentFilePath) - : undefined; + 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, 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, { @@ -182,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: { @@ -202,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 ca8ee9bec..3fb9fe494 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]>; @@ -538,6 +542,7 @@ declare global { | "folder" | "jira" | "postgres" + | "mssql" | "database" | "code" | "docs" @@ -730,6 +735,7 @@ declare global { stop?: string[]; maxTokens?: number; numThreads?: number; + useMmap?: boolean; keepAlive?: number; raw?: boolean; stream?: boolean; 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/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/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/core.ts b/core/core.ts index dcf27f6eb..87eeb52da 100644 --- a/core/core.ts +++ b/core/core.ts @@ -1,6 +1,8 @@ +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"; +import { CompletionProvider } from "./autocomplete/CompletionProvider"; import { ConfigHandler } from "./config/ConfigHandler"; import { setupBestConfig, @@ -16,6 +18,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 { createNewPromptFileV2 } from "./promptFiles/v2/createNewPromptFile"; import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; @@ -77,7 +80,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 () => { }, ) { // Ensure .continue directory is created setupInitialDotContinueDirectory(); @@ -168,7 +171,7 @@ export class Core { this.configHandler, ide, getLlm, - (e) => {}, + (e) => { }, (..._) => Promise.resolve([]), ); @@ -398,6 +401,7 @@ export class Core { }); break; } + // @ts-ignore yield { content: next.value.content }; next = await gen.next(); } @@ -677,7 +681,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) => { @@ -704,8 +708,13 @@ export class Core { return { url }; }); - on("didChangeActiveTextEditor", ({ data: { filepath } }) => { - recentlyEditedFilesCache.set(filepath, filepath); + on("didChangeActiveTextEditor", async ({ data: { filepath } }) => { + 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); + } }); } 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/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..ca47f010d 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, 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/core/index.d.ts b/core/index.d.ts index 5b0b892f6..ac8ea5376 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; @@ -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]>; @@ -780,6 +784,14 @@ export interface CustomCommand { description: string; } +interface Prediction { + type: "content" + content: string | { + type: "text" + text: string + }[] +} + interface BaseCompletionOptions { temperature?: number; topP?: number; @@ -791,9 +803,11 @@ interface BaseCompletionOptions { stop?: string[]; maxTokens?: number; numThreads?: number; + useMmap?: boolean; keepAlive?: number; raw?: boolean; stream?: boolean; + prediction?: Prediction; } export interface ModelCapability { @@ -825,6 +839,7 @@ export type EmbeddingsProviderName = | "ollama" | "openai" | "cohere" + | "lmstudio" | "free-trial" | "gemini" | "continue-proxy" @@ -908,6 +923,7 @@ export interface TabAutocompleteOptions { disableInFiles?: string[]; useImports?: boolean; useRootPathContext?: boolean; + showWhateverWeHaveAtXMs?: number; } export interface ContinueUIConfig { @@ -1057,9 +1073,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/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/indexing/embeddings/LMStudio.ts b/core/indexing/embeddings/LMStudio.ts new file mode 100644 index 000000000..f5ec128d3 --- /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: "nomic-ai/nomic-embed-text-v1.5-GGUF", + }; +} + +export default LMStudioEmbeddingsProvider; \ No newline at end of file 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/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/core/llm/llms/OpenAI.ts b/core/llm/llms/OpenAI.ts index b626a9698..168e0afff 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,18 @@ class OpenAI extends BaseLLM { ); } + if (options.prediction && 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 = options.prediction; + } + return finalOptions; } 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/core/promptFiles/v1/handlebarUtils.ts b/core/promptFiles/v1/handlebarUtils.ts index ada9fa6b7..947b76fbf 100644 --- a/core/promptFiles/v1/handlebarUtils.ts +++ b/core/promptFiles/v1/handlebarUtils.ts @@ -71,7 +71,7 @@ export function registerHelpers( export async function prepareTemplateAndData( template: string, readFile: (filepath: string) => 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/v1/renderTemplatedString.ts b/core/promptFiles/v1/renderTemplatedString.ts index d31cce0b9..bcc645ace 100644 --- a/core/promptFiles/v1/renderTemplatedString.ts +++ b/core/promptFiles/v1/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/v1/slashCommandFromPromptFile.ts b/core/promptFiles/v1/slashCommandFromPromptFile.ts index 1bb99b9cc..a272c2872 100644 --- a/core/promptFiles/v1/slashCommandFromPromptFile.ts +++ b/core/promptFiles/v1/slashCommandFromPromptFile.ts @@ -1,5 +1,5 @@ import * as YAML from "yaml"; -import { SlashCommand } from "../.."; +import { ContinueSDK, SlashCommand } from "../.."; import { stripImages } from "../../llm/images"; import { getBasename } from "../../util/index"; import { getContextProviderHelpers } from "./getContextProviderHelpers"; @@ -37,18 +37,21 @@ export function extractUserInput(input: string, commandName: string): string { return input; } -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 }; +export async function getDefaultVariables( + context: ContinueSDK, + userInput: string, +): Promise> { + const currentFile = await context.ide.getCurrentFile(); + 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); diff --git a/core/protocol/core.ts b/core/protocol/core.ts index e2d512950..86f65b3f0 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/util/types"; import { ProfileDescription } from "../config/ConfigHandler"; export type ProtocolGeneratorType = AsyncGenerator<{ @@ -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/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/protocol/ideWebview.ts b/core/protocol/ideWebview.ts index 0526fb499..6fb101c03 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]; @@ -59,7 +65,6 @@ export interface ApplyState { export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & { setInactive: [undefined, void]; - setTTSActive: [boolean, void]; submitMessage: [{ message: any }, void]; // any -> JSONContent from TipTap updateSubmenuItems: [ { provider: string; submenuItems: ContextSubmenuItem[] }, diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index f570b9e87..1c0f5e962 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -60,4 +60,5 @@ export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] = "isContinueInputFocused", "didChangeAvailableProfiles", "setTTSActive", + "getWebviewHistoryLength" ]; diff --git a/core/protocol/webview.ts b/core/protocol/webview.ts index eccb1e97e..ef2daacf0 100644 --- a/core/protocol/webview.ts +++ b/core/protocol/webview.ts @@ -16,4 +16,5 @@ export type ToWebviewFromIdeOrCoreProtocol = { void, ]; setTTSActive: [boolean, void]; + getWebviewHistoryLength: [undefined, number]; }; 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 0ed9f63d2..75c980809 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); @@ -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/core/util/parameters.ts b/core/util/parameters.ts index 4a99dec8c..7a94abc03 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, @@ -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/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, ) ?? "" ); } 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`, ); 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/context-providers.md b/docs/docs/customize/context-providers.md index 41b569604..e582beb1b 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" { @@ -410,6 +410,16 @@ Reference table schemas from Sqlite, Postgres, and MySQL databases. "port": 5432 } }, + { + "name": "exampleMssql", + "connection_type": "mssql", + "connection": { + "user": "username", + "server": "localhost", + "database": "exampleDB", + "password": "yourPassword" + } + }, { "name": "exampleSqlite", "connection_type": "sqlite", 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/customize/model-providers/more/lmstudio.md b/docs/docs/customize/model-providers/more/lmstudio.md index 7448ebd01..a901f811a 100644 --- a/docs/docs/customize/model-providers/more/lmstudio.md +++ b/docs/docs/customize/model-providers/more/lmstudio.md @@ -14,6 +14,19 @@ } ``` +### 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/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/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-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" } ] 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. diff --git a/docs/docs/customize/tutorials/assets/image.png b/docs/docs/customize/tutorials/assets/image.png new file mode 100644 index 000000000..284b2afc9 Binary files /dev/null and b/docs/docs/customize/tutorials/assets/image.png differ 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..3d37790cd 100644 --- a/docs/docs/customize/tutorials/build-your-own-context-provider.md +++ b/docs/docs/customize/tutorials/build-your-own-context-provider.md @@ -203,26 +203,48 @@ 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: -```typescript +```typescript title="myCustomContextProvider.ts" import * as vscode from "vscode"; +import { + IContextProvider, + ContextProviderDescription, + ContextProviderExtras, + ContextItem, + LoadSubmenuItemsArgs, + ContextSubmenuItem, +} from "@continuedev/core"; class MyCustomProvider implements IContextProvider { get description(): ContextProviderDescription { return { - title: "custom", + title: "Custom", displayTitle: "Custom", - description: "Custom description", + description: "my custom context provider", type: "normal", }; } @@ -251,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; @@ -259,3 +281,7 @@ const continueApi = continueExt?.exports; // register your custom provider continueApi?.registerCustomContextProvider(customProvider); ``` + +This will register `MyCustomProvider` with Continue! + +![alt text](./assets/image.png) 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/reference.md b/docs/docs/reference.md index a78a9689b..09dd150a6 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/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/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" }, 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; 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/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 135d13c8d..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() @@ -148,6 +153,28 @@ class ContinuePluginStartupActivity : StartupActivity, Disposable, DumbAware { } }) + // Handle file changes and deletions - reindex + 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("/") } + + // 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) { _ -> } + } + } + }) + // Listen for clicking settings button to start the auth flow val authService = service() val initialSessionInfo = authService.loadControlPlaneSessionInfo() 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..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 @@ -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 @@ -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( + "path" to it.path, + "contents" 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/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/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 diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index f18bdbb6a..953db6d20 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", @@ -88,10 +93,7 @@ "type": "string" } }, - "required": [ - "cert", - "key" - ] + "required": ["cert", "key"] }, "RequestOptions": { "title": "RequestOptions", @@ -406,10 +408,7 @@ "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" - ] + "enum": ["openai", "azure"] }, "apiVersion": { "title": "Api Version", @@ -432,11 +431,7 @@ } } }, - "required": [ - "title", - "provider", - "model" - ], + "required": ["title", "provider", "model"], "allOf": [ { "if": { @@ -446,9 +441,7 @@ } }, "not": { - "required": [ - "provider" - ] + "required": ["provider"] } }, "then": { @@ -478,67 +471,46 @@ ] } }, - "required": [ - "provider" - ] + "required": ["provider"] }, "then": { - "required": [ - "apiKey" - ] + "required": ["apiKey"] } }, { "if": { "properties": { "provider": { - "enum": [ - "bedrockimport" - ] + "enum": ["bedrockimport"] } }, - "required": [ - "provider" - ] + "required": ["provider"] }, "then": { - "required": [ - "modelArn" - ] + "required": ["modelArn"] } }, { "if": { "properties": { "provider": { - "enum": [ - "huggingface-tgi", - "huggingface-inference-api" - ] + "enum": ["huggingface-tgi", "huggingface-inference-api"] } } }, "then": { - "required": [ - "apiBase" - ] + "required": ["apiBase"] }, - "required": [ - "provider" - ] + "required": ["provider"] }, { "if": { "properties": { "provider": { - "enum": [ - "openai" - ] + "enum": ["openai"] } }, - "required": [ - "provider" - ] + "required": ["provider"] }, "then": { "properties": { @@ -558,14 +530,10 @@ "if": { "properties": { "provider": { - "enum": [ - "cloudflare" - ] + "enum": ["cloudflare"] } }, - "required": [ - "provider" - ] + "required": ["provider"] }, "then": { "properties": { @@ -623,14 +591,10 @@ "if": { "properties": { "provider": { - "enum": [ - "openai" - ] + "enum": ["openai"] } }, - "required": [ - "provider" - ] + "required": ["provider"] }, "then": { "properties": { @@ -662,24 +626,17 @@ "if": { "properties": { "provider": { - "enum": [ - "xAI" - ] + "enum": ["xAI"] } }, - "required": [ - "provider" - ] + "required": ["provider"] }, "then": { "properties": { "model": { "anyOf": [ { - "enum": [ - "grok-beta", - "AUTODETECT" - ] + "enum": ["grok-beta", "AUTODETECT"] }, { "type": "string" @@ -693,14 +650,10 @@ "if": { "properties": { "provider": { - "enum": [ - "replicate" - ] + "enum": ["replicate"] } }, - "required": [ - "provider" - ] + "required": ["provider"] }, "then": { "properties": { @@ -734,14 +687,10 @@ "if": { "properties": { "provider": { - "enum": [ - "free-trial" - ] + "enum": ["free-trial"] } }, - "required": [ - "provider" - ] + "required": ["provider"] }, "then": { "properties": { @@ -765,9 +714,7 @@ "if": { "properties": { "provider": { - "enum": [ - "openai" - ] + "enum": ["openai"] }, "apiType": { "not": { @@ -775,9 +722,7 @@ } } }, - "required": [ - "provider" - ] + "required": ["provider"] }, "then": { "properties": { @@ -839,14 +784,10 @@ "if": { "properties": { "provider": { - "enum": [ - "anthropic" - ] + "enum": ["anthropic"] } }, - "required": [ - "provider" - ] + "required": ["provider"] }, "then": { "properties": { @@ -887,22 +828,15 @@ "if": { "properties": { "provider": { - "enum": [ - "cohere" - ] + "enum": ["cohere"] } }, - "required": [ - "provider" - ] + "required": ["provider"] }, "then": { "properties": { "model": { - "enum": [ - "command-r", - "command-r-plus" - ] + "enum": ["command-r", "command-r-plus"] } } } @@ -911,14 +845,10 @@ "if": { "properties": { "provider": { - "enum": [ - "bedrock" - ] + "enum": ["bedrock"] } }, - "required": [ - "provider" - ] + "required": ["provider"] }, "then": { "properties": { @@ -943,14 +873,10 @@ "if": { "properties": { "provider": { - "enum": [ - "sagemaker" - ] + "enum": ["sagemaker"] } }, - "required": [ - "provider" - ] + "required": ["provider"] }, "then": { "properties": { @@ -964,14 +890,10 @@ "if": { "properties": { "provider": { - "enum": [ - "gemini" - ] + "enum": ["gemini"] } }, - "required": [ - "provider" - ] + "required": ["provider"] }, "then": { "properties": { @@ -1001,14 +923,10 @@ "if": { "properties": { "provider": { - "enum": [ - "together" - ] + "enum": ["together"] } }, - "required": [ - "provider" - ] + "required": ["provider"] }, "then": { "properties": { @@ -1046,14 +964,10 @@ "if": { "properties": { "provider": { - "enum": [ - "deepinfra" - ] + "enum": ["deepinfra"] } }, - "required": [ - "provider" - ] + "required": ["provider"] }, "then": { "properties": { @@ -1077,9 +991,7 @@ ] } }, - "required": [ - "provider" - ] + "required": ["provider"] }, "then": { "properties": { @@ -1128,14 +1040,10 @@ "if": { "properties": { "provider": { - "enum": [ - "ollama" - ] + "enum": ["ollama"] } }, - "required": [ - "provider" - ] + "required": ["provider"] }, "then": { "properties": { @@ -1187,14 +1095,10 @@ "if": { "properties": { "provider": { - "enum": [ - "mistral" - ] + "enum": ["mistral"] } }, - "required": [ - "provider" - ] + "required": ["provider"] }, "then": { "properties": { @@ -1216,34 +1120,23 @@ "if": { "properties": { "provider": { - "enum": [ - "vertexai" - ] + "enum": ["vertexai"] } }, - "required": [ - "provider" - ] + "required": ["provider"] }, "then": { - "required": [ - "projectId", - "region" - ] + "required": ["projectId", "region"] } }, { "if": { "properties": { "provider": { - "enum": [ - "deepseek" - ] + "enum": ["deepseek"] } }, - "required": [ - "provider" - ] + "required": ["provider"] }, "then": { "properties": { @@ -1260,10 +1153,7 @@ } }, "model": { - "enum": [ - "deepseek-chat", - "deepseek-coder" - ] + "enum": ["deepseek-chat", "deepseek-coder"] } } } @@ -1272,14 +1162,10 @@ "if": { "properties": { "provider": { - "enum": [ - "groq" - ] + "enum": ["groq"] } }, - "required": [ - "provider" - ] + "required": ["provider"] }, "then": { "properties": { @@ -1304,21 +1190,15 @@ "if": { "properties": { "provider": { - "enum": [ - "fireworks" - ] + "enum": ["fireworks"] } }, - "required": [ - "provider" - ] + "required": ["provider"] }, "then": { "properties": { "model": { - "enum": [ - "starcoder-7b" - ] + "enum": ["starcoder-7b"] } } } @@ -1330,29 +1210,20 @@ "const": "azure" } }, - "required": [ - "apiType" - ] + "required": ["apiType"] }, "then": { - "required": [ - "deployment", - "apiBase" - ] + "required": ["deployment", "apiBase"] } }, { "if": { "properties": { "provider": { - "enum": [ - "openai" - ] + "enum": ["openai"] } }, - "required": [ - "provider" - ] + "required": ["provider"] }, "then": { "properties": { @@ -1369,9 +1240,7 @@ "const": "llamafile" } }, - "required": [ - "provider" - ] + "required": ["provider"] }, "then": { "properties": { @@ -1385,22 +1254,15 @@ "if": { "properties": { "provider": { - "enum": [ - "cerebras" - ] + "enum": ["cerebras"] } }, - "required": [ - "provider" - ] + "required": ["provider"] }, "then": { "properties": { "model": { - "enum": [ - "llama3.1-8b", - "llama3.1-70b" - ] + "enum": ["llama3.1-8b", "llama3.1-70b"] } } } @@ -1409,14 +1271,10 @@ "if": { "properties": { "provider": { - "enum": [ - "text-gen-webui" - ] + "enum": ["text-gen-webui"] } }, - "required": [ - "provider" - ] + "required": ["provider"] }, "then": { "properties": { @@ -1430,14 +1288,10 @@ "if": { "properties": { "provider": { - "enum": [ - "flowise" - ] + "enum": ["flowise"] } }, - "required": [ - "provider" - ] + "required": ["provider"] }, "then": { "properties": { @@ -1464,10 +1318,7 @@ "type": "string" } }, - "required": [ - "key", - "value" - ] + "required": ["key", "value"] } }, "additionalFlowiseConfiguration": { @@ -1486,10 +1337,7 @@ "description": "Configuration Property value" } }, - "required": [ - "key", - "value" - ] + "required": ["key", "value"] } }, "model": { @@ -1564,14 +1412,10 @@ "if": { "properties": { "provider": { - "enum": [ - "watsonx" - ] + "enum": ["watsonx"] } }, - "required": [ - "provider" - ] + "required": ["provider"] }, "then": { "properties": { @@ -1607,36 +1451,24 @@ ] } }, - "required": [ - "apiBase", - "apiKey", - "apiVersion" - ] + "required": ["apiBase", "apiKey", "apiVersion"] } }, { "if": { "properties": { "provider": { - "enum": [ - "sambanova" - ] + "enum": ["sambanova"] } }, - "required": [ - "provider" - ] + "required": ["provider"] }, "then": { "properties": { "model": { "anyOf": [ { - "enum": [ - "llama3.1-8b", - "llama3.1-70b", - "llama3.1-405b" - ] + "enum": ["llama3.1-8b", "llama3.1-70b", "llama3.1-405b"] }, { "type": "string" @@ -1651,14 +1483,10 @@ "if": { "properties": { "provider": { - "enum": [ - "ask-sage" - ] + "enum": ["ask-sage"] } }, - "required": [ - "provider" - ] + "required": ["provider"] }, "then": { "properties": { @@ -1713,9 +1541,7 @@ "type": "string" } }, - "required": [ - "default" - ] + "required": ["default"] }, "SlashCommand": { "title": "SlashCommand", @@ -1772,9 +1598,7 @@ "if": { "properties": { "name": { - "enum": [ - "issue" - ] + "enum": ["issue"] } } }, @@ -1787,23 +1611,17 @@ "description": "Enter the URL of the GitHub repository for which you want to generate the issue." } }, - "required": [ - "repositoryUrl" - ] + "required": ["repositoryUrl"] } }, - "required": [ - "params" - ] + "required": ["params"] } }, { "if": { "properties": { "name": { - "enum": [ - "edit" - ] + "enum": ["edit"] } } }, @@ -1829,9 +1647,7 @@ "if": { "properties": { "name": { - "enum": [ - "share" - ] + "enum": ["share"] } } }, @@ -1853,9 +1669,7 @@ "if": { "properties": { "name": { - "enum": [ - "commit" - ] + "enum": ["commit"] } } }, @@ -1874,10 +1688,7 @@ } } ], - "required": [ - "name", - "description" - ] + "required": ["name", "description"] }, "CustomCommand": { "title": "CustomCommand", @@ -1896,11 +1707,7 @@ "type": "string" } }, - "required": [ - "name", - "prompt", - "description" - ] + "required": ["name", "prompt", "description"] }, "ContextProviderWithParams": { "title": "ContextProviderWithParams", @@ -1980,9 +1787,7 @@ "if": { "properties": { "name": { - "enum": [ - "discord" - ] + "enum": ["discord"] } } }, @@ -2015,15 +1820,11 @@ "description": "The name of the channel" } }, - "required": [ - "id" - ] + "required": ["id"] } } }, - "required": [ - "discordKey" - ] + "required": ["discordKey"] } } }, @@ -2032,18 +1833,14 @@ { "properties": { "params": { - "required": [ - "guildId" - ] + "required": ["guildId"] } } }, { "properties": { "params": { - "required": [ - "channels" - ] + "required": ["channels"] } } } @@ -2056,9 +1853,7 @@ "if": { "properties": { "name": { - "enum": [ - "google" - ] + "enum": ["google"] } } }, @@ -2071,23 +1866,17 @@ "description": "Your API key for https://serper.dev in order to get Google search results" } }, - "required": [ - "serperApiKey" - ] + "required": ["serperApiKey"] } }, - "required": [ - "params" - ] + "required": ["params"] } }, { "if": { "properties": { "name": { - "enum": [ - "web" - ] + "enum": ["web"] } } }, @@ -2104,18 +1893,14 @@ } } }, - "required": [ - "params" - ] + "required": ["params"] } }, { "if": { "properties": { "name": { - "enum": [ - "open" - ] + "enum": ["open"] } } }, @@ -2137,9 +1922,7 @@ "if": { "properties": { "name": { - "enum": [ - "issue" - ] + "enum": ["issue"] } } }, @@ -2168,37 +1951,24 @@ "type": { "type": "string", "description": "The type of issues to search for", - "enum": [ - "open", - "closed", - "all" - ] + "enum": ["open", "closed", "all"] } }, - "required": [ - "owner", - "repo" - ] + "required": ["owner", "repo"] } } }, - "required": [ - "repos" - ] + "required": ["repos"] } }, - "required": [ - "params" - ] + "required": ["params"] } }, { "if": { "properties": { "name": { - "enum": [ - "database" - ] + "enum": ["database"] } } }, @@ -2219,11 +1989,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", @@ -2256,31 +2022,21 @@ "required": [] } }, - "required": [ - "name", - "connection_type", - "connection" - ] + "required": ["name", "connection_type", "connection"] } } }, - "required": [ - "connections" - ] + "required": ["connections"] } }, - "required": [ - "params" - ] + "required": ["params"] } }, { "if": { "properties": { "name": { - "enum": [ - "gitlab-mr" - ] + "enum": ["gitlab-mr"] } } }, @@ -2301,23 +2057,17 @@ "description": "If you have code selected, filters out comments that aren't related to the selection." } }, - "required": [ - "token" - ] + "required": ["token"] } }, - "required": [ - "params" - ] + "required": ["params"] } }, { "if": { "properties": { "name": { - "enum": [ - "jira" - ] + "enum": ["jira"] } } }, @@ -2364,24 +2114,17 @@ ] } }, - "required": [ - "domain", - "token" - ] + "required": ["domain", "token"] } }, - "required": [ - "params" - ] + "required": ["params"] } }, { "if": { "properties": { "name": { - "enum": [ - "http" - ] + "enum": ["http"] } } }, @@ -2399,24 +2142,17 @@ "type": "object" } }, - "required": [ - "url" - ] + "required": ["url"] } }, - "required": [ - "params" - ] + "required": ["params"] } }, { "if": { "properties": { "name": { - "enum": [ - "codebase", - "folder" - ] + "enum": ["codebase", "folder"] } } }, @@ -2451,9 +2187,7 @@ "if": { "properties": { "name": { - "enum": [ - "postgres" - ] + "enum": ["postgres"] } } }, @@ -2505,22 +2239,14 @@ } } }, - "required": [ - "host", - "port", - "user", - "password", - "database" - ] + "required": ["host", "port", "user", "password", "database"] } }, { "if": { "properties": { "name": { - "enum": [ - "greptile" - ] + "enum": ["greptile"] } } }, @@ -2543,16 +2269,11 @@ } } }, - "required": [ - "GreptileToken", - "GithubToken" - ] + "required": ["GreptileToken", "GithubToken"] } } ], - "required": [ - "name" - ] + "required": ["name"] }, "SerializedContinueConfig": { "title": "config.json", @@ -2586,10 +2307,7 @@ "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" - ] + "required": ["title", "startUrl"] } }, "allowAnonymousTelemetry": { @@ -2717,13 +2435,18 @@ "openai", "cohere", "free-trial", + "continue-proxy", "gemini", "voyage", "nvidia", "bedrock", "sagemaker", "nebius", - "vertexai" + "vertexai", + "deepinfra", + "mistral", + "watsonx", + "lmstudio" ] }, "model": { @@ -2765,44 +2488,29 @@ "type": "string" } }, - "required": [ - "provider" - ], + "required": ["provider"], "allOf": [ { "if": { "properties": { "provider": { - "enum": [ - "cohere", - "voyage", - "nvidia", - "gemini" - ] + "enum": ["cohere", "voyage", "nvidia", "gemini"] } }, - "required": [ - "provider" - ] + "required": ["provider"] }, "then": { - "required": [ - "apiKey" - ] + "required": ["apiKey"] } }, { "if": { "properties": { "provider": { - "enum": [ - "sagemaker" - ] + "enum": ["sagemaker"] } }, - "required": [ - "provider" - ] + "required": ["provider"] }, "then": { "properties": { @@ -2810,23 +2518,17 @@ "description": "SageMaker endpoint name" } }, - "required": [ - "model" - ] + "required": ["model"] } }, { "if": { "properties": { "provider": { - "enum": [ - "vertexai" - ] + "enum": ["vertexai"] } }, - "required": [ - "provider" - ] + "required": ["provider"] }, "then": { "properties": { @@ -2841,11 +2543,7 @@ "default": "text-embedding-004" } }, - "required": [ - "projectId", - "model", - "region" - ] + "required": ["projectId", "model", "region"] } } ] @@ -2868,22 +2566,16 @@ "type": "object" } }, - "required": [ - "name" - ], + "required": ["name"], "allOf": [ { "if": { "properties": { "name": { - "enum": [ - "cohere" - ] + "enum": ["cohere"] } }, - "required": [ - "name" - ] + "required": ["name"] }, "then": { "properties": { @@ -2905,9 +2597,7 @@ "type": "string" } }, - "required": [ - "apiKey" - ] + "required": ["apiKey"] } } } @@ -2916,14 +2606,10 @@ "if": { "properties": { "name": { - "enum": [ - "llm" - ] + "enum": ["llm"] } }, - "required": [ - "name" - ] + "required": ["name"] }, "then": { "properties": { @@ -2934,9 +2620,7 @@ "type": "string" } }, - "required": [ - "modelTitle" - ] + "required": ["modelTitle"] } } } @@ -2945,14 +2629,10 @@ "if": { "properties": { "name": { - "enum": [ - "voyage" - ] + "enum": ["voyage"] } }, - "required": [ - "name" - ] + "required": ["name"] }, "then": { "properties": { @@ -2971,9 +2651,7 @@ ] } }, - "required": [ - "apiKey" - ] + "required": ["apiKey"] } } } @@ -2982,14 +2660,10 @@ "if": { "properties": { "name": { - "enum": [ - "huggingface-tei" - ] + "enum": ["huggingface-tei"] } }, - "required": [ - "name" - ] + "required": ["name"] }, "then": { "properties": { @@ -3009,17 +2683,12 @@ "default": false }, "truncation_direction": { - "enum": [ - "Right", - "Left" - ], + "enum": ["Right", "Left"], "description": "Whether to truncate sequences from the left or right.", "default": "Right" } }, - "required": [ - "apiBase" - ] + "required": ["apiBase"] } }, "if": { @@ -3030,9 +2699,7 @@ } }, "then": { - "required": [ - "truncation_direction" - ] + "required": ["truncation_direction"] } } } @@ -3103,11 +2770,7 @@ "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" - ], + "enum": ["always", "never", "auto"], "description": "If set to true, Continue will only complete a single line at a time." }, "useCache": { @@ -3136,10 +2799,7 @@ "type": "object", "properties": { "codeBlockToolbarPosition": { - "enum": [ - "top", - "bottom" - ], + "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." }, @@ -3165,10 +2825,7 @@ "properties": { "provider": { "type": "string", - "enum": [ - "posthog", - "logstash" - ], + "enum": ["posthog", "logstash"], "description": "The 3rd party analytics provider to use.", "default": "posthog", "markdownEnumDescriptions": [ @@ -3184,40 +2841,30 @@ "description": "The client key to use for analytics" } }, - "required": [ - "provider" - ], + "required": ["provider"], "allOf": [ { "if": { "properties": { "provider": { - "enum": [ - "posthog" - ] + "enum": ["posthog"] } } }, "then": { - "required": [ - "clientKey" - ] + "required": ["clientKey"] } }, { "if": { "properties": { "provider": { - "enum": [ - "logstash" - ] + "enum": ["logstash"] } } }, "then": { - "required": [ - "url" - ] + "required": ["url"] } } ] @@ -3289,10 +2936,7 @@ "default": false } }, - "required": [ - "prompt", - "title" - ] + "required": ["prompt", "title"] }, "description": "Quick actions are a way to add custom commands to the Code Lens of function and class declarations." }, @@ -3331,4 +2975,4 @@ } } } -} \ No newline at end of file +} diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 3751e3f97..466cd705e 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "0.9.226", + "version": "0.9.227", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "0.9.226", + "version": "0.9.227", "license": "Apache-2.0", "dependencies": { "@electron/rebuild": "^3.2.10", @@ -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/extensions/vscode/package.json b/extensions/vscode/package.json index 52029445b..50c295b98 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -608,7 +608,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", diff --git a/extensions/vscode/src/VsCodeIde.ts b/extensions/vscode/src/VsCodeIde.ts index 526dc1844..eabb2fec8 100644 --- a/extensions/vscode/src/VsCodeIde.ts +++ b/extensions/vscode/src/VsCodeIde.ts @@ -256,6 +256,7 @@ class VsCodeIde implements IDE { return tags; } + getIdeInfo(): Promise { return Promise.resolve({ ideType: "vscode", @@ -267,6 +268,7 @@ class VsCodeIde implements IDE { .version, }); } + readRangeInFile(filepath: string, range: Range): Promise { return this.ideUtils.readRangeInFile( filepath, @@ -343,7 +345,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)); @@ -385,7 +387,7 @@ class VsCodeIde implements IDE { } async openFile(path: string): Promise { - this.ideUtils.openFile(path); + await this.ideUtils.openFile(path); } async showLines( @@ -422,8 +424,55 @@ 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 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, @@ -437,8 +486,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 { @@ -573,3 +627,4 @@ class VsCodeIde implements IDE { } export { VsCodeIde }; + diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index 821f215f1..131d61ffa 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/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/lsp.ts b/extensions/vscode/src/autocomplete/lsp.ts index f24b23bf3..41ae1d973 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 { 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"; 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..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/ranking"; -import { RecentlyEditedRange } from "core/autocomplete/recentlyEdited"; +import { getSymbolsForSnippet } from "core/autocomplete/context/ranking"; +import { RecentlyEditedRange } from "core/autocomplete/util/types"; import { RangeInFileWithContents } from "core/commands/util"; import * as vscode from "vscode"; diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index bb020c302..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,6 +33,7 @@ import { QuickEdit, QuickEditShowParams } from "./quickEdit/QuickEditQuickPick"; import { Battery } from "./util/battery"; import { getFullyQualifiedPath } from "./util/util"; import { uriFromFilePath } from "./util/vscode"; +import { VsCodeIde } from "./VsCodeIde"; import type { VsCodeWebviewProtocol } from "./webviewProtocol"; let fullScreenPanel: vscode.WebviewPanel | undefined; @@ -177,18 +178,31 @@ async function addEntireFileToContext( function focusGUI() { const fullScreenTab = getFullScreenTab(); - if (!fullScreenTab) { - // focus sidebar - vscode.commands.executeCommand("continue.continueGUIView.focus"); - } else { + if (fullScreenTab) { // focus fullscreen fullScreenPanel?.reveal(); + } else { + // focus sidebar + vscode.commands.executeCommand("continue.continueGUIView.focus"); + // vscode.commands.executeCommand("workbench.action.focusAuxiliaryBar"); + } +} + +function hideGUI() { + const fullScreenTab = getFullScreenTab(); + if (fullScreenTab) { + // focus fullscreen + fullScreenPanel?.dispose(); + } else { + // focus sidebar + vscode.commands.executeCommand("workbench.action.closeAuxiliaryBar"); + // vscode.commands.executeCommand("workbench.action.toggleAuxiliaryBar"); } } // Copy everything over from extension.ts const commandsMap: ( - ide: IDE, + ide: VsCodeIde, extensionContext: vscode.ExtensionContext, sidebar: ContinueGUIWebviewViewProvider, configHandler: ConfigHandler, @@ -261,8 +275,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 +294,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, false); @@ -344,32 +362,37 @@ const commandsMap: ( 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 historyLength = await sidebar.webviewProtocol.request( + "getWebviewHistoryLength", + undefined, + ); const isContinueInputFocused = await sidebar.webviewProtocol.request( "isContinueInputFocused", undefined, ); if (isContinueInputFocused) { - // Handle closing the GUI only if we are focused on the input - if (fullScreenTab) { - fullScreenPanel?.dispose(); + if (historyLength === 0) { + hideGUI(); + } else { + sidebar.webviewProtocol?.request("focusContinueInput", undefined); } } else { - // Handle opening the GUI otherwise - if (!fullScreenTab) { - // focus sidebar - vscode.commands.executeCommand("continue.continueGUIView.focus"); - } else { - // focus fullscreen - fullScreenPanel?.reveal(); - } + 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(); sidebar.webviewProtocol?.request( "focusContinueInputWithoutClear", @@ -381,39 +404,40 @@ const commandsMap: ( }, "continue.edit": async () => { captureCommandTelemetry("edit"); - const fullScreenTab = getFullScreenTab(); - if (!fullScreenTab) { - // focus sidebar - vscode.commands.executeCommand("continue.continueGUIView.focus"); - } else { - // focus fullscreen - fullScreenPanel?.reveal(); - } + focusGUI(); const editor = vscode.window.activeTextEditor; if (!editor) { return; } - editDecorationManager.setDecoration( - editor, - new vscode.Range(editor.selection.start, editor.selection.end), + 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), + ); - const highlightedCode = getCurrentlyHighlightedCode(true)!; - await sidebar.webviewProtocol?.request("startEditMode", { - highlightedCode, - }); + 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, - ); + // Un-select the current selection + editor.selection = new vscode.Selection( + editor.selection.anchor, + editor.selection.anchor, + ); - setTimeout(() => { + setTimeout(() => { + sidebar.webviewProtocol?.request("focusContinueInput", undefined); + }, 30); + } else { sidebar.webviewProtocol?.request("focusContinueInput", undefined); - }, 30); + } }, "continue.exitEditMode": async () => { captureCommandTelemetry("exitEditMode"); @@ -564,15 +588,15 @@ const commandsMap: ( const fullScreenTab = getFullScreenTab(); if (fullScreenTab && fullScreenPanel) { - //Full screen open, but not focused - focus it + // Full screen open, but not focused - focus it fullScreenPanel.reveal(); return; } - //Full screen not open - open it + // Full screen not open - open it captureCommandTelemetry("openFullScreen"); - //create the full screen panel + // Create the full screen panel let panel = vscode.window.createWebviewPanel( "continue.continueGUIView", "Continue", @@ -583,7 +607,7 @@ const commandsMap: ( ); fullScreenPanel = panel; - //Add content to the panel + // Add content to the panel panel.webview.html = sidebar.getSidebarContent( extensionContext, panel, @@ -592,7 +616,7 @@ const commandsMap: ( true, ); - //When panel closes, reset the webview and focus + // When panel closes, reset the webview and focus panel.onDidDispose( () => { sidebar.resetWebviewProtocolWebview(); @@ -807,7 +831,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/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/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index 5534625d9..faee3cc06 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -291,11 +291,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.split("/").slice(0, -1).join("/")) + }) + }) + // When GitHub sign-in status changes, reload config vscode.authentication.onDidChangeSessions(async (e) => { if (e.provider.id === "github") { @@ -328,7 +335,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] }); } } @@ -341,8 +348,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/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index 483ff1603..d7ed63a5f 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(this.ide, 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(ide, 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/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( 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/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"; diff --git a/extensions/vscode/src/util/ideUtils.ts b/extensions/vscode/src/util/ideUtils.ts index d42aa65b0..2dd9cd330 100644 --- a/extensions/vscode/src/util/ideUtils.ts +++ b/extensions/vscode/src/util/ideUtils.ts @@ -156,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, @@ -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/extensions/vscode/src/util/util.ts b/extensions/vscode/src/util/util.ts index 2d0ae72a7..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,15 +124,12 @@ export function getExtensionVersion(): string { return extension?.packageJSON.version || "0.1.0"; } -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", - ); - } +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 ide.ideUtils.path.join(workspaceFolders[0].uri.fsPath, filepath); } } 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" 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/components/mainInput/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor.tsx index 631f59824..c2646415e 100644 --- a/gui/src/components/mainInput/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor.tsx @@ -508,7 +508,7 @@ function TipTapEditor(props: TipTapEditorProps) { return; } }, - editable: !active, + editable: !active || props.isMainInput, }); const [shouldHideToolbar, setShouldHideToolbar] = useState(false); @@ -551,18 +551,10 @@ function TipTapEditor(props: TipTapEditorProps) { * with those key actions. */ const handleKeyDown = async (e: KeyboardEvent) => { - if (!editor || !editorFocusedRef.current) return; + if (!editorFocusedRef?.current) return; setActiveKey(e.key); - // Allow users to use the escape key to jump back to the editor - if (e.key === "Escape") { - e.stopPropagation(); - e.preventDefault(); - ideMessenger.post("focusEditor", undefined); - return; - } - // Handle meta key issues if (isMetaEquivalentKeyPressed(e)) { if (isJetBrains()) { @@ -631,7 +623,7 @@ function TipTapEditor(props: TipTapEditorProps) { return; } if (historyLength > 0) { - saveSession(); + await saveSession(); } setTimeout(() => { editor?.commands.blur(); @@ -660,12 +652,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( @@ -685,9 +677,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: { @@ -702,6 +696,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 { 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 b5380e26d..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; @@ -87,6 +87,7 @@ interface CodeBlockToolBarProps { language: string | undefined; isNextCodeBlock: boolean; filepath?: string; + range?: string; } const terminalLanguages = ["bash", "sh"]; @@ -131,7 +132,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 +149,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,23 +173,26 @@ function CodeBlockToolBar(props: CodeBlockToolBarProps) { } async function onClickApply() { - if (isApplying) return; - 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() { @@ -227,7 +231,6 @@ function CodeBlockToolBar(props: CodeBlockToolBarProps) { {!isJetBrains() && isTerminal && ( @@ -235,15 +238,11 @@ function CodeBlockToolBar(props: CodeBlockToolBarProps) { )} - {isApplying ? ( - - ) : ( - - )} + - {getBasename(props.filepath)} + + {getBasename(props.filepath)} + {props.range && ` ${props.range}`} +
diff --git a/gui/src/components/markdown/CodeSnippetPreview.tsx b/gui/src/components/markdown/CodeSnippetPreview.tsx index 5794b6781..b635179a2 100644 --- a/gui/src/components/markdown/CodeSnippetPreview.tsx +++ b/gui/src/components/markdown/CodeSnippetPreview.tsx @@ -86,7 +86,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, ); @@ -123,8 +123,8 @@ function CodeSnippetPreview(props: CodeSnippetPreviewProps) { >
diff --git a/gui/src/components/markdown/PreWithToolbar.tsx b/gui/src/components/markdown/PreWithToolbar.tsx index ec9297d54..75304f4e5 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"; @@ -76,6 +77,7 @@ function PreWithToolbar(props: { bottom={toolbarBottom} language={props.language} filepath={props.filepath} + range={props.range} /> ) : ( hovering && ( @@ -84,6 +86,7 @@ function PreWithToolbar(props: { text={copyValue} bottom={toolbarBottom} language={props.language} + range={props.range} /> ) )} 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 ? ( diff --git a/gui/src/hooks/useChatHandler.ts b/gui/src/hooks/useChatHandler.ts index 5cd469c87..ba0a7e26d 100644 --- a/gui/src/hooks/useChatHandler.ts +++ b/gui/src/hooks/useChatHandler.ts @@ -216,30 +216,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, }, }); } diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index 09bb77010..f7c9fdf10 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -87,6 +87,11 @@ function useSetup(dispatch: Dispatch) { ); // IDE event listeners + const history = useSelector((store: RootState) => store.state.history); + useWebviewListener("getWebviewHistoryLength", async () => { + return history.length; + }, [history]); + useWebviewListener("setInactive", async () => { dispatch(setInactive()); }); 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 && (
)} 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
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, ); 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. +
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(),