Merge branch 'dev' into fix-code-context-meta-parsing

This commit is contained in:
Nate 2024-11-08 16:29:38 -08:00
commit 6ce81bb0cf
433 changed files with 16112 additions and 14811 deletions

View file

@ -0,0 +1,9 @@
## 0.8.55 - 2024-10-25
### Added
* Web context provider
* Cerebras inference provider
* Automatic descriptions for previous chats
* Discord context provider
* Improved full screen UI
### Changed
* Easier way to accept/reject/re-prompt after cmd/ctrl+I

View file

@ -1,4 +0,0 @@
project: extensions/vscode
kind: Added
body: Web context provider
time: 2024-10-14T23:15:51.670444-07:00

View file

@ -1,4 +0,0 @@
project: extensions/vscode
kind: Added
body: Cerebras inference provider
time: 2024-10-14T23:16:22.754491-07:00

View file

@ -1,4 +0,0 @@
project: extensions/vscode
kind: Added
body: Automatic descriptions for previous chats
time: 2024-10-14T23:16:39.451261-07:00

View file

@ -1,4 +0,0 @@
project: extensions/vscode
kind: Added
body: Discord context provider
time: 2024-10-14T23:16:57.089953-07:00

View file

@ -1,4 +0,0 @@
project: extensions/vscode
kind: Added
body: Improved full screen UI
time: 2024-10-14T23:17:14.574917-07:00

View file

@ -0,0 +1,4 @@
project: extensions/vscode
kind: Added
body: New Edit mode in sidebar (cmd/ctrl+I)
time: 2024-11-02T00:27:24.40964-07:00

View file

@ -0,0 +1,4 @@
project: extensions/vscode
kind: Added
body: Significantly faster and more accurate docs crawler by default
time: 2024-11-02T00:27:44.408045-07:00

View file

@ -0,0 +1,4 @@
project: extensions/vscode
kind: Added
body: OpenAI predicted outputs support
time: 2024-11-08T11:39:42.277047-08:00

View file

@ -0,0 +1,4 @@
project: extensions/vscode
kind: Added
body: Improve codebase retrieval with BM25
time: 2024-11-08T11:41:00.002716-08:00

View file

@ -0,0 +1,4 @@
project: extensions/vscode
kind: Added
body: Support for Grok from xAI
time: 2024-11-08T11:44:23.761084-08:00

View file

@ -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

View file

@ -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

View file

@ -0,0 +1,4 @@
project: extensions/vscode
kind: Added
body: Support for Nebius LLM provider
time: 2024-11-08T11:46:12.94828-08:00

View file

@ -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

View file

@ -0,0 +1,4 @@
project: extensions/vscode
kind: Added
body: Improved reference for config.json
time: 2024-11-08T11:46:49.648545-08:00

View file

@ -0,0 +1,4 @@
project: extensions/vscode
kind: Added
body: New @web context provider
time: 2024-11-08T11:47:53.447346-08:00

View file

@ -0,0 +1,4 @@
project: extensions/vscode
kind: Added
body: Updates for llama3.2
time: 2024-11-08T11:48:13.830692-08:00

View file

@ -1,4 +0,0 @@
project: extensions/vscode
kind: Changed
body: Easier way to accept/reject/re-prompt after cmd/ctrl+I
time: 2024-10-14T23:17:38.086964-07:00

View file

@ -0,0 +1,4 @@
project: extensions/vscode
kind: Changed
body: Improved @docs crawler
time: 2024-11-08T11:45:49.381554-08:00

View file

@ -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

View file

@ -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

View file

@ -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

View file

@ -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

36
.eslintrc.shared.json Normal file
View file

@ -0,0 +1,36 @@
{
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 6,
"sourceType": "module"
},
"plugins": ["@typescript-eslint", "import"],
"rules": {
"@typescript-eslint/semi": "warn",
"curly": "warn",
"eqeqeq": "warn",
"no-throw-literal": "warn",
"semi": "off",
"import/order": [
"warn",
{
"groups": [
"builtin",
"external",
"internal",
"parent",
"sibling",
"index",
"object",
"type"
],
"alphabetize": {
"order": "asc",
"caseInsensitive": true
},
"newlines-between": "always"
}
]
},
"ignorePatterns": ["out", "dist", "**/*.d.ts"]
}

View file

@ -4,8 +4,8 @@
## Checklist
- [ ] The base branch of this PR is `dev`, rather than `main`
- [ ] The relevant docs, if any, have been updated or created
- [] The base branch of this PR is `dev`, rather than `main`
- [] The relevant docs, if any, have been updated or created
## Screenshots

View file

