* ✨ shared indexing
* 🎨 indexing
* 🧑💻 npm i --no-save in prepackage.js
* fix issue with /edit not acknowledging highlighted code after retrying
* 🚚 rename addLogs to addPromptCompletionPair
* Bedrock chat completion, Anthropic models
* 🩹 add filter for midline imports/top-level keywords and encoding header
* 🩹 add .t. to stop words
* 🔥 Improved Ctrl/Cmd+I (#1023)
* ⚡️ improved diff streaming algo
* 🎨 better messaging/formatting for further cmd/ctrl+I instructions
* ⚡️ more reliably filter out unwanted explanations
* 🚸 better follow up edits
* 💄 accept/reject diffs block-by-block
* ✨ cmd/ctrl+z to reject diff
* 🚚 rename variables
* 💄 allow switching files when inline diff still visible
* 🚸 don't show quick pick if not ctx providers exist
* 🚧 (sort of) allow switching editors while streaming diff
* 💄 show model being used for cmd/ctrl+I
* 💄 don't add undo stops when generating diff
* 🐛 fix shortcuts for accept/reject diff blocks
* ✨ improved GPT edit prompt, taking prefix/suffix into account
* ✨ improved prompting for empty selection ctrl/cmd+I
* ⚡️ immediately refresh codelens
* 🐛 use first model if default undefined
* ⚡️ refresh codelens after diff cleared
* 💄 update keyboard shortcuts
* ⚡️ Improved edit prompts for OS models (#1029)
* 💄 refresh codelens more frequently
* ⚡️ improved codellama edit prompt
* ⚡️ better codellama prompt
* ⚡️ use same improved prompt for most OS models
* 🎨 refactor chat templates
* 🎨 refactor llama2 prompt to allow ending assistant message
* ⚡️ separate os models prompt when no prefix/suffix
* 🎨 refactor to allow putting words in the model's mouth
* ⚡️ prune code around cmd/ctrl+I
* 🚚 rename to cmd/ctrl+I
* 🎨 make raw a base completion option
* 🩹 small improvements
* 🩹 use different prompt when completions not supported
* Keep the same statusBar item when updating it to prevent flickering of the status bar. (#1022)
* 🎨 add getRepoName to IDE, use for indexing
* 🎨 implement server client interface
* 📌 pin to vectordb=0.4.12
* 🧑💻 mark xhr-sync-worker.js as external in esbuild
* 🎨 break out ignore defaults into core
* 🎨 update getRepoName
* 🐛 fix import error
* 🩹 fix chat.jsonl logging
* ⚡️ improved OpenAI autocomplete support
* 🐛 fix bug causing part of completions to be skipped
* 🔥 remove URLContextProvider
* ✨ Add Groq as an official provider
* 🩹 make sure autocomplete works with claude
* 💄 update positioning of code block toolbar to not cover code
* ✨ Run in terminal button
* ✨ insert at cursor button
* ✨ Regenerate and copy buttons
* ✨ Button to force re-indexing
* 🐛 make sure tooltip IDs are unique
* ✨ Button to continue truncated response
* 🚧 WIP on inline edit browser embedding
* 🚧 inline TipTapEditor
* 🚧 WIP on inline TipTapEditor
* 🔥 remove unused test component
* 🚧 native inline edit
* 💄 nicer looking input box
* ✨ Diff Streaming in JetBrains
* 💄 line highlighting
* 💄 arial font
* ✨ Retry with further instructions
* 🚧 drop shadow
* ✨ accept/reject diffs
* ✨ accept/reject diffs
* 🐛 fix off-by-one errors
* 🚧 swap out button on enter
* 💄 styling and auto-resize
* 💄 box shadow
* 🚧 fix keyboard shortcuts to accept/reject diff
* 💄 improve small interactions
* 💄 loading icon, cancellation logic
* 🐛 handle next.value being undefined
* ✨ latex support
* Bug Fix: Add ternary operator to prevent nonexistant value error (#1052)
* add terniary operator
* Removing logging
* remove comment
---------
Co-authored-by: Justin Milner <jmilner@jmilner-lt2.deka.local>
Co-authored-by: Nate Sesti <33237525+sestinj@users.noreply.github.com>
* 🎨 small formatting change
* 🩹 tweak /edit solution
* ✨ Dropdown to select model
* 🔊 print when SSL verification disabled
* 📌 pin esbuild version to match our hosted binary
* 🔥 remove unused package folder
* 👷 add note about pinning esbuild
* 🚚 rename pkg to binary
* ⚡️ update an important stop word for starcoder2, improve dev data
* 🐛 fix autocomplete bug
* Update completionProvider.ts
Add \r\n\r\n stop to tab completion
* 📌 update package-locks
* 🐛 fix bug in edit prompt
* 🔊 log extension version
* 🐛 handle repo undefined in vscode
* ⏪ revert back to esbuild ^0.17.19 to solve no backend found error with onnxruntime
* 🩹 set default autocomplete temp to 0.01 to be strictly positive
* make the useCopyBuffer option effective (#1062)
* Con-1037: Toggle full screen bug (#1065)
* webview reset
* add warning
---------
Co-authored-by: Justin Milner <jmilner@jmilner-lt2.deka.local>
* Update completionProvider.ts
as @rootedbox suggested
* Resolve conflict, accept branch being merged in (#1076)
* Resolve conflict, accept branch being merged in
* remove accidental .gitignore add
* whoops, put gitignore back
* fix
---------
Co-authored-by: Justin Milner <jmilner@jmilner-lt2.deka.local>
* #1073: update outdated documentation (#1074)
* 🩹 small tweaks to stop words
* Add abstraction for fetch to easily allow using request options (#1059)
* add fetch helper function with request options
* add support for request options for Jira context provider
* Add a new slash command to review code. (#1071)
* Add a new slash command to review code.
* clean code
* 🩹 add new starcoder artifact as stopword
* 💄 slight improvements to inline edit UI
* 🔖 update default models, bump gradle version
* 📝 recommend starcoder2
* 🐛 fix jetbrains encoding issue
* 🩹 don't index site-packages
* 🩹 error handling in JetBrains
* 🐛 fix copy to clipboard in jetbrains
* fix: cursor focus issue causing unwanted return to text area (#1086)
* 📝 mention autocomplete in jetbrains
* 📝 Tab-autocomplete README
* 🔥 remove note about custom ctx providers only being on VS Code
* 📝 docs about http context provider
* 👥 pull request template
* Update from Claude 2 to Claude 3 (#1078)
* 📝 add FAQ about single-line completions
* 📝 update autocomplete docs
* fix cursor focus issue causing unwanted return to text area
---------
Co-authored-by: Nate Sesti <sestinj@gmail.com>
Co-authored-by: Ty Dunn <ty@tydunn.com>
Co-authored-by: Nate Sesti <33237525+sestinj@users.noreply.github.com>
* Update tree-sitter-wasms to 0.1.11 (which includes Solidity)
* Make use of solidity tree-sitter parser
* 🔧 option to disable autocomplete from config.json
* ✨ option to disable streaming with anthropic
* ✅ Test to verify that files are packaged
* Add FIM template for CodeGemma (#1097)
Also pass stop tokens to llama.cpp.
* ✨ customizable rerankers (#1088)
* ✨ customizable rerankers
* 💄 fix early truncation button
* ⚡️ improvements to full text search + reranking
* ⚡️ only use starcoder2 stop words for starcoder2
* ⚡️ crawl code graph for call expressions
* 🚧 starcoder2-7b free trial
* 🚧 free trial client for embeddings and re-ranking
* 🚧 embeddings provider
* ✅ test for presence of files in CI
* 🐛 fixes to reranking
* ✨ new onboarding experience
* ✨ new onboarding experience
* 💄 small tweaks to onboarding
* 🩹 add stopAtLines filter to /edit
* 🐛 clean up vite build errors
* 👷 make vscode external in binary build
* 💄 improved models onboarding for existing users
* 💄 default indexing progress to 0.0
* 🐛 small fixes to reranking
* 👷 clear folders before prepackage
* 👷 say where .vsix is output
* 👷 also download arm packages outside of gh actions
* 🎨 add AbortSignal to indexing
* 🔧 starcoder, not 2 in config_schema
* 🚚 again, starcoder, not 2
* 🐛 fix bug when reranker undefined
* 🩹 fix binary tsc error
* ✨ configure context menu prompts
* 🐛 acknowledge useLegacyCompletionsEndpoint
* 🚑 fix keep existing config option
* 🔊 learn about selection
* ⚡️ improvements to indexing reporting when not in git repo
* 🥅 handle situation where git doesn't exist in workspace
* ✨ support for gemini 1.5 pro
* 🐛 handle embeddingProvider name not found
* ✨ Gemini 1.5 and GPT-4 Turbo
* 👷 fix os, arch undefined in prepackage.js
* ⚡️ better detection of terminal code blocks
* 🧑💻 solve tailwind css warnings
* ✨ cmd/ctrl+L to select terminal contents
* 🐛 correctly handle remotes not found
* ✨ allow templating for custom commands
* 🔥 temporarily remove cmd+L to select terminal contents
* 🐛 remove quotes around Ollama stop words
* ✨ add Cohere as Model Provider (#1119)
* 🩹 add gpt-4-turbo to list of chat_only models
* feat: use exponential backoff in llm chat (#1115)
Signed-off-by: inimaz <93inigo93@gmail.com>
* 🩹 update exponential backoff timing
* 💄 spell out Alt in keyboard shortcuts
* 🩹 don't set edit prompt for templateType "none"
* Adds additional ignores for C-fmilies langs (#1129)
Ignored:
- cache directory `.cache`, used by clangd
- dependency files `*o.d`, used by object files
- LLVM and GNU coverage files: `*.profraw`, `*.gcda` and `*.gcno`
* 🔥 temporarily remove problematic expandSnippet import
* 👷 add npx to prefix vsce in build
* 🐛 handle messages sent in multiple parts over stdin
* 🔖 update gradle version
* 🩹 for now, skip onboarding in jetbrains
* 🩹 temporarily don't show use codebase on jetbrains
* 🐛 use system certificates in binary
* 🔖 update jetbrains version
* 🩹 correctly contruct set of certs
* 🔖 bump intellij version to 0.0.45
* 🩹 update to support images for gpt-4-turbo
* 🐛 fix image support autodetection
* ⚡️ again, improve image support autodetection
* 🐛 set supportsCompletions based on useLegacyCompletionsEndpoint model setting
Closes #1132
* 📝 useLegacyCompletionsEndpoint within OpenAI docs
* 🔧 forceCompletionsEndpointType option
* Revert "🔧 forceCompletionsEndpointType option"
This reverts commit dd51fcbb7f.
* 🩹 set default useLegacyCompletionsEndpoint to undefined
* 🩹 look for bedrock credentials in homedir
* 🩹 use title for autodetect
* ✨ disableInFiles option for autocomplete
* feat(httpContextProvider): load AC on fetch client (#1150)
Co-authored-by: Bertrand Pinel <bertrand.pinel@pole-emploi.fr>
* ✨ global filewatcher for config.json/ts changes
* 🐛 retry webview requests so that first cmd+L works
* ✨ Improved onboarding experience (#1155)
* 🚸 onboarding improvements
* 🧑💻 keyboard shortcuts to toggle autocomplete and open config.json
* ⚡️ improve detection of terminal code blocks
* 🚧 onboarding improvements
* 🚧 more onboarding improvements
* 💄 last session button
* 🚸 show more fallback options in dropdown
* 💄 add sectioning to models page
* 💄 clean up delete model button
* 💄 make tooltip look nicer
* 🚸 download Ollama button
* 💄 local LLM onboarding
* 🐛 select correct terminal on "runCommand" message
* 💄 polish onboarding
* 💚 fix gui build errors
* 📝 add /v1 to OpenAI examples in docs
* 🚑 hotfix for not iterable error
* 💄 add llama3 to UI
* 🔥 remove disable indexing
* 🍱 update continue logo
* 🐛 fix language undefined bug
---------
Signed-off-by: inimaz <93inigo93@gmail.com>
Co-authored-by: Nithish <nithishmohandass06@gmail.com>
Co-authored-by: EC2 Default User <ec2-user@ip-172-31-2-149.ec2.internal>
Co-authored-by: LapinMalin <111463204+TheLapinMalin@users.noreply.github.com>
Co-authored-by: Justin Milner <42585006+justinmilner1@users.noreply.github.com>
Co-authored-by: Justin Milner <jmilner@jmilner-lt2.deka.local>
Co-authored-by: lmaosweqf1 <138042737+lmaosweqf1@users.noreply.github.com>
Co-authored-by: ading2210 <71154407+ading2210@users.noreply.github.com>
Co-authored-by: Martin Mois <martin.mois@googlemail.com>
Co-authored-by: Tobias Jung <102594442+tobiajung@users.noreply.github.com>
Co-authored-by: Jason Jacobs <nerfnerd@gmail.com>
Co-authored-by: Nithish <83941930+Nithishvb@users.noreply.github.com>
Co-authored-by: Ty Dunn <ty@tydunn.com>
Co-authored-by: Riccardo Schirone <riccardo.schirone@trailofbits.com>
Co-authored-by: postmasters <namnguyen@google.com>
Co-authored-by: Maxime Brunet <max@brnt.mx>
Co-authored-by: inimaz <49730431+inimaz@users.noreply.github.com>
Co-authored-by: SR_team <me@sr.team>
Co-authored-by: Roger Meier <r.meier@siemens.com>
Co-authored-by: Bertrand P <49525332+Berber31@users.noreply.github.com>
Co-authored-by: Bertrand Pinel <bertrand.pinel@pole-emploi.fr>
500 lines
14 KiB
TypeScript
500 lines
14 KiB
TypeScript
import Handlebars from "handlebars";
|
|
import ignore from "ignore";
|
|
import path from "path";
|
|
import { v4 as uuidv4 } from "uuid";
|
|
import { IDE, ILLM, Position, TabAutocompleteOptions } from "..";
|
|
import { RangeInFileWithContents } from "../commands/util";
|
|
import { ConfigHandler } from "../config/handler";
|
|
import { streamLines } from "../diff/util";
|
|
import OpenAI from "../llm/llms/OpenAI";
|
|
import { getBasename } from "../util";
|
|
import { logDevData } from "../util/devdata";
|
|
import { DEFAULT_AUTOCOMPLETE_OPTS } from "../util/parameters";
|
|
import { Telemetry } from "../util/posthog";
|
|
import { getRangeInString } from "../util/ranges";
|
|
import AutocompleteLruCache from "./cache";
|
|
import { noFirstCharNewline, onlyWhitespaceAfterEndOfLine } from "./charStream";
|
|
import {
|
|
constructAutocompletePrompt,
|
|
languageForFilepath,
|
|
} from "./constructPrompt";
|
|
import { AutocompleteLanguageInfo } from "./languages";
|
|
import {
|
|
avoidPathLine,
|
|
noTopLevelKeywordsMidline,
|
|
stopAtLines,
|
|
stopAtRepeatingLines,
|
|
stopAtSimilarLine,
|
|
streamWithNewLines,
|
|
} from "./lineStream";
|
|
import { AutocompleteSnippet } from "./ranking";
|
|
import { getTemplateForModel } from "./templates";
|
|
import { GeneratorReuseManager } from "./util";
|
|
|
|
export interface AutocompleteInput {
|
|
completionId: string;
|
|
filepath: string;
|
|
pos: Position;
|
|
recentlyEditedFiles: RangeInFileWithContents[];
|
|
recentlyEditedRanges: RangeInFileWithContents[];
|
|
clipboardText: string;
|
|
}
|
|
|
|
export interface AutocompleteOutcome extends TabAutocompleteOptions {
|
|
accepted?: boolean;
|
|
time: number;
|
|
prompt: string;
|
|
completion: string;
|
|
modelProvider: string;
|
|
modelName: string;
|
|
completionOptions: any;
|
|
cacheHit: boolean;
|
|
}
|
|
|
|
const autocompleteCache = AutocompleteLruCache.get();
|
|
|
|
const DOUBLE_NEWLINE = "\n\n";
|
|
const WINDOWS_DOUBLE_NEWLINE = "\r\n\r\n";
|
|
const SRC_DIRECTORY = "/src/";
|
|
// Starcoder2 tends to output artifacts starting with the letter "t"
|
|
const STARCODER2_T_ARTIFACTS = ["t.", "\nt"];
|
|
const PYTHON_ENCODING = "#- coding: utf-8";
|
|
const CODE_BLOCK_END = "```";
|
|
|
|
const multilineStops = [DOUBLE_NEWLINE, WINDOWS_DOUBLE_NEWLINE];
|
|
const commonStops = [SRC_DIRECTORY, PYTHON_ENCODING, CODE_BLOCK_END];
|
|
|
|
function formatExternalSnippet(
|
|
filepath: string,
|
|
snippet: string,
|
|
language: AutocompleteLanguageInfo,
|
|
) {
|
|
const comment = language.comment;
|
|
const lines = [
|
|
comment + " Path: " + getBasename(filepath),
|
|
...snippet
|
|
.trim()
|
|
.split("\n")
|
|
.map((line) => comment + " " + line),
|
|
comment,
|
|
];
|
|
return lines.join("\n");
|
|
}
|
|
|
|
let shownGptClaudeWarning = false;
|
|
|
|
export async function getTabCompletion(
|
|
token: AbortSignal,
|
|
options: TabAutocompleteOptions,
|
|
llm: ILLM,
|
|
ide: IDE,
|
|
generatorReuseManager: GeneratorReuseManager,
|
|
input: AutocompleteInput,
|
|
getDefinitionsFromLsp: (
|
|
filepath: string,
|
|
contents: string,
|
|
cursorIndex: number,
|
|
ide: IDE,
|
|
) => Promise<AutocompleteSnippet[]>,
|
|
): Promise<AutocompleteOutcome | undefined> {
|
|
const startTime = Date.now();
|
|
|
|
const {
|
|
filepath,
|
|
pos,
|
|
recentlyEditedFiles,
|
|
recentlyEditedRanges,
|
|
clipboardText,
|
|
} = input;
|
|
const fileContents = await ide.readFile(filepath);
|
|
const fileLines = fileContents.split("\n");
|
|
|
|
// Filter
|
|
const lang = languageForFilepath(filepath);
|
|
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 !== "starcoder-7b"
|
|
) {
|
|
throw new Error(
|
|
"The only free trial model supported for tab-autocomplete is starcoder-7b.",
|
|
);
|
|
}
|
|
|
|
if (
|
|
!shownGptClaudeWarning &&
|
|
(llm.model.includes("gpt") || llm.model.includes("claude"))
|
|
) {
|
|
shownGptClaudeWarning = true;
|
|
throw new Error(
|
|
`Warning: ${llm.model} is not trained for tab-autocomplete, and will result in low-quality suggestions. See the docs to learn more about why: https://continue.dev/docs/walkthroughs/tab-autocomplete#i-want-better-completions-should-i-use-gpt-4`,
|
|
);
|
|
}
|
|
|
|
// Prompt
|
|
const fullPrefix = getRangeInString(fileContents, {
|
|
start: { line: 0, character: 0 },
|
|
end: pos,
|
|
});
|
|
const fullSuffix = getRangeInString(fileContents, {
|
|
start: pos,
|
|
end: { line: fileLines.length - 1, character: Number.MAX_SAFE_INTEGER },
|
|
});
|
|
const lineBelowCursor =
|
|
fileLines[Math.min(pos.line + 1, fileLines.length - 1)];
|
|
|
|
let extrasSnippets = (await Promise.race([
|
|
getDefinitionsFromLsp(
|
|
filepath,
|
|
fullPrefix + fullSuffix,
|
|
fullPrefix.length,
|
|
ide,
|
|
),
|
|
new Promise((resolve) => {
|
|
setTimeout(() => resolve([]), 100);
|
|
}),
|
|
])) as AutocompleteSnippet[];
|
|
|
|
const workspaceDirs = await 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,
|
|
);
|
|
|
|
// Template prompt
|
|
const { template, completionOptions } = options.template
|
|
? { template: options.template, completionOptions: {} }
|
|
: getTemplateForModel(llm.model);
|
|
|
|
let prompt: string;
|
|
const filename = getBasename(filepath);
|
|
const reponame = getBasename(workspaceDirs[0] ?? "myproject");
|
|
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;
|
|
}
|
|
|
|
prompt = compiledTemplate({
|
|
prefix,
|
|
suffix,
|
|
filename,
|
|
reponame,
|
|
});
|
|
} else {
|
|
// Let the template function format snippets
|
|
prompt = template(prefix, suffix, filename, reponame, snippets);
|
|
}
|
|
|
|
// Completion
|
|
let completion = "";
|
|
|
|
const cache = await autocompleteCache;
|
|
const cachedCompletion = options.useCache
|
|
? await cache.get(prompt)
|
|
: undefined;
|
|
let cacheHit = false;
|
|
if (cachedCompletion) {
|
|
// Cache
|
|
cacheHit = true;
|
|
completion = cachedCompletion;
|
|
} else {
|
|
let stop = [
|
|
...(completionOptions?.stop || []),
|
|
...multilineStops,
|
|
...commonStops,
|
|
...(llm.model.toLowerCase().includes("starcoder2")
|
|
? STARCODER2_T_ARTIFACTS
|
|
: []),
|
|
...lang.stopWords,
|
|
];
|
|
|
|
const multiline =
|
|
options.multilineCompletions !== "never" &&
|
|
(options.multilineCompletions === "always" || completeMultiline);
|
|
|
|
// Try to reuse pending requests if what the user typed matches start of completion
|
|
let generator = generatorReuseManager.getGenerator(
|
|
prefix,
|
|
() =>
|
|
llm.streamComplete(prompt, {
|
|
...completionOptions,
|
|
raw: true,
|
|
stop,
|
|
}),
|
|
multiline,
|
|
);
|
|
|
|
// 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();
|
|
charGenerator = noFirstCharNewline(charGenerator);
|
|
charGenerator = onlyWhitespaceAfterEndOfLine(charGenerator, lang.endOfLine);
|
|
|
|
let lineGenerator = streamLines(charGenerator);
|
|
lineGenerator = stopAtLines(lineGenerator);
|
|
lineGenerator = stopAtRepeatingLines(lineGenerator);
|
|
lineGenerator = avoidPathLine(lineGenerator, lang.comment);
|
|
lineGenerator = noTopLevelKeywordsMidline(lineGenerator, lang.stopWords);
|
|
lineGenerator = streamWithNewLines(lineGenerator);
|
|
|
|
const finalGenerator = stopAtSimilarLine(lineGenerator, lineBelowCursor);
|
|
for await (const update of finalGenerator) {
|
|
completion += update;
|
|
}
|
|
|
|
if (cancelled) {
|
|
return undefined;
|
|
}
|
|
|
|
// Don't return empty
|
|
if (completion.trim().length <= 0) {
|
|
return undefined;
|
|
}
|
|
|
|
// Post-processing
|
|
completion = completion.trimEnd();
|
|
}
|
|
|
|
const time = Date.now() - startTime;
|
|
return {
|
|
time,
|
|
completion,
|
|
prompt,
|
|
modelProvider: llm.providerName,
|
|
modelName: llm.model,
|
|
completionOptions,
|
|
cacheHit,
|
|
...options,
|
|
};
|
|
}
|
|
|
|
export class CompletionProvider {
|
|
private static debounceTimeout: NodeJS.Timeout | undefined = undefined;
|
|
private static debouncing: boolean = false;
|
|
private static lastUUID: string | undefined = undefined;
|
|
|
|
constructor(
|
|
private readonly configHandler: ConfigHandler,
|
|
private readonly ide: IDE,
|
|
private readonly getLlm: () => Promise<ILLM | undefined>,
|
|
private readonly _onError: (e: any) => void,
|
|
private readonly getDefinitionsFromLsp: (
|
|
filepath: string,
|
|
contents: string,
|
|
cursorIndex: number,
|
|
ide: IDE,
|
|
) => Promise<AutocompleteSnippet[]>,
|
|
) {
|
|
this.generatorReuseManager = new GeneratorReuseManager(
|
|
this.onError.bind(this),
|
|
);
|
|
}
|
|
|
|
private generatorReuseManager: GeneratorReuseManager;
|
|
private autocompleteCache = AutocompleteLruCache.get();
|
|
public errorsShown: Set<string> = new Set();
|
|
|
|
private onError(e: any) {
|
|
console.warn("Error generating autocompletion: ", e);
|
|
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();
|
|
}
|
|
|
|
private _abortControllers = new Map<string, AbortController>();
|
|
private _logRejectionTimeouts = new Map<string, NodeJS.Timeout>();
|
|
private _outcomes = new Map<string, AutocompleteOutcome>();
|
|
|
|
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);
|
|
Telemetry.capture("autocomplete", {
|
|
accepted: outcome.accepted,
|
|
modelName: outcome.modelName,
|
|
modelProvider: outcome.modelProvider,
|
|
time: outcome.time,
|
|
cacheHit: outcome.cacheHit,
|
|
});
|
|
this._outcomes.delete(completionId);
|
|
}
|
|
}
|
|
|
|
public async provideInlineCompletionItems(
|
|
input: AutocompleteInput,
|
|
token: AbortSignal | undefined,
|
|
): Promise<AutocompleteOutcome | undefined> {
|
|
try {
|
|
// Debounce
|
|
const uuid = uuidv4();
|
|
CompletionProvider.lastUUID = uuid;
|
|
|
|
const config = await this.configHandler.loadConfig();
|
|
const options = {
|
|
...DEFAULT_AUTOCOMPLETE_OPTS,
|
|
...config.tabAutocompleteOptions,
|
|
};
|
|
|
|
// 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) {
|
|
if (filepath.startsWith(workspaceDir)) {
|
|
filepath = path.relative(workspaceDir, filepath);
|
|
break;
|
|
}
|
|
}
|
|
|
|
// Worst case we can check filetype glob patterns
|
|
if (filepath === input.filepath) {
|
|
filepath = getBasename(filepath);
|
|
}
|
|
|
|
const pattern = ignore().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;
|
|
}
|
|
|
|
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;
|
|
}
|
|
|
|
// Set temperature (but don't overrride)
|
|
if (llm.completionOptions.temperature === undefined) {
|
|
llm.completionOptions.temperature = 0.01;
|
|
}
|
|
|
|
const outcome = await getTabCompletion(
|
|
token,
|
|
options,
|
|
llm,
|
|
this.ide,
|
|
this.generatorReuseManager,
|
|
input,
|
|
this.getDefinitionsFromLsp,
|
|
);
|
|
const completion = outcome?.completion;
|
|
|
|
if (!completion) {
|
|
return undefined;
|
|
}
|
|
|
|
// Do some stuff later so as not to block return. Latency matters
|
|
setTimeout(async () => {
|
|
if (!outcome.cacheHit) {
|
|
(await this.autocompleteCache).put(outcome.prompt, completion);
|
|
}
|
|
}, 100);
|
|
|
|
outcome.accepted = false;
|
|
const logRejectionTimeout = setTimeout(() => {
|
|
// Wait 10 seconds, then assume it wasn't accepted
|
|
logDevData("autocomplete", outcome);
|
|
const { prompt, completion, ...restOfOutcome } = outcome;
|
|
Telemetry.capture("autocomplete", {
|
|
...restOfOutcome,
|
|
});
|
|
this._logRejectionTimeouts.delete(input.completionId);
|
|
}, 10_000);
|
|
this._outcomes.set(input.completionId, outcome);
|
|
this._logRejectionTimeouts.set(input.completionId, logRejectionTimeout);
|
|
|
|
return outcome;
|
|
} catch (e: any) {
|
|
this.onError(e);
|
|
} finally {
|
|
this._abortControllers.delete(input.completionId);
|
|
}
|
|
}
|
|
}
|