@ -16,3 +16,9 @@ jobs:
repo-token: ${{ secrets.CI_GITHUB_TOKEN }}
assignees: sestinj,Patrick-Erichsen
numOfAssignee: 1
- name: "Add default labels"
uses: actions-ecosystem/action-add-labels@v1
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
labels: |
"needs-triage"

View file

@ -20,6 +20,12 @@ jobs:
with:
node-version-file: ".nvmrc"
- name: Cache root node_modules
uses: actions/cache@v3
with:
path: node_modules
key: ${{ runner.os }}-node-${{ hashFiles('package-lock.json') }}
- name: Cache extension node_modules
uses: actions/cache@v3
with:
@ -44,6 +50,10 @@ jobs:
path: binary/node_modules
key: ${{ runner.os }}-node-${{ hashFiles('binary/package-lock.json') }}
- name: root install
run: |
npm ci
- name: extensions/vscode install
run: |
cd extensions/vscode
@ -71,6 +81,7 @@ jobs:
run: |
cd extensions/vscode
npx tsc --noEmit
npm run lint
- name: core checks
run: |

View file

@ -97,7 +97,6 @@ jobs:
with:
node-version-file: ".nvmrc"
# Cache node_modules
- name: Cache core node_modules
uses: actions/cache@v3
with:

View file

@ -255,11 +255,3 @@ jobs:
# with:
# github_token: ${{ secrets.GITHUB_TOKEN }}
# branch: ${{ github.ref }}
# 5 Send to Discord Webhook
- name: Discord Commits
uses: Sniddl/discord-commits@1.7
with:
webhook: ${{ secrets.DISCORD_WEBHOOK }}
template: "avatar-with-link"
include-extras: true

View file

@ -21,6 +21,12 @@ jobs:
with:
node-version-file: ".nvmrc"
- name: Cache root node_modules
uses: actions/cache@v3
with:
path: node_modules
key: ${{ runner.os }}-node-${{ hashFiles('package-lock.json') }}
- name: Cache extension node_modules
uses: actions/cache@v3
with:
@ -45,6 +51,10 @@ jobs:
path: binary/node_modules
key: ${{ runner.os }}-node-${{ hashFiles('binary/package-lock.json') }}
- name: Install Root Dependencies
run: |
npm ci
- name: Install extension Dependencies
run: |
cd extensions/vscode
@ -72,11 +82,13 @@ jobs:
run: |
cd core
npx tsc --noEmit
npm run lint
- name: tsc extensions/vscode
run: |
cd extensions/vscode
npx tsc --noEmit
npm run lint
- name: tsc binary
run: |

3
.gitignore vendored
View file

@ -166,3 +166,6 @@ extensions/intellij/.idea/**
**/.idea/workspace.xml
**/.idea/usage.statistics.xml
**/.idea/shelf/
extensions/intellij/bin
extensions/.continue-debug/

2
.idea/.name generated
View file

@ -1 +1 @@
Continue IntelliJ Extension
continue-intellij-extension

9
.idea/continue.iml generated Normal file
View file

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

2
.idea/misc.xml generated
View file

@ -4,7 +4,7 @@
<component name="FrameworkDetectionExcludesConfiguration">
<file type="web" url="file://$PROJECT_DIR$/extensions/intellij" />
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_17" project-jdk-name="19" project-jdk-type="JavaSDK" />
<component name="ProjectRootManager" version="2" languageLevel="JDK_17" default="true" project-jdk-name="17" project-jdk-type="JavaSDK" />
<component name="SuppressKotlinCodeStyleNotification">
<option name="disableForAll" value="true" />
</component>

4
.idea/modules.xml generated
View file

@ -2,9 +2,7 @@
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/modules/com.github.continuedev.continueintellijextension.continue-intellij-extension.iml" filepath="$PROJECT_DIR$/.idea/modules/com.github.continuedev.continueintellijextension.continue-intellij-extension.iml" />
<module fileurl="file://$PROJECT_DIR$/.idea/modules/com.github.continuedev.continueintellijextension.continue-intellij-extension.main.iml" filepath="$PROJECT_DIR$/.idea/modules/com.github.continuedev.continueintellijextension.continue-intellij-extension.main.iml" />
<module fileurl="file://$PROJECT_DIR$/.idea/modules/com.github.continuedev.continueintellijextension.continue-intellij-extension.test.iml" filepath="$PROJECT_DIR$/.idea/modules/com.github.continuedev.continueintellijextension.continue-intellij-extension.test.iml" />
<module fileurl="file://$PROJECT_DIR$/.idea/continue.iml" filepath="$PROJECT_DIR$/.idea/continue.iml" />
</modules>
</component>
</project>

View file

@ -1,3 +1,3 @@
<component name="DependencyValidationManager">
<scope name="Continue" pattern="!file[com.github.continuedev.continueintellijextension.continue-intellij-extension]:gui/dist//*&amp;&amp;!file[com.github.continuedev.continueintellijextension.continue-intellij-extension]:extensions/vscode/gui//*&amp;&amp;!file[com.github.continuedev.continueintellijextension.continue-intellij-extension]:core/vendor//*" />
<scope name="Continue" pattern="file[continue-intellij-extension]:*/&amp;&amp;!file[continue-intellij-extension]:binary/bin//*&amp;&amp;!file[continue-intellij-extension]:binary/build//*&amp;&amp;!file[continue-intellij-extension]:binary/out//*&amp;&amp;!file[continue-intellij-extension]:gui/dist//*&amp;&amp;!file[continue-intellij-extension]:extensions/intellij/build//*&amp;&amp;!file[continue-intellij-extension]:extensions/vscode/bin//*&amp;&amp;!file[continue-intellij-extension]:extensions/vscode/build//*&amp;&amp;!file[continue-intellij-extension]:extensions/vscode/out//*" />
</component>

View file

@ -2,5 +2,8 @@
"tabWidth": 2,
"useTabs": false,
"trailingComma": "all",
"semi": true,
"singleQuote": false,
"bracketSpacing": true,
"plugins": ["prettier-plugin-tailwindcss"]
}

View file

@ -1,19 +0,0 @@
temperature: 0.5
maxTokens: 4096
name: jest
description: Write Jest unit tests
---
<system>
You are an expert programmer
</system>
{{{ input }}}
Write unit tests for the above selected code, following each of these instructions:
- Use `jest`
- Properly set up and tear down
- Include important edge cases
- The tests should be complete and sophisticated
- Give the tests just as chat output, don't edit any file
- Don't explain how to set up `jest`
- Write a single code block, making sure to label with the language being used (e.g. "```typscript")

26
.vscode/launch.json vendored
View file

@ -20,7 +20,10 @@
"outFiles": ["${workspaceFolder}/extensions/vscode/out/extension.js"],
"preLaunchTask": "vscode-extension:build",
"env": {
"CONTROL_PLANE_ENV": "local"
"CONTINUE_GLOBAL_DIR": "${workspaceFolder}/extensions/.continue-debug"
// "staging" for the preview deployment "CONTINUE_GLOBAL_DIR": "${workspaceFolder}/extensions/.continue-debug"
// "local" for entirely local development of control plane/proxy
// "CONTROL_PLANE_ENV": "staging"
}
},
{
@ -36,7 +39,7 @@
"cwd": "${workspaceFolder}/binary",
"env": {
"CONTINUE_DEVELOPMENT": "true",
"CONTINUE_GLOBAL_DIR": "${workspaceFolder}/binary/.continue"
"CONTINUE_GLOBAL_DIR": "${workspaceFolder}/extensions/.continue-debug"
}
},
{
@ -135,24 +138,5 @@
"NODE_OPTIONS": "--experimental-vm-modules"
}
}
// {
// "name": "[openai-adapters] Jest Test Debugger, Current Open File",
// "type": "node",
// "request": "launch",
// "runtimeArgs": [
// "--inspect-brk",
// "${workspaceRoot}/packages/openai-adapters/node_modules/jest/bin/jest.js",
// "--runInBand",
// "--config",
// "${workspaceRoot}/packages/openai-adapters/jest.config.mjs",
// "${relativeFile}"
// ],
// "cwd": "${workspaceRoot}/packages/openai-adapters",
// "console": "integratedTerminal",
// "internalConsoleOptions": "neverOpen",
// "env": {
// "NODE_OPTIONS": "--experimental-vm-modules"
// }
// }
]
}

24
.vscode/settings.json vendored
View file

@ -14,10 +14,26 @@
}
},
"search.exclude": {
"**/core/vendor/**": true,
"**/gui/dist": true,
"**/extensions/vscode/gui/**": true,
"**/extensions/vscode/out/**": true
"**/package-lock.json": true,
"binary/bin/**": true,
"binary/build/**": true,
"binary/out/**": true,
"binary/tmp/**": true,
"core/llm/llamaTokenizer.js": true,
"core/llm/llamaTokenizer.mjs": true,
"core/vendor/**": true,
"docs/.docusaurus/**": true,
"extensions/intellij/build/**": true,
"extensions/vscode/bin/**": true,
"extensions/vscode/build/**": true,
"extensions/vscode/gui/**": true,
"extensions/vscode/models/all-MiniLM-L6-v2/**": true,
"extensions/vscode/out/**": true,
"extensions/vscode/tag-qry/**": true,
"extensions/vscode/textmate-syntaxes/**": true,
"extensions/vscode/tree-sitter/**": true,
"gui/dist/**": true
// "sync/**": true
},
"eslint.workingDirectories": ["./core"]
}

4
.vscode/tasks.json vendored
View file

@ -9,7 +9,7 @@
"vscode-extension:tsc",
// To build the React app that is used in the extension
"vscode-extension:continue-ui:build",
// To bundle the code the same way we do for publishing
// // To bundle the code the same way we do for publishing
"vscode-extension:esbuild",
// Start the React app that is used in the extension
"gui:dev"
@ -41,7 +41,7 @@
"background": {
"activeOnStart": true,
"beginsPattern": ">",
"endsPattern": ">"
"endsPattern": "VS Code Extension esbuild complete"
}
}
]

View file

@ -200,10 +200,9 @@ Continue has support for more than a dozen different LLM "providers", making it
While any model that works with a supported provider can be used with Continue, we keep a list of recommended models that can be automatically configured from the UI or `config.json`. The following files should be updated when adding a model:
- [config_schema.json](./extensions/vscode/config_schema.json) - This is the JSON Schema definition that is used to validate `config.json`. You'll notice a number of rules defined in "definitions.ModelDescription.allOf". Here is where you write rules that can specify something like "for the provider 'anthropic', only models 'claude-2' and 'claude-instant-1' are allowed. Look through all of these rules and make sure that your model is included for providers that support it.
- [modelData.ts](./gui/src/util/modelData.ts) - This file defines that information that is shown in the model selection UI in the side bar. To add a new model:
1. create a `ModelPackage` object, following the lead of the many examples near the top of the file
2. add the `ModelPackage` to the `MODEL_INFO` array if you would like it to be displayed in the "Models" tab
3. if you would like it to be displayed as an option under any of the providers, go to the `PROVIDER_INFO` object and add it to the `packages` array for each provider that you want it to be displayed under. If it is an OS model that should be valid for most providers offering OS models, you might just be able to add it to the `osModels` array as shorthand.
- [AddNewModel page](./gui/src/pages/AddNewModel) - This directory defines which model options are shown in the side bar model selection UI. To add a new model:
1. Add a `ModelPackage` entry for the model into [configs/models.ts](./gui/src/pages/AddNewModel/configs/models.ts), following the lead of the many examples near the top of the file
2. Add the model within its provider's array to [AddNewModel.tsx](./gui/src/pages/AddNewModel/AddNewModel.tsx) (add provider if needed)
- [index.d.ts](./core/index.d.ts) - This file defines the TypeScript types used throughout Continue. You'll find a `ModelName` type. Be sure to add the name of your model to this.
- LLM Providers: Since many providers use their own custom strings to identify models, you'll have to add the translation from Continue's model name (the one you added to `index.d.ts`) and the model string for each of these providers: [Ollama](./core/llm/llms/Ollama.ts), [Together](./core/llm/llms/Together.ts), and [Replicate](./core/llm/llms/Replicate.ts). You can find their full model lists here: [Ollama](https://ollama.ai/library), [Together](https://docs.together.ai/docs/inference-models), [Replicate](https://replicate.com/collections/streaming-language-models).
- [Prompt Templates](./core/llm/index.ts) - In this file you'll find the `autodetectTemplateType` function. Make sure that for the model name you just added, this function returns the correct template type. This is assuming that the chat template for that model is already built in Continue. If not, you will have to add the template type and corresponding edit and chat templates.

View file

@ -47,12 +47,11 @@
"@aws-sdk/client-bedrock-runtime": "^3.620.1",
"@aws-sdk/client-sagemaker-runtime": "^3.621.0",
"@aws-sdk/credential-providers": "^3.620.1",
"@continuedev/config-types": "^1.0.10",
"@continuedev/config-types": "^1.0.13",
"@continuedev/llm-info": "^1.0.2",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.0.2",
"@typescript-eslint/eslint-plugin": "^7.8.0",
"@typescript-eslint/parser": "^7.8.0",
"@xenova/transformers": "2.14.0",
"adf-to-md": "^1.1.0",
"async-mutex": "^0.5.0",
@ -124,7 +123,6 @@
"cross-env": "^7.0.3",
"esbuild": "0.17.19",
"eslint": "^8",
"eslint-plugin-import": "^2.29.1",
"jest": "^29.7.0",
"jest-environment-jsdom": "^29.7.0",
"myers-diff": "^2.1.0",

View file

@ -1,21 +1,12 @@
{
"root": true,
"parser": "@typescript-eslint/parser",
"extends": ["../.eslintrc.shared.json"],
"parserOptions": {
"ecmaVersion": 6,
"sourceType": "module",
"project": "./tsconfig.json"
},
"plugins": ["@typescript-eslint", "import"],
"rules": {
"quotes": ["warn", "double", {}],
"@typescript-eslint/naming-convention": "off",
"@typescript-eslint/semi": "warn",
"curly": "warn",
"eqeqeq": "warn",
"no-throw-literal": "warn",
"semi": "off",
"@typescript-eslint/no-floating-promises": "warn"
},
"ignorePatterns": ["out", "dist", "**/*.d.ts"]
}
}

View file

@ -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<AutocompleteSnippet[]>;
export class CompletionProvider {
private autocompleteCache = AutocompleteLruCache.get();
public errorsShown: Set<string> = 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<ILLM | undefined>,
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<ILLM | undefined> {
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<AutocompleteOutcome | undefined> {
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<AutocompleteSnippet[]> {
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;
}
}

View file

@ -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,
},
};
}),
);
}
}

View file

@ -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

View file

@ -120,7 +120,7 @@ This object allows you to customize the behavior of tab-autocomplete. The availa
### I want better completions, should I use GPT-4?
Perhaps surprisingly, the answer is no. The models that we suggest for autocomplete are trained with a highly specific prompt format, which allows them to respond to requests for completing code (see examples of these prompts [here](https://github.com/continuedev/continue/blob/d2bc6359e8ebf647892ec953e418042dc7f8a685/core/autocomplete/templates.ts)). Some of the best commercial models like GPT-4 or Claude are not trained with this prompt format, which means that they won't generate useful completions. Luckily, a huge model is not required for great autocomplete. Most of the state-of-the-art autocomplete models are no more than 10b parameters, and increasing beyond this does not significantly improve performance.
Perhaps surprisingly, the answer is no. The models that we suggest for autocomplete are trained with a highly specific prompt format, which allows them to respond to requests for completing code (see examples of these prompts [here](https://github.com/continuedev/continue/blob/main/core/autocomplete/templates.ts)). Some of the best commercial models like GPT-4 or Claude are not trained with this prompt format, which means that they won't generate useful completions. Luckily, a huge model is not required for great autocomplete. Most of the state-of-the-art autocomplete models are no more than 10b parameters, and increasing beyond this does not significantly improve performance.
### I'm not seeing any completions

View file

@ -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,
);
}

View file

@ -1,783 +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,
noTopLevelKeywordsMidline,
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 {
noFirstCharNewline,
onlyWhitespaceAfterEndOfLine,
stopAtStopTokens,
} from "./streamTransforms/charStream.js";
export interface AutocompleteInput {
completionId: string;
filepath: string;
pos: Position;
recentlyEditedFiles: RangeInFileWithContents[];
recentlyEditedRanges: RecentlyEditedRange[];
clipboardText: string;
// Used for notebook files
manuallyPassFileContents?: string;
// Used for VS Code git commit input box
manuallyPassPrefix?: string;
selectedCompletionInfo?: {
text: string;
range: Range;
};
injectDetails?: string;
}
export interface AutocompleteOutcome extends TabAutocompleteOptions {
accepted?: boolean;
time: number;
prefix: string;
suffix: string;
prompt: string;
completion: string;
modelProvider: string;
modelName: string;
completionOptions: any;
cacheHit: boolean;
filepath: string;
gitRepo?: string;
completionId: string;
uniqueId: string;
}
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", "<file_sep>"];
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",
];
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");
}
let shownGptClaudeWarning = false;
const nonAutocompleteModels = [
// "gpt",
// "claude",
"mistral",
"instruct",
];
export type GetLspDefinitionsFunction = (
filepath: string,
contents: string,
cursorIndex: number,
ide: IDE,
lang: AutocompleteLanguageInfo,
) => Promise<AutocompleteSnippet[]>;
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<ILLM | undefined>,
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<string> = 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<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);
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<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 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) {
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);
}
// @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;
}
// Set model-specific options
const LOCAL_PROVIDERS: ModelProvider[] = [
"ollama",
"lmstudio",
"llama.cpp",
"llamafile",
"text-gen-webui",
];
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 (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, ...restOfOutcome } = outcome;
void Telemetry.capture(
"autocomplete",
{
...restOfOutcome,
},
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,
};
}
async getTabCompletion(
token: AbortSignal,
options: TabAutocompleteOptions,
llm: ILLM,
input: AutocompleteInput,
): Promise<AutocompleteOutcome | undefined> {
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);
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;
}
if (
!shownGptClaudeWarning &&
nonAutocompleteModels.some((model) => llm.model.includes(model)) &&
!llm.model.toLowerCase().includes("deepseek") &&
!llm.model.toLowerCase().includes("codestral")
) {
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://docs.continue.dev/features/tab-autocomplete#i-want-better-completions-should-i-use-gpt-4`,
);
}
// 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}`),
];
let langMultilineDecision = lang.useMultiline?.({ prefix, suffix });
let multiline: boolean = false;
if (langMultilineDecision) {
multiline = langMultilineDecision;
} else {
multiline =
!input.selectedCompletionInfo && // Only ever single-line if using intellisense selected value
options.multilineCompletions !== "never" &&
(options.multilineCompletions === "always" || 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();
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);
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 = streamWithNewLines(lineGenerator);
const finalGenerator = stopAtSimilarLine(
lineGenerator,
lineBelowCursor,
fullStop,
);
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 = postprocessCompletion({
completion,
prefix,
suffix,
llm,
});
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,
};
}
}

View file

@ -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;
}

View file

@ -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<AutocompleteSnippet[]> {
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;
}

View file

@ -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<AutocompleteSnippet[]> {
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),
);
});
}
}

View file

@ -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;

View file

@ -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<AutocompleteSnippet>[] {
const windowAroundCursor =
helper.fullPrefix.slice(
-helper.options.slidingWindowSize *
helper.options.slidingWindowPrefixPercentage,
) +
helper.fullSuffix.slice(
helper.options.slidingWindowSize *
(1 - helper.options.slidingWindowPrefixPercentage),
);
const snippets: Required<AutocompleteSnippet>[] = 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<AutocompleteSnippet>[],

View file

@ -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,

View file

@ -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"],
);
});
});

View file

@ -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<string, AutocompleteSnippet[]>({

View file

@ -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;
}
}

View file

@ -0,0 +1,11 @@
export interface Person {
firstName: string;
lastName: string;
age: number;
address: Address;
}
export interface Address {
street: string;
city: string;
}

View file

@ -1,4 +0,0 @@
export function isOnlyWhitespace(completion: string): boolean {
const whitespaceRegex = /^[\s]+$/;
return whitespaceRegex.test(completion);
}

View file

@ -84,9 +84,13 @@ export class BracketMatchingService {
// Add corresponding open brackets from suffix to stack
// because we overwrite them and the diff is displayed, and this allows something to be edited after that
for (let i = 0; i < suffix.length; i++) {
if (suffix[i] === " ") {continue;}
if (suffix[i] === " ") {
continue;
}
const openBracket = BracketMatchingService.BRACKETS_REVERSE[suffix[i]];
if (!openBracket) {break;}
if (!openBracket) {
break;
}
stack.unshift(openBracket);
}

View file

@ -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<string>,
prefix: string,
suffix: string,
multiline: boolean,
stopTokens: string[],
fullStop: () => void,
helper: HelperVars,
): AsyncGenerator<string> {
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;
}
}

View file

@ -1,4 +1,4 @@
import { stopAtStopTokens } from "./streamTransforms/charStream";
import { stopAtStopTokens } from "./charStream";
describe("stopAtStopTokens", () => {
async function* createMockStream(chunks: string[]): AsyncGenerator<string> {

View file

@ -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);",
]);
});
});

View file

@ -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<string>;
prefix: string;
suffix: string;
filepath: string;
multiline: boolean;
}) => AsyncGenerator<string>;
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: <PATH>' or empty comments.
* Filters out lines starting with '// Path: <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: <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;
}
}
}

View file

@ -0,0 +1,60 @@
##### Prompt #####
{
"active": true,
"department": "Product Development",
"location": {
"country": "USA",
"state": "California",
"city": "San BERNARDINO",
"coordinates": {
<FIM>
}
},
"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"]

View file

@ -0,0 +1,128 @@
##### Prompt #####
}`,
},
{
description: "Should autocomplete Vue computed property",
filename: "UserComponent.vue",
input: `<template>
<div>
<p>User Full Name: {{ fullName }}</p>
</div>
</template>
<script>
export default {
data() {
return {
firstName: 'John',
lastName: 'Doe',
};
},
computed: {
fullName<|fim|>
},
};
</script>
`,
llmOutput: `() {
return this.firstName + ' ' + this.lastName;
}`,
expectedCompletion: `() {
return this.firstName + ' ' + this.lastName;
}`,
},
{
description: "Should autocomplete Vue method using props",
filename: "TodoItem.vue",
input: `<template>
<li>
<p>{{ title }}</p>
<button @click="completeTodo">Complete</button>
</li>
</template>
<script>
export default {
props: {
title: String,
completed: Boolean,
},
methods: {
completeTodo() {
<|fim|> = true;
}
},
};
</script>
`,
llmOutput: `this.completed`,
expectedCompletion: `this.completed`,
},
{
description: "Should autocomplete Svelte reactive statement",
filename: "Counter.svelte",
input: `
<script>
let count = 0;
$: <|fim|>
function handleClick() {
count += 1;
}
</script>
<button on:click={handleClick}>
Clicked {count} times
</button>
`,
llmOutput: `doubledCount = count * 2`,
expectedCompletion: `doubledCount = count * 2`,
},
{
description: "Should autocomplete Svelte component inside HTML",
filename: "NestedComponent.svelte",
input: `
<script>
import ChildComponent from './ChildComponent.svelte';
</script>
<main>
<h1>Hello Svelte</h1>
<ChildComponent <|fim|> />
</main>
`,
llmOutput: `name="World"`,
expectedCompletion: `name="World"`,
},
{
description: "Should handle autocomplete in Svelte each block",
filename: "List.svelte",
input: `
<script>
let items = ["Apple", "Banana", "Cherry"];
</script>
<ul>
{#each items as item}
<li>{item}</li>
{/each<|fim|>
</ul>
`,
llmOutput: `}`,
expectedCompletion: `}`,
},
<FIM>
];
==========================================================================
==========================================================================
Completion:
export default {
components: {
ChildComponent,
},

View file

@ -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" }<FIM>
],
"active": true
}
==========================================================================
==========================================================================
Completion:
}
{
"employees": [
{ "name": "John Doe", "age": 30 },
{ "name": "Jane Smith", "age": 25 }

View file

@ -0,0 +1,29 @@
##### Prompt #####
class Calculator:
def __init__(self):
self.result = 0
def add(self, number):
self.result += number
return self
def divid<FIM>
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

View file

@ -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<FIM>
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

View file

@ -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::<f64>().unwrap();
println!("Please enter the second number:");
let num2 = read_input().parse::<f64>().unwrap();
let result = match operator.as_str() {
"+" => num1 + num2,
"-" => num1 - num2,
"*" => num1 * num2,
"/" => num1 / num2,
<FIM>
_ => {
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() {
"+" | "-" | "*" | "/" => (),

View file

@ -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);
},
);
});
});
});

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,75 @@
import fs from "node:fs";
import path from "node:path";
import Mock from "../../../llm/llms/Mock";
import { testConfigHandler, testIde } from "../../../test/util/fixtures";
import { CompletionProvider } from "../../CompletionProvider";
import { AutocompleteInput } from "../../util/types";
const FIM_DELIMITER = "<|fim|>";
function parseFimExample(text: string): { prefix: string; suffix: string } {
const [prefix, suffix] = text.split(FIM_DELIMITER);
return { prefix, suffix };
}
export interface AutocompleteFileringTestInput {
description: string;
filename: string;
input: string;
llmOutput: string;
expectedCompletion: string | null;
options?: {
only?: boolean;
};
}
export async function testAutocompleteFiltering(
test: AutocompleteFileringTestInput,
) {
const { prefix, suffix } = parseFimExample(test.input);
// Setup necessary objects
const llm = new Mock({
model: "mock",
});
llm.completion = test.llmOutput;
const ide = testIde;
const configHandler = testConfigHandler;
// Create a real file
const [workspaceDir] = await ide.getWorkspaceDirs();
const filepath = path.join(workspaceDir, test.filename);
fs.writeFileSync(filepath, test.input.replace(FIM_DELIMITER, ""));
// Prepare completion input and provider
const completionProvider = new CompletionProvider(
configHandler,
ide,
async () => llm,
() => {},
async () => [],
);
const line = prefix.split("\n").length - 1;
const character = prefix.split("\n")[line].length;
const autocompleteInput: AutocompleteInput = {
clipboardText: "",
completionId: "test-completion-id",
filepath,
pos: {
line,
character,
},
recentlyEditedFiles: [],
recentlyEditedRanges: [],
};
// Generate a completion
const result = await completionProvider.provideInlineCompletionItems(
autocompleteInput,
undefined,
);
// Ensure that we return the text that is wanted to be displayed
expect(result?.completion).toEqual(test.expectedCompletion);
}

View file

@ -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<CompletionOptions> | 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;
}
}
}

View file

@ -1,78 +1,4 @@
export class ListenableGenerator<T> {
private _source: AsyncGenerator<T>;
private _buffer: T[] = [];
private _listeners: Set<(value: T) => void> = new Set();
private _isEnded = false;
constructor(
source: AsyncGenerator<T>,
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<T> {
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<T>((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<string> | undefined;

View file

@ -0,0 +1,75 @@
export class ListenableGenerator<T> {
private _source: AsyncGenerator<T>;
private _buffer: T[] = [];
private _listeners: Set<(value: T) => void> = new Set();
private _isEnded = false;
constructor(
source: AsyncGenerator<T>,
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<T> {
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<T>((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!);
}
}
}

View file

@ -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);
}

View file

@ -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<boolean> {
// 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;
}

View file

@ -1,18 +0,0 @@
import { RangeInFile } from "../index.js";
export type RecentlyEditedRange = RangeInFile & {
timestamp: number;
lines: string[];
symbols: Set<string>;
};
export function findMatchingRange(
recentlyEditedRanges: RecentlyEditedRange[],
linePrefix: string,
): RecentlyEditedRange | undefined {
return recentlyEditedRanges.find((recentlyEditedRange) => {
return recentlyEditedRange.lines.some((line) =>
line.startsWith(linePrefix),
);
});
}

View file

@ -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<Chunk[]> {
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;
}

View file

@ -1,75 +0,0 @@
import { AstPath } from "./ast";
import { AutocompleteLanguageInfo } from "./languages";
const BLOCK_TYPES = ["body", "statement_block"];
function shouldCompleteMultilineAst(
treePath: AstPath,
cursorLine: number,
): boolean {
// If at the base of the file, do multiline
if (treePath.length === 1) {
return true;
}
// If at the first line of an otherwise empty funtion body, do multiline
for (let i = treePath.length - 1; i >= 0; i--) {
const node = treePath[i];
if (
BLOCK_TYPES.includes(node.type) &&
Math.abs(node.startPosition.row - cursorLine) <= 1
) {
let text = node.text;
text = text.slice(text.indexOf("{") + 1);
text = text.slice(0, text.lastIndexOf("}"));
text = text.trim();
return text.split("\n").length === 1;
}
}
return false;
}
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<boolean> {
// 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;
}
// First, if the line before ends with an opening bracket, then assume multi-line
if (
["{", "(", "["].includes(
fullPrefix.split("\n").slice(-2)[0]?.trim().slice(-1)[0],
)
) {
return true;
}
// Use AST to determine whether to complete multiline
let completeMultiline = false;
if (treePath) {
const cursorLine = fullPrefix.split("\n").length - 1;
completeMultiline = shouldCompleteMultilineAst(treePath, cursorLine);
}
return completeMultiline;
}

View file

@ -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,

View file

@ -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 };
}

View file

@ -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", "<file_sep>"];
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<CompletionOptions> | 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;
}

View file

@ -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<CompletionOptions> | 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 };
}

View file

@ -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<boolean> {
// 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;
}
}

View file

@ -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<string, AbortController>();
private _logRejectionTimeouts = new Map<string, NodeJS.Timeout>();
private _outcomes = new Map<string, AutocompleteOutcome>();
_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,
);
}
}

View file

@ -1,18 +1,17 @@
import { Mutex } from "async-mutex";
import { open } from "sqlite";
import sqlite3 from "sqlite3";
import { DatabaseConnection } 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();
db: DatabaseConnection;
constructor(db: DatabaseConnection) {
this.db = db;
}
constructor(private db: DatabaseConnection) {}
static async get(): Promise<AutocompleteLruCache> {
const db = await open({
@ -41,7 +40,7 @@ export class AutocompleteLruCache {
// Have to make sure we take the key with shortest length
const result = await this.db.get(
"SELECT key, value FROM cache WHERE ? LIKE key || '%' ORDER BY LENGTH(key) DESC LIMIT 1",
prefix,
truncateSqliteLikePattern(prefix),
);
// Validate that the cached compeltion is a valid completion for the prefix

View file

@ -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<HelperVars> {
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;
}
}

View file

@ -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[];

View file

@ -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<string>;
};
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;
}

View file

@ -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 {
@ -95,10 +95,10 @@ export async function getPromptParts(
}
let filePrefix = fullFileContentsList
.slice(curStartLine, maxStartLine)
.slice(curStartLine, maxStartLine - 1)
.join("\n");
let fileSuffix = fullFileContentsList
.slice(minEndLine, curEndLine - 1)
.slice(minEndLine, curEndLine + 1)
.join("\n");
if (rif.contents.length > 0) {

View file

@ -4,9 +4,10 @@ import CommitMessageCommand from "./commit";
import DraftIssueCommand from "./draftIssue";
import EditSlashCommand from "./edit";
import HttpSlashCommand from "./http";
import MultiFileEditSlashCommand from "./multifileEdit";
import OnboardSlashCommand from "./onboard";
import ReviewMessageCommand from "./review";
import ShareSlashCommand from "./share";
import OnboardSlashCommand from "./onboard";
export default [
DraftIssueCommand,
@ -18,4 +19,5 @@ export default [
CommitMessageCommand,
ReviewMessageCommand,
OnboardSlashCommand,
MultiFileEditSlashCommand,
];

View file

@ -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:
<example>
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]
</example>
Now, let's make the changes based on the engineer's request:
<input>
${input}
</input>
Here are the files to base your edits on:
<files>
${filesToEditStr}
</files>
And here is any additional context the engineer has provided:
<context>
${additionalContextStr}
</context>
Please provide the multi-file edit details based on the engineer's request.
`;
}
export default MultiFileEditSlashCommand;

Some files were not shown because too many files have changed in this diff Show more