Merge branch 'preview' into main

This commit is contained in:
Ashok Gelal 2024-03-17 18:59:56 -04:00 • committed by GitHub
commit 514609cff0
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
191 changed files with 13522 additions and 16492 deletions

View file

@ -0,0 +1,4 @@
## 0.0.38 - 2024-03-15
### Added
* Remote config server support
* Autocomplete support in JetBrains

View file

@ -1,211 +0,0 @@
name: Publish Extension
on:
push:
branches:
- main
jobs:
build:
strategy:
matrix:
include:
- os: windows-latest
platform: win32
arch: x64
npm_config_arch: x64
- os: windows-latest
platform: win32
arch: arm64
npm_config_arch: arm
- os: ubuntu-latest
platform: linux
arch: x64
npm_config_arch: x64
- os: ubuntu-latest
platform: linux
arch: arm64
npm_config_arch: arm64
- os: ubuntu-latest
platform: linux
arch: armhf
npm_config_arch: arm
- os: ubuntu-latest
platform: alpine
arch: x64
npm_config_arch: x64
- os: macos-latest
platform: darwin
arch: x64
npm_config_arch: x64
- os: macos-latest
platform: darwin
arch: arm64
npm_config_arch: arm64
runs-on: ${{ matrix.os }}
steps:
# 1. Check-out repository
- name: Check-out repository
uses: actions/checkout@v4
- name: Make sure version isn't odd
run: |
cd extensions/vscode
node versionCheck.js
# 2. Install npm dependencies
- name: Use Node.js 19.0.0
uses: actions/setup-node@v4
with:
node-version: 19.0.0
- name: Cache extension node_modules
uses: actions/cache@v3
with:
path: extensions/vscode/node_modules
key: ${{ runner.os }}-node-${{ hashFiles('extensions/vscode/package-lock.json') }}
- name: Cache core node_modules
uses: actions/cache@v3
with:
path: core/node_modules
key: ${{ runner.os }}-node-${{ hashFiles('core/package-lock.json') }}
- name: Cache gui node_modules
uses: actions/cache@v3
with:
path: gui/node_modules
key: ${{ runner.os }}-node-${{ hashFiles('gui/package-lock.json') }}
- name: Install global Dependencies
run: |
npm install -g cargo-cp-artifact
- name: Install extension Dependencies
run: |
cd extensions/vscode
npm ci
env:
# https://github.com/microsoft/vscode-ripgrep/issues/9#issuecomment-643965333
GITHUB_TOKEN: ${{ secrets.CI_GITHUB_TOKEN }}
- name: Install gui Dependencies
run: |
cd gui
npm ci --legacy-peer-deps
- name: Install Core Dependencies
run: |
cd core
npm ci --legacy-peer-deps
# 2.5. Pre package
- name: Make the out/node_modules directory
run: |
cd extensions/vscode
mkdir out
cd out
mkdir node_modules
- name: Set var for environment info
shell: pwsh
run: echo "target=${{ matrix.platform }}-${{ matrix.arch }}" >> $env:GITHUB_ENV
- name: Prepackage the extension
run: |
cd extensions/vscode
npm run prepackage -- --target ${{ env.target }}
# 3. Run tests for the extension
# - name: Install Xvfb for Linux and run tests
# run: |
# sudo apt-get install -y xvfb # Install Xvfb
# Xvfb :99 & # Start Xvfb
# export DISPLAY=:99 # Export the display number to the environment
# cd extensions/vscode
# npm run test
# if: matrix.os == 'ubuntu-latest'
# - name: Run extension tests
# run: |
# cd extensions/vscode
# npm run test
# if: matrix.os != 'ubuntu-latest'
# 4. Package the extension
- name: Re-install esbuild
run: |
cd extensions/vscode
npm install -f esbuild
- name: Package the extension
run: cd extensions/vscode && npx vsce package --target ${{ env.target }}
# 5. Upload the .vsix as an artifact
- uses: actions/upload-artifact@v2
with:
name: ${{ env.target }}
path: "extensions/vscode/*.vsix"
publish:
runs-on: ubuntu-latest
needs:
- build
permissions:
contents: write
steps:
# 0. Setup git
- name: Checkout
uses: actions/checkout@v4
- name: Set up Git
run: |
git config --local user.email "action@github.com"
git config --local user.name "GitHub Action"
- name: Pull latest changes
run: git pull origin main
# 1. Download the artifacts
- uses: actions/download-artifact@v3
# 2. Publish the extension to VS Code Marketplace
- name: Publish to VS Code Marketplace
run: |
cd extensions/vscode
npx vsce publish --packagePath ../../alpine-x64/*.vsix ../../darwin-arm64/*.vsix ../../darwin-x64/*.vsix ../../linux-arm64/*.vsix ../../linux-armhf/*.vsix ../../linux-x64/*.vsix ../../win32-x64/*.vsix ../../win32-arm64/*.vsix
env:
VSCE_PAT: ${{ secrets.VSCE_TOKEN }}
# 3. Publish the extension to Open VSX Registry
- name: Publish (Open VSX Registry)
run: |
cd extensions/vscode
npx ovsx publish -p ${{ secrets.VSX_REGISTRY_TOKEN }} --packagePath ../../alpine-x64/*.vsix ../../darwin-arm64/*.vsix ../../darwin-x64/*.vsix ../../linux-arm64/*.vsix ../../linux-armhf/*.vsix ../../linux-x64/*.vsix ../../win32-x64/*.vsix ../../win32-arm64/*.vsix
# 4. Update the package.json version and push changes
- name: Update version in package.json
run: |
cd extensions/vscode
npm version patch
- name: Commit changes
run: |
git config --local user.email "action@github.com"
git config --local user.name "GitHub Action"
git commit -am "💚 Update package.json version [skip ci]"
- name: Push changes
uses: ad-m/github-push-action@master
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

@ -1,198 +0,0 @@
name: Publish Preview Extension
on:
push:
branches:
- preview
jobs:
build:
strategy:
matrix:
include:
- os: windows-latest
platform: win32
arch: x64
npm_config_arch: x64
- os: windows-latest
platform: win32
arch: arm64
npm_config_arch: arm
- os: ubuntu-latest
platform: linux
arch: x64
npm_config_arch: x64
- os: ubuntu-latest
platform: linux
arch: arm64
npm_config_arch: arm64
- os: ubuntu-latest
platform: linux
arch: armhf
npm_config_arch: arm
- os: ubuntu-latest
platform: alpine
arch: x64
npm_config_arch: x64
- os: macos-latest
platform: darwin
arch: x64
npm_config_arch: x64
- os: macos-latest
platform: darwin
arch: arm64
npm_config_arch: arm64
runs-on: ${{ matrix.os }}
steps:
# 1. Check-out repository
- name: Check-out repository
uses: actions/checkout@v4
# 2. Install npm dependencies
- name: Use Node.js 19.0.0
uses: actions/setup-node@v4
with:
node-version: 19.0.0
- name: Cache extension node_modules
uses: actions/cache@v3
with:
path: extensions/vscode/node_modules
key: ${{ runner.os }}-node-${{ hashFiles('extensions/vscode/package-lock.json') }}
- name: Cache core node_modules
uses: actions/cache@v3
with:
path: core/node_modules
key: ${{ runner.os }}-node-${{ hashFiles('core/package-lock.json') }}
- name: Cache gui node_modules
uses: actions/cache@v3
with:
path: gui/node_modules
key: ${{ runner.os }}-node-${{ hashFiles('gui/package-lock.json') }}
- name: Install global Dependencies
run: |
npm install -g cargo-cp-artifact
- name: Install extension Dependencies
run: |
cd extensions/vscode
npm ci
env:
# https://github.com/microsoft/vscode-ripgrep/issues/9#issuecomment-643965333
GITHUB_TOKEN: ${{ secrets.CI_GITHUB_TOKEN }}
- name: Install gui Dependencies
run: |
cd gui
npm ci --legacy-peer-deps
- name: Install Core Dependencies
run: |
cd core
npm ci --legacy-peer-deps
# 2.5. Pre package
- name: Make the out/node_modules directory
run: |
cd extensions/vscode
mkdir out
cd out
mkdir node_modules
- name: Set var for environment info
shell: pwsh
run: echo "target=${{ matrix.platform }}-${{ matrix.arch }}" >> $env:GITHUB_ENV
- name: Prepackage the extension
run: |
cd extensions/vscode
npm run prepackage -- --target ${{ env.target }}
# 3. Run tests for the extension
# - name: Install Xvfb for Linux and run tests
# run: |
# sudo apt-get install -y xvfb # Install Xvfb
# Xvfb :99 & # Start Xvfb
# export DISPLAY=:99 # Export the display number to the environment
# cd extensions/vscode
# npm run test
# if: matrix.os == 'ubuntu-latest'
# - name: Run extension tests
# run: |
# cd extensions/vscode
# npm run test
# if: matrix.os != 'ubuntu-latest'
# 4. Package the extension
- name: Re-install esbuild
run: |
cd extensions/vscode
npm install -f esbuild
- name: Package the extension
run: cd extensions/vscode && npx vsce package --pre-release --target ${{ env.target }}
# 5. Upload the .vsix as an artifact
- uses: actions/upload-artifact@v2
with:
name: ${{ env.target }}
path: "extensions/vscode/*.vsix"
publish:
runs-on: ubuntu-latest
needs:
- build
permissions:
contents: write
steps:
# 0. Setup git
- name: Checkout
uses: actions/checkout@v4
- name: Set up Git
run: |
git config --local user.email "action@github.com"
git config --local user.name "GitHub Action"
- name: Pull latest changes
run: git pull origin preview
# 1. Download the artifacts
- uses: actions/download-artifact@v3
# 2. Publish the extension to VS Code Marketplace
- name: Publish to VS Code Marketplace
run: |
cd extensions/vscode
npx vsce publish --pre-release --packagePath ../../alpine-x64/*.vsix ../../darwin-arm64/*.vsix ../../darwin-x64/*.vsix ../../linux-arm64/*.vsix ../../linux-armhf/*.vsix ../../linux-x64/*.vsix ../../win32-x64/*.vsix ../../win32-arm64/*.vsix
env:
VSCE_PAT: ${{ secrets.VSCE_TOKEN }}
# 3. Publish the extension to Open VSX Registry
- name: Publish (Open VSX Registry)
run: |
cd extensions/vscode
npx ovsx publish --pre-release -p ${{ secrets.VSX_REGISTRY_TOKEN }} --packagePath ../../alpine-x64/*.vsix ../../darwin-arm64/*.vsix ../../darwin-x64/*.vsix ../../linux-arm64/*.vsix ../../linux-armhf/*.vsix ../../linux-x64/*.vsix ../../win32-x64/*.vsix ../../win32-arm64/*.vsix
# 4. Update the package.json version and push changes
- name: Update version in package.json
run: |
cd extensions/vscode
npm version patch
- name: Commit changes
run: |
git config --local user.email "action@github.com"
git config --local user.name "GitHub Action"
git commit -am "💚 Update package.json version [skip ci]"
- name: Push changes
uses: ad-m/github-push-action@master
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
branch: ${{ github.ref }}

1
.nvmrc Normal file
View file

@ -0,0 +1 @@
v19.0.0

View file

@ -58,6 +58,12 @@ Continue is continuously improving, but a feature isn't complete until it is ref
VS Code is assumed for development as Continue is primarily a VS Code tool at the moment. Most of the setup and running is automated through VS Code tasks and launch configurations.
<!-- Pre-requisite: you will need `cargo` the rust package manager installed ([get it on rust-lang.org](https://www.rust-lang.org/tools/install)). -->
Pre-requisite: you have Node.js version 20.11.0 (LTS) or higher installed. [get it on https://nodejs.org](https://nodejs.org/en/download/
Alternatively, if you are using NVM (Node Version Manager), you can set the correct version of Node.js for this project by running the following command in the root of the project:
```bash
nvm use
1. Clone and open in VS Code the Continue repo `https://github.com/continuedev/continue`

View file

@ -12,8 +12,12 @@ export async function getAst(
return undefined;
}
const ast = parser.parse(fileContents);
return ast;
try {
const ast = parser.parse(fileContents);
return ast;
} catch (e) {
return undefined;
}
}
export async function getTreePathAtCursor(

View file

@ -0,0 +1,437 @@
import Handlebars from "handlebars";
import { v4 as uuidv4 } from "uuid";
import { IDE, ILLM, Position, TabAutocompleteOptions } from "..";
import { RangeInFileWithContents } from "../commands/util";
import { ConfigHandler } from "../config/handler";
import { streamLines } from "../diff/util";
import OpenAI from "../llm/llms/OpenAI";
import { getBasename } from "../util";
import { logDevData } from "../util/devdata";
import { Telemetry } from "../util/posthog";
import { getRangeInString } from "../util/ranges";
import AutocompleteLruCache from "./cache";
import { noFirstCharNewline, onlyWhitespaceAfterEndOfLine } from "./charStream";
import {
constructAutocompletePrompt,
languageForFilepath,
} from "./constructPrompt";
import { AutocompleteLanguageInfo } from "./languages";
import {
avoidPathLine,
stopAtLines,
stopAtRepeatingLines,
stopAtSimilarLine,
streamWithNewLines,
} from "./lineStream";
import { DEFAULT_AUTOCOMPLETE_OPTS } from "./parameters";
import { AutocompleteSnippet } from "./ranking";
import { getTemplateForModel } from "./templates";
import { GeneratorReuseManager } from "./util";
export interface AutocompleteInput {
completionId: string;
filepath: string;
pos: Position;
recentlyEditedFiles: RangeInFileWithContents[];
recentlyEditedRanges: RangeInFileWithContents[];
clipboardText: string;
}
export interface AutocompleteOutcome {
accepted?: boolean;
time: number;
prompt: string;
completion: string;
modelProvider: string;
modelName: string;
completionOptions: any;
cacheHit: boolean;
}
const autocompleteCache = AutocompleteLruCache.get();
function formatExternalSnippet(
filepath: string,
snippet: string,
language: AutocompleteLanguageInfo,
) {
const comment = language.comment;
const lines = [
comment + " Path: " + getBasename(filepath),
...snippet
.trim()
.split("\n")
.map((line) => comment + " " + line),
comment,
];
return lines.join("\n");
}
export async function getTabCompletion(
token: AbortSignal,
options: TabAutocompleteOptions,
llm: ILLM,
ide: IDE,
generatorReuseManager: GeneratorReuseManager,
input: AutocompleteInput,
getDefinitionsFromLsp: (
filepath: string,
contents: string,
cursorIndex: number,
ide: IDE,
) => Promise<AutocompleteSnippet[]>,
): Promise<AutocompleteOutcome | undefined> {
const startTime = Date.now();
const {
filepath,
pos,
recentlyEditedFiles,
recentlyEditedRanges,
clipboardText,
} = input;
const fileContents = await ide.readFile(filepath);
const fileLines = fileContents.split("\n");
// Filter
const lang = languageForFilepath(filepath);
const line = fileLines[pos.line] ?? "";
for (const endOfLine of lang.endOfLine) {
if (line.endsWith(endOfLine) && pos.character >= line.length) {
return undefined;
}
}
// Model
if (llm instanceof OpenAI) {
llm.useLegacyCompletionsEndpoint = true;
}
if (!llm) return;
// Prompt
const fullPrefix = getRangeInString(fileContents, {
start: { line: 0, character: 0 },
end: pos,
});
const fullSuffix = getRangeInString(fileContents, {
start: pos,
end: { line: fileLines.length - 1, character: Number.MAX_SAFE_INTEGER },
});
const lineBelowCursor =
fileLines[Math.min(pos.line + 1, fileLines.length - 1)];
let extrasSnippets = (await Promise.race([
getDefinitionsFromLsp(
filepath,
fullPrefix + fullSuffix,
fullPrefix.length,
ide,
),
new Promise((resolve) => {
setTimeout(() => resolve([]), 100);
}),
])) as AutocompleteSnippet[];
const workspaceDirs = await ide.getWorkspaceDirs();
if (options.onlyMyCode) {
extrasSnippets = extrasSnippets.filter((snippet) => {
return workspaceDirs.some((dir) => snippet.filepath.startsWith(dir));
});
}
let { prefix, suffix, completeMultiline, snippets } =
await constructAutocompletePrompt(
filepath,
pos.line,
fullPrefix,
fullSuffix,
clipboardText,
lang,
options,
recentlyEditedRanges,
recentlyEditedFiles,
llm.model,
extrasSnippets,
);
// Template prompt
const { template, completionOptions } = options.template
? { template: options.template, completionOptions: {} }
: getTemplateForModel(llm.model);
let prompt: string;
const filename = getBasename(filepath);
const reponame = getBasename(workspaceDirs[0] ?? "myproject");
if (typeof template === "string") {
const compiledTemplate = Handlebars.compile(template);
// Format snippets as comments and prepend to prefix
const formattedSnippets = snippets
.map((snippet) =>
formatExternalSnippet(snippet.filepath, snippet.contents, lang),
)
.join("\n");
if (formattedSnippets.length > 0) {
prefix = formattedSnippets + "\n\n" + prefix;
}
prompt = compiledTemplate({
prefix,
suffix,
filename,
reponame,
});
} else {
// Let the template function format snippets
prompt = template(prefix, suffix, filename, reponame, snippets);
}
// Completion
let completion = "";
const cache = await autocompleteCache;
const cachedCompletion = options.useCache
? await cache.get(prompt)
: undefined;
let cacheHit = false;
if (cachedCompletion) {
// Cache
cacheHit = true;
completion = cachedCompletion;
} else {
// Try to reuse pending requests if what the user typed matches start of completion
let stop = [
...(completionOptions?.stop || []),
"\n\n",
"/src/",
"```",
...lang.stopWords,
];
const multiline =
options.multilineCompletions !== "never" &&
(options.multilineCompletions === "always" || completeMultiline);
let generator = generatorReuseManager.getGenerator(
prefix,
() =>
llm.streamComplete(prompt, {
...completionOptions,
raw: true,
stop,
}),
multiline,
);
// LLM
let cancelled = false;
const generatorWithCancellation = async function* () {
for await (const update of generator) {
if (token.aborted) {
cancelled = true;
return undefined;
}
yield update;
}
};
let chars = generatorWithCancellation();
const gen2 = onlyWhitespaceAfterEndOfLine(
noFirstCharNewline(chars),
lang.endOfLine,
);
const lineGenerator = streamWithNewLines(
avoidPathLine(
stopAtRepeatingLines(stopAtLines(streamLines(gen2))),
lang.comment,
),
);
const finalGenerator = stopAtSimilarLine(lineGenerator, lineBelowCursor);
for await (const update of finalGenerator) {
completion += update;
}
if (cancelled) {
return undefined;
}
// Don't return empty
if (completion.trim().length <= 0) {
return undefined;
}
// Post-processing
completion = completion.trimEnd();
}
const time = Date.now() - startTime;
return {
time,
completion,
prompt,
modelProvider: llm.providerName,
modelName: llm.model,
completionOptions,
cacheHit,
};
}
export class CompletionProvider {
private static debounceTimeout: NodeJS.Timeout | undefined = undefined;
private static debouncing: boolean = false;
private static lastUUID: string | undefined = undefined;
constructor(
private readonly configHandler: ConfigHandler,
private readonly ide: IDE,
private readonly getLlm: () => Promise<ILLM | undefined>,
private readonly _onError: (e: any) => void,
private readonly getDefinitionsFromLsp: (
filepath: string,
contents: string,
cursorIndex: number,
ide: IDE,
) => Promise<AutocompleteSnippet[]>,
) {
this.generatorReuseManager = new GeneratorReuseManager(
this.onError.bind(this),
);
}
private generatorReuseManager: GeneratorReuseManager;
private autocompleteCache = AutocompleteLruCache.get();
public errorsShown: Set<string> = new Set();
private onError(e: any) {
console.warn("Error generating autocompletion: ", e);
if (!this.errorsShown.has(e.message)) {
this.errorsShown.add(e.message);
this._onError(e);
}
}
public cancel() {
this._abortControllers.forEach((abortController, id) => {
abortController.abort();
});
this._abortControllers.clear();
}
private _abortControllers = new Map<string, AbortController>();
private _logRejectionTimeouts = new Map<string, NodeJS.Timeout>();
private _outcomes = new Map<string, AutocompleteOutcome>();
public accept(completionId: string) {
if (this._logRejectionTimeouts.has(completionId)) {
clearTimeout(this._logRejectionTimeouts.get(completionId));
this._logRejectionTimeouts.delete(completionId);
}
if (this._outcomes.has(completionId)) {
const outcome = this._outcomes.get(completionId)!;
outcome.accepted = true;
logDevData("autocomplete", outcome);
Telemetry.capture("autocomplete", {
accepted: outcome.accepted,
modelName: outcome.modelName,
modelProvider: outcome.modelProvider,
time: outcome.time,
cacheHit: outcome.cacheHit,
});
this._outcomes.delete(completionId);
}
}
public async provideInlineCompletionItems(
input: AutocompleteInput,
token: AbortSignal | undefined,
): Promise<AutocompleteOutcome | undefined> {
// Create abort signal if not given
if (!token) {
const controller = new AbortController();
token = controller.signal;
this._abortControllers.set(input.completionId, controller);
}
try {
// Debounce
const uuid = uuidv4();
CompletionProvider.lastUUID = uuid;
const config = await this.configHandler.loadConfig();
const options = {
...DEFAULT_AUTOCOMPLETE_OPTS,
...config.tabAutocompleteOptions,
};
if (CompletionProvider.debouncing) {
CompletionProvider.debounceTimeout?.refresh();
const lastUUID = await new Promise((resolve) =>
setTimeout(() => {
resolve(CompletionProvider.lastUUID);
}, options.debounceDelay),
);
if (uuid !== lastUUID) {
return undefined;
}
} else {
CompletionProvider.debouncing = true;
CompletionProvider.debounceTimeout = setTimeout(async () => {
CompletionProvider.debouncing = false;
}, options.debounceDelay);
}
// Get completion
const llm = await this.getLlm();
if (!llm) {
return undefined;
}
// Set temperature (but don't overrride)
if (llm.completionOptions.temperature === undefined) {
llm.completionOptions.temperature = 0.0;
}
const outcome = await getTabCompletion(
token,
options,
llm,
this.ide,
this.generatorReuseManager,
input,
this.getDefinitionsFromLsp,
);
const completion = outcome?.completion;
if (!completion) {
return undefined;
}
// Do some stuff later so as not to block return. Latency matters
setTimeout(async () => {
if (!outcome.cacheHit) {
(await this.autocompleteCache).put(outcome.prompt, completion);
}
}, 100);
outcome.accepted = false;
const logRejectionTimeout = setTimeout(() => {
// Wait 10 seconds, then assume it wasn't accepted
logDevData("autocomplete", outcome);
Telemetry.capture("autocomplete", {
accepted: outcome.accepted,
modelName: outcome.modelName,
modelProvider: outcome.modelProvider,
time: outcome.time,
cacheHit: outcome.cacheHit,
});
this._logRejectionTimeouts.delete(input.completionId);
}, 10_000);
this._outcomes.set(input.completionId, outcome);
this._logRejectionTimeouts.set(input.completionId, logRejectionTimeout);
return outcome;
} finally {
this._abortControllers.delete(input.completionId);
}
}
}

View file

@ -87,7 +87,7 @@ export async function constructAutocompletePrompt(
language: AutocompleteLanguageInfo,
options: TabAutocompleteOptions,
recentlyEditedRanges: RangeInFileWithContents[],
recentlyEditedDocuments: RangeInFileWithContents[],
recentlyEditedFiles: RangeInFileWithContents[],
modelName: string,
extraSnippets: AutocompleteSnippet[],
): Promise<{
@ -123,7 +123,7 @@ export async function constructAutocompletePrompt(
);
const slidingWindowMatches = await slidingWindowMatcher(
recentlyEditedDocuments,
recentlyEditedFiles,
windowAroundCursor,
3,
options.slidingWindowSize,

View file

@ -184,6 +184,28 @@ export const Dart = {
endOfLine: [";"],
};
// Solidity
export const Solidity = {
stopWords: [
"contract",
"event",
"modifier",
"function",
"constructor",
"for",
"require",
"emit",
"interface",
"error",
"library",
"struct",
"enum",
"type",
],
comment: "//",
endOfLine: [";"],
};
export const LANGUAGES: { [extension: string]: AutocompleteLanguageInfo } = {
ts: Typescript,
js: Typescript,
@ -219,4 +241,5 @@ export const LANGUAGES: { [extension: string]: AutocompleteLanguageInfo } = {
r: R,
R: R,
dart: Dart,
sol: Solidity,
};

View file

@ -1,6 +1,5 @@
import { Chunk } from "..";
import { Chunk, IndexTag } from "..";
import { FullTextSearchCodebaseIndex } from "../indexing/FullTextSearch";
import { IndexTag } from "../indexing/types";
export async function fullTextRetrieve(
prefix: string,

View file

@ -27,12 +27,12 @@ function* slidingWindow(
/**
* Match by similarity over sliding windows of recent documents.
* @param recentDocuments
* @param recentFiles
* @param prefix
* @param suffix
*/
export async function slidingWindowMatcher(
recentDocuments: RangeInFileWithContents[],
recentFiles: RangeInFileWithContents[],
windowAroundCursor: string,
topN: number,
windowSize: number,
@ -40,7 +40,7 @@ export async function slidingWindowMatcher(
// Sorted lowest similarity to highest
const topMatches: AutocompleteSnippet[] = [];
for (const { filepath, contents, range } of recentDocuments) {
for (const { filepath, contents, range } of recentFiles) {
for (const window of slidingWindow(contents, windowSize)) {
const score = jaccardSimilarity(window, windowAroundCursor);

View file

@ -91,14 +91,15 @@ The last line is incomplete, and you should provide the rest of that line. If th
export function getTemplateForModel(model: string): AutocompleteTemplate {
const lowerCaseModel = model.toLowerCase();
if (lowerCaseModel.includes("starcoder2")) {
return starcoder2FimTemplate;
}
// if (lowerCaseModel.includes("starcoder2")) {
// return starcoder2FimTemplate;
// }
if (
lowerCaseModel.includes("starcoder") ||
lowerCaseModel.includes("star-coder") ||
lowerCaseModel.includes("starchat") ||
lowerCaseModel.includes("octocoder") ||
lowerCaseModel.includes("stable")
) {
return stableCodeFimTemplate;

View file

@ -58,7 +58,7 @@ export async function getPromptParts(
) {
let maxTokens = Math.floor(model.contextLength / 2);
const TOKENS_TO_BE_CONSIDERED_LARGE_RANGE = tokenLimit || 1200;
const TOKENS_TO_BE_CONSIDERED_LARGE_RANGE = tokenLimit ?? 1200;
// if (model.countTokens(rif.contents) > TOKENS_TO_BE_CONSIDERED_LARGE_RANGE) {
// throw new Error(
// "\n\n**It looks like you've selected a large range to edit, which may take a while to complete. If you'd like to cancel, click the 'X' button above. If you highlight a more specific range, Continue will only edit within it.**"
@ -455,7 +455,7 @@ const EditSlashCommand: SlashCommand = {
userInput,
filePrefix: filePrefix,
fileSuffix: fileSuffix,
systemMessage: llm.systemMessage || "",
systemMessage: llm.systemMessage ?? "",
// "contextItems": (await sdk.getContextItemChatMessages()).map(x => x.content || "").join("\n\n"),
},
);
@ -516,7 +516,7 @@ const EditSlashCommand: SlashCommand = {
unfinishedLine = "";
chunkLines.pop(); // because this will be an empty string
} else {
unfinishedLine = chunkLines.pop() || "";
unfinishedLine = chunkLines.pop() ?? "";
}
// Deal with newly accumulated lines

View file

@ -36,15 +36,15 @@ async function fetchData(url: string): Promise<string | undefined> {
const doc = parser.parseFromString(htmlString, "text/html");
const h1 = doc.querySelector("h1.fs-headline1");
const title = h1?.textContent?.trim() || "No Title";
const title = h1?.textContent?.trim() ?? "No Title";
const bodies = doc.querySelectorAll("div.js-post-body");
if (bodies.length < 2) {
return undefined;
}
const question = bodies[0].textContent || "";
const answer = bodies[1].textContent || "";
const question = bodies[0].textContent ?? "";
const answer = bodies[1].textContent ?? "";
return `
# Question: [${title}](${url})

View file

@ -22,6 +22,11 @@ export const defaultConfig: SerializedContinueConfig = {
provider: "free-trial",
model: "codellama-70b",
},
{
title: "Mixtral (Free Trial)",
provider: "free-trial",
model: "mistral-8x7b",
},
],
slashCommands: [
{
@ -88,6 +93,11 @@ export const defaultConfigJetBrains: SerializedContinueConfig = {
provider: "free-trial",
model: "codellama-70b",
},
{
title: "Mixtral (Free Trial)",
provider: "free-trial",
model: "mistral-8x7b",
},
],
slashCommands: [
{

View file

@ -4,6 +4,7 @@ import { HttpProxyAgent } from "http-proxy-agent";
import { HttpsProxyAgent } from "https-proxy-agent";
import fetch from "node-fetch";
import { ContinueConfig, ContinueRcJson, IDE, ILLM } from "..";
import { IdeSettings } from "../protocol";
import { Telemetry } from "../util/posthog";
import {
BrowserSerializedContinueConfig,
@ -16,17 +17,17 @@ export class ConfigHandler {
private savedBrowserConfig?: BrowserSerializedContinueConfig;
private readonly ide: IDE;
private readonly remoteConfigServerUrl: URL | undefined;
private ideSettingsPromise: Promise<IdeSettings>;
private readonly writeLog: (text: string) => void;
private readonly onConfigUpdate: () => void;
constructor(
ide: IDE,
remoteConfigServerUrl: URL | undefined,
ideSettingsPromise: Promise<IdeSettings>,
writeLog: (text: string) => void,
onConfigUpdate: () => void,
) {
this.ide = ide;
this.remoteConfigServerUrl = remoteConfigServerUrl;
this.ideSettingsPromise = ideSettingsPromise;
this.writeLog = writeLog;
this.onConfigUpdate = onConfigUpdate;
try {
@ -36,6 +37,11 @@ export class ConfigHandler {
}
}
updateIdeSettings(ideSettings: IdeSettings) {
this.ideSettingsPromise = Promise.resolve(ideSettings);
this.reloadConfig();
}
reloadConfig() {
this.savedConfig = undefined;
this.savedBrowserConfig = undefined;
@ -65,10 +71,20 @@ export class ConfigHandler {
}
const ideInfo = await this.ide.getIdeInfo();
const ideSettings = await this.ideSettingsPromise;
let remoteConfigServerUrl = undefined;
try {
remoteConfigServerUrl =
typeof ideSettings.remoteConfigServerUrl !== "string" ||
ideSettings.remoteConfigServerUrl === ""
? undefined
: new URL(ideSettings.remoteConfigServerUrl);
} catch (e) {}
this.savedConfig = await loadFullConfigNode(
this.ide.readFile,
workspaceConfigs,
this.remoteConfigServerUrl,
remoteConfigServerUrl,
ideInfo.ideType,
);
this.savedConfig.allowAnonymousTelemetry =
@ -102,7 +118,7 @@ export class ConfigHandler {
);
}
let timeout = (llm.requestOptions?.timeout || TIMEOUT) * 1000; // measured in ms
let timeout = (llm.requestOptions?.timeout ?? TIMEOUT) * 1000; // measured in ms
const agentOptions = {
ca,

View file

@ -38,6 +38,7 @@ import {
getContinueDotEnv,
migrate,
} from "../util/paths";
import { defaultConfig } from "./default";
const { execSync } = require("child_process");
function resolveSerializedConfig(filepath: string): SerializedContinueConfig {
@ -50,10 +51,12 @@ function resolveSerializedConfig(filepath: string): SerializedContinueConfig {
};
config.env.forEach((envVar) => {
content = content.replaceAll(
new RegExp(`"${envVar}"`, "g"),
`"${env[envVar]}"`,
);
if (envVar in env) {
content = content.replaceAll(
new RegExp(`"${envVar}"`, "g"),
`"${env[envVar]}"`,
);
}
});
}
@ -73,41 +76,24 @@ function loadSerializedConfig(
ideType: IdeType,
): SerializedContinueConfig {
const configPath = getConfigJsonPath(ideType);
let config = resolveSerializedConfig(configPath);
let config: SerializedContinueConfig;
try {
config = resolveSerializedConfig(configPath);
} catch (e) {
console.log("config.json is invalid. Falling back to default.");
config = defaultConfig;
}
if (config.allowAnonymousTelemetry === undefined) {
config.allowAnonymousTelemetry = true;
}
migrate("codebaseContextProvider", () => {
if (
!config.contextProviders?.filter((cp) => cp.name === "codebase")?.length
) {
migrate("codeContextProvider", () => {
if (!config.contextProviders?.filter((cp) => cp.name === "code")?.length) {
config.contextProviders = [
...(config.contextProviders || []),
{
name: "codebase",
params: {},
},
];
}
if (!config.embeddingsProvider) {
config.embeddingsProvider = {
provider: "transformers.js",
};
}
fs.writeFileSync(configPath, JSON.stringify(config, undefined, 2), "utf8");
});
migrate("problemsContextProvider", () => {
if (
!config.contextProviders?.filter((cp) => cp.name === "problems")?.length
) {
config.contextProviders = [
...(config.contextProviders || []),
{
name: "problems",
name: "code",
params: {},
},
];
@ -116,14 +102,12 @@ function loadSerializedConfig(
fs.writeFileSync(configPath, JSON.stringify(config, undefined, 2), "utf8");
});
migrate("foldersContextProvider", () => {
if (
!config.contextProviders?.filter((cp) => cp.name === "folder")?.length
) {
migrate("docsContextProvider1", () => {
if (!config.contextProviders?.filter((cp) => cp.name === "docs")?.length) {
config.contextProviders = [
...(config.contextProviders || []),
{
name: "folder",
name: "docs",
params: {},
},
];
@ -133,10 +117,14 @@ function loadSerializedConfig(
});
if (remoteConfigServerUrl) {
const remoteConfigJson = resolveSerializedConfig(
getConfigJsonPathForRemote(remoteConfigServerUrl),
);
config = mergeJson(config, remoteConfigJson, "merge", configMergeKeys);
try {
const remoteConfigJson = resolveSerializedConfig(
getConfigJsonPathForRemote(remoteConfigServerUrl),
);
config = mergeJson(config, remoteConfigJson, "merge", configMergeKeys);
} catch (e) {
console.warn("Error loading remote config: ", e);
}
}
for (const workspaceConfig of workspaceConfigs) {
@ -311,7 +299,7 @@ function finalToBrowserConfig(
models: final.models.map((m) => ({
provider: m.providerName,
model: m.model,
title: m.title || m.model,
title: m.title ?? m.model,
apiKey: m.apiKey,
apiBase: m.apiBase,
contextLength: m.contextLength,

View file

@ -0,0 +1,44 @@
import { BaseContextProvider } from "..";
import {
ContextItem,
ContextProviderDescription,
ContextProviderExtras,
ContextSubmenuItem,
LoadSubmenuItemsArgs,
} from "../..";
import { CodeSnippetsCodebaseIndex } from "../../indexing/CodeSnippetsIndex";
class CodeContextProvider extends BaseContextProvider {
static description: ContextProviderDescription = {
title: "code",
displayTitle: "Code",
description: "Type to search",
type: "submenu",
};
async getContextItems(
query: string,
extras: ContextProviderExtras,
): Promise<ContextItem[]> {
// Assume the query is the id as returned by loadSubmenuItems
return [await CodeSnippetsCodebaseIndex.getForId(parseInt(query, 10))];
}
async loadSubmenuItems(
args: LoadSubmenuItemsArgs,
): Promise<ContextSubmenuItem[]> {
const tags = await args.ide.getTags("codeSnippets");
const snippets = await Promise.all(
tags.map((tag) => CodeSnippetsCodebaseIndex.getAll(tag)),
);
const submenuItems: ContextSubmenuItem[] = [];
for (const snippetList of snippets) {
submenuItems.push(...snippetList);
}
return submenuItems;
}
}
export default CodeContextProvider;

View file

@ -16,9 +16,9 @@ class CustomContextProviderClass implements IContextProvider {
get description(): ContextProviderDescription {
return {
title: this.custom.title,
displayTitle: this.custom.displayTitle || this.custom.title,
description: this.custom.description || "",
type: this.custom.type || "normal",
displayTitle: this.custom.displayTitle ?? this.custom.title,
description: this.custom.description ?? "",
type: this.custom.type ?? "normal",
renderInlineAs: this.custom.renderInlineAs,
};
}
@ -31,7 +31,7 @@ class CustomContextProviderClass implements IContextProvider {
}
async loadSubmenuItems(args: LoadSubmenuItemsArgs) {
return this.custom.loadSubmenuItems?.(args) || [];
return this.custom.loadSubmenuItems?.(args) ?? [];
}
}

View file

@ -6,13 +6,14 @@ import {
ContextSubmenuItem,
LoadSubmenuItemsArgs,
} from "../..";
import configs from "../../indexing/docs/preIndexedDocs";
import TransformersJsEmbeddingsProvider from "../../indexing/embeddings/TransformersJsEmbeddingsProvider";
class DocsContextProvider extends BaseContextProvider {
static description: ContextProviderDescription = {
title: "docs",
displayTitle: "Docs",
description: "Search documentation",
description: "Type to search docs",
type: "submenu",
};
@ -29,10 +30,9 @@ class DocsContextProvider extends BaseContextProvider {
query,
vector,
this.options?.nRetrieve || 15,
embeddingsProvider.id,
);
console.log(chunks);
return [
...chunks
.map((chunk) => ({
@ -45,7 +45,7 @@ class DocsContextProvider extends BaseContextProvider {
.slice(1)
.join("/")
: chunk.otherMetadata?.title || chunk.filepath,
description: new URL(chunk.filepath, query).toString(),
description: chunk.filepath, // new URL(chunk.filepath, query).toString(),
content: chunk.content,
}))
.reverse(),
@ -53,7 +53,7 @@ class DocsContextProvider extends BaseContextProvider {
name: "Instructions",
description: "Instructions",
content:
"Use the above documentation to answer the following question. You should not reference anything outside of what is shown, unless it is a commonly known concept. Reference URLs whenever possible. If there isn't enough information to answer the question, suggest where the user might look to learn more.",
"Use the above documentation to answer the following question. You should not reference anything outside of what is shown, unless it is a commonly known concept. Reference URLs whenever possible using markdown formatting. If there isn't enough information to answer the question, suggest where the user might look to learn more.",
},
];
}
@ -63,11 +63,25 @@ class DocsContextProvider extends BaseContextProvider {
): Promise<ContextSubmenuItem[]> {
const { listDocs } = await import("../../indexing/docs/db");
const docs = await listDocs();
return docs.map((doc) => ({
const submenuItems = docs.map((doc) => ({
title: doc.title,
description: new URL(doc.baseUrl).hostname,
id: doc.baseUrl,
}));
submenuItems.push(
...configs
// After it's actually downloaded, we don't want to show twice
.filter(
(config) => !submenuItems.some((item) => item.id === config.startUrl),
)
.map((config) => ({
title: config.title,
description: new URL(config.startUrl).hostname,
id: config.startUrl,
})),
);
return submenuItems;
}
}

View file

@ -25,7 +25,7 @@ class FileContextProvider extends BaseContextProvider {
const content = await extras.ide.readFile(query);
return [
{
name: query.split(/[\\/]/).pop() || query,
name: query.split(/[\\/]/).pop() ?? query,
description: query,
content: `\`\`\`${query}\n${content}\n\`\`\``,
},

View file

@ -53,7 +53,7 @@ class FileTreeContextProvider extends BaseContextProvider {
const contents = await extras.ide.listWorkspaceContents(workspaceDir);
const subDirTree: Directory = {
name: splitPath(workspaceDir).pop() || "",
name: splitPath(workspaceDir).pop() ?? "",
files: [],
directories: [],
};

View file

@ -0,0 +1,277 @@
import { AxiosInstance, AxiosError } from "axios";
import {BaseContextProvider} from "..";
import { ContextProviderExtras, ContextItem, ContextProviderDescription } from "../..";
interface RemoteBranchInfo {
branch: string | null;
project: string | null;
}
interface GitLabUser {
id: number;
username: string;
name: string;
state: "active";
locked: boolean;
avatar_url: string;
web_url: string;
}
interface GitLabMergeRequest {
iid: number;
project_id: number;
title: string;
description: string;
}
interface GitLabComment {
type: null | "DiffNote";
resolvable: boolean;
resolved?: boolean;
body: string;
created_at: string;
author: GitLabUser;
position?: {
new_path: string;
new_line: number;
head_sha: string;
line_range: {
start: {
line_code: string;
type: "new";
old_line: null;
new_line: number;
};
end: {
line_code: string;
type: "new";
old_line: null;
new_line: number;
};
};
};
}
const trimFirstElement = (args: Array<string>): string => {
return args[0].trim();
};
const getSubprocess = async (extras: ContextProviderExtras) => {
const workingDir = await extras.ide
.getWorkspaceDirs()
.then(trimFirstElement);
return (command: string) =>
extras.ide
.subprocess(`cd ${workingDir}; ${command}`)
.then(trimFirstElement);
};
class GitLabMergeRequestContextProvider extends BaseContextProvider {
static description: ContextProviderDescription = {
title: 'gitlab-mr',
displayTitle: 'GitLab Merge Request',
description: 'Reference comments in a GitLab Merge Request',
type: 'normal'
};
private async getApi(): Promise<AxiosInstance> {
const { default: Axios } = await import("axios");
const domain = this.options.domain ?? "gitlab.com";
const token = this.options.token;
if(!token) {
throw new Error(`GitLab Private Token is required!`);
}
return Axios.create({
baseURL: `https://${domain ?? "gitlab.com"}/api/v4`,
headers: {
"PRIVATE-TOKEN": token,
},
});
};
private async getRemoteBranchName(extras: ContextProviderExtras): Promise<RemoteBranchInfo> {
const subprocess = await getSubprocess(extras);
const branchName = await subprocess(`git branch --show-current`);
const branchRemote = await subprocess(
`git config branch.${branchName}.remote`
);
const branchInfo = await subprocess(`git branch -vv`);
const currentBranchInfo = branchInfo
.split("\n")
.find((line) => line.startsWith("*"));
const remoteMatches = RegExp(
`\\[${branchRemote}/(?<remote_branch>[^\\]]+)\\]`
).exec(currentBranchInfo!);
console.dir({ remoteMatches });
const remoteBranch = remoteMatches?.groups?.["remote_branch"] ?? null;
const remoteUrl = await subprocess(`git remote get-url ${branchRemote}`);
const urlMatches = RegExp(`:(?<project>.*).git`).exec(remoteUrl);
const project = urlMatches?.groups?.["project"] ?? null;
return {
branch: remoteBranch,
project,
};
};
async getContextItems(query: string, extras: ContextProviderExtras): Promise<ContextItem[]> {
const { branch, project } = await this.getRemoteBranchName(extras);
const api = await this.getApi();
const result = [] as Array<ContextItem>;
try {
const mergeRequests = await api
.get<Array<GitLabMergeRequest>>(
`/projects/${encodeURIComponent(project!)}/merge_requests`,
{
params: {
source_branch: branch,
state: "opened",
},
}
)
.then((x) => x.data);
const subprocess = await getSubprocess(extras);
for (const mergeRequest of mergeRequests) {
const parts = [
`# GitLab Merge Request\ntitle: "${mergeRequest.title}"\ndescription: "${mergeRequest.description ?? 'None'}"`,
`## Comments`,
];
const comments = await api.get<Array<GitLabComment>>(
`/projects/${mergeRequest.project_id}/merge_requests/${mergeRequest.iid}/notes`,
{
params: {
sort: "asc",
order_by: "created_at",
},
}
);
const filteredComments = comments.data.filter(
(x) => x.type === "DiffNote"
);
const locations = {} as Record<string, Array<GitLabComment>>;
for (const comment of filteredComments) {
const filename = comment.position?.new_path ?? "general";
if (!locations[filename]) {
locations[filename] = [];
}
locations[filename].push(comment);
}
if (extras.selectedCode.length && this.options.filterComments) {
const toRemove = Object.keys(locations).filter(filename => !extras.selectedCode.find(selection => selection.filepath.endsWith(filename)) && filename !== "general");
for (const filepath of toRemove) {
delete locations[filepath];
}
}
const commentFormatter = async (comment: GitLabComment) => {
const commentLabel = comment.body.includes("```suggestion") ? 'Code Suggestion' : 'Comment';
let result = `#### ${commentLabel}\nauthor: "${comment.author.name}"\ndate: "${comment.created_at}"\nresolved: ${
comment.resolved ? "Yes" : "No"
}`;
if (comment.position?.new_line) {
result += `\nline: ${comment.position.new_line}`;
if (comment.position.head_sha) {
const sourceLines = await subprocess(`git show ${comment.position.head_sha}:${comment.position.new_path}`).then(result => result.split("\n")).catch(ex => []);
const line = comment.position.new_line <= sourceLines.length ? sourceLines[comment.position.new_line - 1] : null;
if (line) {
result += `\nsource: \`${line}\``;
}
}
}
result += `\n\n${comment.body}`;
return result;
};
for (const [filename, locationComments] of Object.entries(locations)) {
if (filename !== "general") {
parts.push(`### File ${filename}`);
locationComments.sort(
(a, b) => a.position!.new_line - b.position!.new_line
);
} else {
parts.push("### General");
}
const commentSections = await Promise.all(locationComments.map(commentFormatter));
parts.push(...commentSections);
}
const content = parts.join("\n\n");
result.push(
{
name: mergeRequest.title,
content,
description: `Comments from the Merge Request for this branch.`,
},
);
}
} catch (ex) {
let content = `# GitLab Merge Request\n\nError getting merge request. `;
if (ex instanceof AxiosError) {
if (ex.response) {
const errorMessage = ex.response?.data ? ex.response.data.message ?? JSON.stringify(ex.response?.data) : `${ex.response.status}: ${ex.response.statusText}`;
content += `GitLab Error: ${errorMessage}`;
} else {
content += `GitLab Request Error ${ex.request}`;
}
} else {
// @ts-ignore
content += `Unknown error: ${ex.message ?? JSON.stringify(ex)}`;
}
result.push(
{
name: `GitLab Merge Request`,
content,
description: `Error getting the Merge Request for this branch.`,
},
);
}
return result;
}
}
export default GitLabMergeRequestContextProvider;

View file

@ -1,134 +0,0 @@
import type { AxiosInstance } from "axios";
import { BaseContextProvider } from "..";
import {
ContextItem,
ContextProviderDescription,
ContextProviderExtras,
ContextSubmenuItem,
LoadSubmenuItemsArgs,
} from "../..";
const { convert } = require("adf-to-md");
interface JiraComment {
id: string;
created: string;
updated: string;
author: {
emailAddress: string;
displayName: string;
};
body: object;
}
interface JiraIssue {
id: string;
key: string;
fields: {
summary: string;
description: object;
comment: {
total: number;
comments: Array<JiraComment>;
};
};
}
interface QueryResults {
issues: JiraIssue[];
}
class JiraIssuesContextProvider extends BaseContextProvider {
static description: ContextProviderDescription = {
title: "jira",
displayTitle: "Jira Issues",
description: "Reference Jira issues",
type: "submenu",
};
private async createApi(): Promise<AxiosInstance> {
const { default: Axios } = await import("axios");
return Axios.create({
baseURL: `https://${this.options.domain}/rest/api/3/`,
auth: {
username: this.options.email,
password: this.options.token,
},
});
}
async getContextItems(
query: string,
extras: ContextProviderExtras,
): Promise<ContextItem[]> {
const issueId = query;
const api = await this.createApi();
const issue = await api
.get<JiraIssue>(`/issue/${issueId}`, {
params: {
fields: "description,comment,summary",
},
})
.then((result) => result.data);
const parts = [
`# Jira Issue ${issue.key}: ${issue.fields.summary}`,
"## Description",
issue.fields.description
? convert(issue.fields.description).result
: "No description",
];
if (issue.fields.comment.comments.length > 0) {
parts.push("## Comments");
parts.push(
...issue.fields.comment.comments.map((comment) => {
const commentText = convert(comment.body).result;
return `### ${comment.author.displayName} on ${comment.created}\n\n${commentText}`;
}),
);
}
const content = parts.join("\n\n");
return [
{
name: `${issue.key}: ${issue.fields.summary}`,
content,
description: issue.key,
},
];
}
async loadSubmenuItems(
args: LoadSubmenuItemsArgs,
): Promise<ContextSubmenuItem[]> {
const api = await this.createApi();
try {
const results = await api.get<QueryResults>("/search", {
params: {
jql:
this.options.issueQuery ??
`assignee = currentUser() AND resolution = Unresolved order by updated DESC`,
fields: "summary",
},
});
return results.data.issues.map((issue) => ({
id: issue.id,
title: `${issue.key}: ${issue.fields.summary}`,
description: "",
}));
} catch (ex) {
console.error(`Unable to get jira tickets: ${ex}`);
return [];
}
}
}
export default JiraIssuesContextProvider;

View file

@ -0,0 +1,157 @@
import type { AxiosInstance } from "axios";
const { convert: adf2md } = require("adf-to-md");
interface JiraClientOptions {
domain: string;
username: string;
password: string;
issueQuery?: string;
apiVersion?: string;
}
interface JiraComment {
id: string;
created: string;
updated: string;
author: {
emailAddress: string;
displayName: string;
};
body: object | string;
}
interface JiraIssue {
id: string;
key: string;
fields: {
summary: string;
description: object | string;
comment: {
total: number;
comments: Array<JiraComment>;
};
};
}
interface QueryResult {
id: string;
key: string;
summary: string;
}
interface QueryResults {
issues: JiraIssue[];
}
export interface Comment {
created: string;
updated: string;
author: {
emailAddress: string;
displayName: string;
};
body: string;
}
export interface Issue {
key: string;
summary: string;
description?: string;
comments: Array<Comment>;
}
export class JiraClient {
private readonly options: Required<JiraClientOptions>;
private _api: AxiosInstance | null = null;
constructor(options: JiraClientOptions) {
this.options = {
issueQuery: `assignee = currentUser() AND resolution = Unresolved order by updated DESC`,
apiVersion: '3',
...options
};
}
private async getApi() {
if (!this._api) {
const { default: Axios } = await import("axios");
this._api = Axios.create({
baseURL: `https://${this.options.domain}/rest/api/${this.options.apiVersion}/`,
...(this.options.username
? {
auth: {
username: this.options.username,
password: this.options.password,
},
}
: {
headers: {
Authorization: `Bearer ${this.options.password}`,
},
}),
});
}
return this._api;
}
async issue(issueId: string): Promise<Issue> {
const api = await this.getApi();
const result = {} as Issue;
const issue = await api
.get<JiraIssue>(`/issue/${issueId}`, {
params: {
fields: "description,comment,summary",
},
})
.then((result) => result.data);
result.key = issue.key;
result.summary = issue.fields.summary;
if (typeof issue.fields.description === 'string') {
result.description = issue.fields.description;
} else if(issue.fields.description) {
result.description = adf2md(issue.fields.description).result;
} else {
result.description = "";
}
result.comments = issue.fields.comment?.comments?.map((comment) => {
const body = typeof comment.body === 'string' ? comment.body : adf2md(comment.body).result;
return {
body,
author: comment.author,
created: comment.created,
updated: comment.updated,
};
}) ?? [];
return result;
}
async listIssues(): Promise<Array<QueryResult>> {
const api = await this.getApi();
const results = await api.get<QueryResults>("/search", {
params: {
jql:
this.options.issueQuery ??
`assignee = currentUser() AND resolution = Unresolved order by updated DESC`,
fields: "summary",
},
});
return results.data?.issues?.map((issue) => ({
id: issue.id,
key: issue.key,
summary: issue.fields.summary,
})) ?? [];
}
}

View file

@ -0,0 +1,85 @@
import { BaseContextProvider } from "../..";
import {
ContextItem,
ContextProviderDescription,
ContextProviderExtras,
ContextSubmenuItem,
LoadSubmenuItemsArgs,
} from "../../..";
import { JiraClient } from "./JiraClient";
class JiraIssuesContextProvider extends BaseContextProvider {
static description: ContextProviderDescription = {
title: "jira",
displayTitle: "Jira Issues",
description: "Reference Jira issues",
type: "submenu",
};
private getApi() {
return new JiraClient({
domain: this.options.domain,
username: this.options.email,
password: this.options.token,
issueQuery: this.options.issueQuery,
apiVersion: this.options.apiVersion,
});
}
async getContextItems(
query: string,
extras: ContextProviderExtras
): Promise<ContextItem[]> {
const issueId = query;
const api = this.getApi();
const issue = await api.issue(query);
const parts = [
`# Jira Issue ${issue.key}: ${issue.summary}`,
"## Description",
issue.description ?? "No description",
];
if (issue.comments.length > 0) {
parts.push("## Comments");
parts.push(
...issue.comments.map((comment) => {
return `### ${comment.author.displayName} on ${comment.created}\n\n${comment.body}`;
})
);
}
const content = parts.join("\n\n");
return [
{
name: `${issue.key}: ${issue.summary}`,
content,
description: issue.key,
},
];
}
async loadSubmenuItems(
args: LoadSubmenuItemsArgs
): Promise<ContextSubmenuItem[]> {
const api = await this.getApi();
try {
const issues = await api.listIssues();
return issues.map((issue) => ({
id: issue.id,
title: `${issue.key}: ${issue.summary}`,
description: "",
}));
} catch (ex) {
console.error(`Unable to get jira tickets: ${ex}`);
return [];
}
}
}
export default JiraIssuesContextProvider;

View file

@ -0,0 +1,62 @@
import { BaseContextProvider } from "..";
import {
ContextItem,
ContextProviderDescription,
ContextProviderExtras,
ContextSubmenuItem,
LoadSubmenuItemsArgs,
} from "../..";
class LocalsProvider extends BaseContextProvider {
static description: ContextProviderDescription = {
title: "locals",
displayTitle: "Locals",
description: "Reference the contents of the local variables",
type: "submenu",
};
async getContextItems(
query: string,
extras: ContextProviderExtras
): Promise<ContextItem[]> {
// Assuming that the query is a number
const localVariables = await extras.ide.getDebugLocals(Number(query));
const threadIndex = Number(query);
const thread = (await extras.ide.getAvailableThreads()).find(
(thread) => thread.id == threadIndex
);
const callStacksSources = await extras.ide.getTopLevelCallStackSources(
threadIndex,
this.options?.stackDepth || 3
);
const callStackContents = callStacksSources.reduce(
(acc, source, index) =>
acc + `\n\ncall stack ${index}\n` + "```\n" + source + "\n```",
""
);
return [
{
description: "The value, name and possibly type of the local variables",
content:
`This is a paused thread: ${thread?.name}\n` +
`Current local variable contents: \n${localVariables}.\n` +
`Current top level call stacks: ${callStackContents}`,
name: "Locals",
},
];
}
async loadSubmenuItems(
args: LoadSubmenuItemsArgs
): Promise<ContextSubmenuItem[]> {
const threads = await args.ide.getAvailableThreads();
return threads.map((thread) => ({
id: `${thread.id}`,
title: thread.name,
description: `${thread.id}`,
}));
}
}
export default LocalsProvider;

View file

@ -29,7 +29,7 @@ class OpenFilesContextProvider extends BaseContextProvider {
content: `\`\`\`${getBasename(filepath)}\n${await ide.readFile(
filepath,
)}\n\`\`\``,
name: (filepath.split("/").pop() || "").split("\\").pop() || "",
name: (filepath.split("/").pop() ?? "").split("\\").pop() ?? "",
};
}),
);

View file

@ -1,5 +1,6 @@
import { BaseContextProvider } from "..";
import { ContextProviderName } from "../..";
import CodeContextProvider from "./CodeContextProvider";
import CodebaseContextProvider from "./CodebaseContextProvider";
import DatabaseContextProvider from "./DatabaseContextProvider";
import DiffContextProvider from "./DiffContextProvider";
@ -15,7 +16,9 @@ import PostgresContextProvider from "./PostgresContextProvider";
import ProblemsContextProvider from "./ProblemsContextProvider";
import SearchContextProvider from "./SearchContextProvider";
import TerminalContextProvider from "./TerminalContextProvider";
import LocalsProvider from "./LocalsProvider";
import URLContextProvider from "./URLContextProvider";
import GitLabMergeRequestContextProvider from "./GitLabMergeRequestContextProvider";
const Providers: (typeof BaseContextProvider)[] = [
DiffContextProvider,
@ -23,6 +26,7 @@ const Providers: (typeof BaseContextProvider)[] = [
GitHubIssuesContextProvider,
GoogleContextProvider,
TerminalContextProvider,
LocalsProvider,
URLContextProvider,
OpenFilesContextProvider,
HttpContextProvider,
@ -31,11 +35,13 @@ const Providers: (typeof BaseContextProvider)[] = [
ProblemsContextProvider,
FolderContextProvider,
DocsContextProvider,
GitLabMergeRequestContextProvider,
// CodeHighlightsContextProvider,
// CodeOutlineContextProvider,
JiraIssuesContextProvider,
PostgresContextProvider,
DatabaseContextProvider,
CodeContextProvider,
];
export function contextProviderClassFromName(

View file

@ -1,7 +1,7 @@
import { Chunk, ContextItem, ContextProviderExtras, ILLM } from "..";
import { Chunk, ContextItem, ContextProviderExtras, ILLM, IndexTag } from "..";
import { FullTextSearchCodebaseIndex } from "../indexing/FullTextSearch";
import { LanceDbIndex } from "../indexing/LanceDbIndex";
import { IndexTag } from "../indexing/types";
import { llmCanGenerateInParallel } from "../llm/autodetect";
import { getBasename } from "../util";

52
core/index.d.ts vendored
View file

@ -16,7 +16,7 @@ declare global {
postIntellijMessage?: (
messageType: string,
data: any,
messageIde: string,
messageIde: string
) => void;
}
}
@ -73,17 +73,17 @@ export interface ILLM extends LLMOptions {
streamComplete(
prompt: string,
options?: LLMFullCompletionOptions,
options?: LLMFullCompletionOptions
): AsyncGenerator<string, LLMReturnValue>;
streamChat(
messages: ChatMessage[],
options?: LLMFullCompletionOptions,
options?: LLMFullCompletionOptions
): AsyncGenerator<ChatMessage, LLMReturnValue>;
chat(
messages: ChatMessage[],
options?: LLMFullCompletionOptions,
options?: LLMFullCompletionOptions
): Promise<ChatMessage>;
countTokens(text: string): number;
@ -123,10 +123,10 @@ export interface CustomContextProvider {
type?: ContextProviderType;
getContextItems(
query: string,
extras: ContextProviderExtras,
extras: ContextProviderExtras
): Promise<ContextItem[]>;
loadSubmenuItems?: (
args: LoadSubmenuItemsArgs,
args: LoadSubmenuItemsArgs
) => Promise<ContextSubmenuItem[]>;
}
@ -141,7 +141,7 @@ export interface IContextProvider {
getContextItems(
query: string,
extras: ContextProviderExtras,
extras: ContextProviderExtras
): Promise<ContextItem[]>;
loadSubmenuItems(args: LoadSubmenuItemsArgs): Promise<ContextSubmenuItem[]>;
@ -287,15 +287,15 @@ export interface CustomLLMWithOptionals {
streamCompletion?: (
prompt: string,
options: CompletionOptions,
fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>,
fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>
) => AsyncGenerator<string>;
streamChat?: (
messages: ChatMessage[],
options: CompletionOptions,
fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>,
fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>
) => AsyncGenerator<string>;
listModels?: (
fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>,
fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>
) => Promise<string[]>;
}
@ -320,6 +320,11 @@ export class Problem {
message: string;
}
export class Thread {
name: string;
id: number;
}
export type IdeType = "vscode" | "jetbrains";
export interface IdeInfo {
ideType: IdeType;
@ -328,12 +333,24 @@ export interface IdeInfo {
remoteName: string;
}
export interface IndexTag {
directory: string;
branch: string;
artifactId: string;
}
export interface IDE {
getIdeInfo(): Promise<IdeInfo>;
getDiff(): Promise<string>;
isTelemetryEnabled(): Promise<boolean>;
getUniqueId(): Promise<string>;
getTerminalContents(): Promise<string>;
getDebugLocals(threadIndex: number): Promise<string>;
getTopLevelCallStackSources(
threadIndex: number,
stackDepth: number
): Promise<string[]>;
getAvailableThreads(): Promise<Thread[]>;
listWorkspaceContents(directory?: string): Promise<string[]>;
listFolders(): Promise<string[]>;
getWorkspaceDirs(): Promise<string[]>;
@ -349,12 +366,12 @@ export interface IDE {
showLines(
filepath: string,
startLine: number,
endLine: number,
endLine: number
): Promise<void>;
showDiff(
filepath: string,
newContents: string,
stepIndex: number,
stepIndex: number
): Promise<void>;
getOpenFiles(): Promise<string[]>;
getPinnedFiles(): Promise<string[]>;
@ -363,6 +380,7 @@ export interface IDE {
getProblems(filepath?: string | undefined): Promise<Problem[]>;
getBranch(dir: string): Promise<string>;
getStats(directory: string): Promise<{ [path: string]: number }>;
getTags(artifactId: string): Promise<IndexTag[]>;
}
// Slash Commands
@ -408,6 +426,7 @@ type ContextProviderName =
| "diff"
| "github"
| "terminal"
| "locals"
| "open"
| "google"
| "search"
@ -419,7 +438,10 @@ type ContextProviderName =
| "folder"
| "jira"
| "postgres"
| "database";
| "database"
| "code"
| "docs"
| "gitlab-mr";
type TemplateType =
| "llama2"
@ -435,7 +457,8 @@ type TemplateType =
| "xwin-coder"
| "neural-chat"
| "codellama-70b"
| "llava";
| "llava"
| "gemma";
type ModelProvider =
| "openai"
@ -548,6 +571,7 @@ interface BaseCompletionOptions {
stop?: string[];
maxTokens?: number;
numThreads?: number;
keepAlive?: number;
}
export interface ModelDescription {

View file

@ -0,0 +1,216 @@
import fs from "fs";
import path from "path";
import {
ChunkWithoutID,
ContextItem,
ContextSubmenuItem,
IDE,
IndexTag,
IndexingProgressUpdate,
} from "..";
import { getBasename } from "../util";
import {
getLanguageForFile,
getParserForFile,
supportedLanguages,
} from "../util/treeSitter";
import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex";
import {
CodebaseIndex,
IndexResultType,
MarkCompleteCallback,
RefreshIndexResults,
} from "./types";
export class CodeSnippetsCodebaseIndex implements CodebaseIndex {
artifactId = "codeSnippets";
constructor(private readonly ide: IDE) {}
private async _createTables(db: DatabaseConnection) {
await db.exec(`CREATE TABLE IF NOT EXISTS code_snippets (
id INTEGER PRIMARY KEY,
path TEXT NOT NULL,
cacheKey TEXT NOT NULL,
content TEXT NOT NULL,
title TEXT NOT NULL,
startLine INTEGER NOT NULL,
endLine INTEGER NOT NULL
)`);
await db.exec(`CREATE TABLE IF NOT EXISTS code_snippets_tags (
id INTEGER PRIMARY KEY AUTOINCREMENT,
tag TEXT NOT NULL,
snippetId INTEGER NOT NULL,
FOREIGN KEY (snippetId) REFERENCES code_snippets (id)
)`);
}
private getQuerySource(filepath: string) {
const fullLangName = supportedLanguages[filepath.split(".").pop() ?? ""];
const sourcePath = path.join(
__dirname,
"..",
"tree-sitter",
"code-snippet-queries",
`tree-sitter-${fullLangName}-tags.scm`,
);
if (!fs.existsSync(sourcePath)) {
return "";
}
return fs.readFileSync(sourcePath).toString();
}
async getSnippetsInFile(
filepath: string,
contents: string,
): Promise<(ChunkWithoutID & { title: string })[]> {
const lang = await getLanguageForFile(filepath);
if (!lang) {
return [];
}
const parser = await getParserForFile(filepath);
if (!parser) {
return [];
}
const ast = parser.parse(contents);
const query = lang?.query(this.getQuerySource(filepath));
const matches = query?.matches(ast.rootNode);
return (
matches?.flatMap((match) => {
const node = match.captures[0].node;
const title = match.captures[1].node.text;
const results = {
title,
content: node.text,
startLine: node.startPosition.row,
endLine: node.endPosition.row,
};
return results;
}) ?? []
);
}
async *update(
tag: IndexTag,
results: RefreshIndexResults,
markComplete: MarkCompleteCallback,
): AsyncGenerator<IndexingProgressUpdate, any, unknown> {
const db = await SqliteDb.get();
await this._createTables(db);
const tagString = tagToString(tag);
for (let i = 0; i < results.compute.length; i++) {
const compute = results.compute[i];
const snippets = await this.getSnippetsInFile(
compute.path,
await this.ide.readFile(compute.path),
);
// Add snippets to sqlite
for (const snippet of snippets) {
const { lastID } = await db.run(
`INSERT INTO code_snippets (path, cacheKey, content, title, startLine, endLine) VALUES (?, ?, ?, ?, ?, ?)`,
[
compute.path,
compute.cacheKey,
snippet.content,
snippet.title,
snippet.startLine,
snippet.endLine,
],
);
await db.run(
`INSERT INTO code_snippets_tags (snippetId, tag) VALUES (?, ?)`,
[lastID, tagString],
);
}
yield {
desc: `Indexing ${compute.path}`,
progress: i / results.compute.length,
};
markComplete([compute], IndexResultType.Compute);
}
for (let i = 0; i < results.del.length; i++) {
const del = results.del[i];
const deleted = await db.run(
`DELETE FROM code_snippets WHERE path = ? AND cacheKey = ?`,
[del.path, del.cacheKey],
);
await db.run(`DELETE FROM code_snippets_tags WHERE snippetId = ?`, [
deleted.lastID,
]);
markComplete([del], IndexResultType.Delete);
}
for (let i = 0; i < results.addTag.length; i++) {
const snippetsWithPath = await db.all(
`SELECT * FROM code_snippets WHERE cacheKey = ?`,
[results.addTag[i].cacheKey],
);
for (const snippet of snippetsWithPath) {
await db.run(
`INSERT INTO code_snippets_tags (snippetId, tag) VALUES (?, ?)`,
[snippet.id, tagString],
);
}
markComplete([results.addTag[i]], IndexResultType.AddTag);
}
for (let i = 0; i < results.removeTag.length; i++) {
const item = results.removeTag[i];
await db.run(
`
DELETE FROM code_snippets_tags
WHERE tag = ?
AND snippetId IN (
SELECT id FROM code_snippets
WHERE cacheKey = ? AND path = ?
)
`,
[tagString, item.cacheKey, item.path],
);
markComplete([results.removeTag[i]], IndexResultType.RemoveTag);
}
}
static async getForId(id: number): Promise<ContextItem> {
const db = await SqliteDb.get();
const row = await db.get(`SELECT * FROM code_snippets WHERE id = ?`, [id]);
return {
name: row.title,
description: getBasename(row.path, 2),
content: `\`\`\`${getBasename(row.path)}\n${row.content}\n\`\`\``,
};
}
static async getAll(tag: IndexTag): Promise<ContextSubmenuItem[]> {
const db = await SqliteDb.get();
try {
const rows = await db.all(
`SELECT cs.id, cs.path, cs.title
FROM code_snippets cs
JOIN code_snippets_tags cst ON cs.id = cst.snippetId
WHERE cst.tag = ?;
`,
[tagToString(tag)],
);
return rows.map((row) => ({
title: row.title,
description: getBasename(row.path, 2),
id: row.id.toString(),
}));
} catch (e) {
console.warn("Error getting all code snippets: ", e);
return [];
}
}
}

View file

@ -1,9 +1,8 @@
import { Chunk, IndexingProgressUpdate } from "..";
import { Chunk, IndexTag, IndexingProgressUpdate } from "..";
import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex";
import {
CodebaseIndex,
IndexResultType,
IndexTag,
MarkCompleteCallback,
RefreshIndexResults,
} from "./types";

View file

@ -1,6 +1,11 @@
// NOTE: vectordb requirement must be listed in extensions/vscode to avoid error
import { v4 as uuidv4 } from "uuid";
import { Chunk, EmbeddingsProvider, IndexingProgressUpdate } from "..";
import {
Chunk,
EmbeddingsProvider,
IndexTag,
IndexingProgressUpdate,
} from "..";
import { MAX_CHUNK_SIZE } from "../llm/constants";
import { getBasename } from "../util";
import { getLanceDbPath } from "../util/paths";
@ -9,7 +14,6 @@ import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex";
import {
CodebaseIndex,
IndexResultType,
IndexTag,
PathAndCacheKey,
RefreshIndexResults,
} from "./types";

30
core/indexing/README.md Normal file
View file

@ -0,0 +1,30 @@
# Indexing
Continue uses a tagging system along with content addressing to ensure that nothing needs to be indexed twice. When you change branches, Continue will only re-index the files that are newly modified and that we don't already have a copy of. This system can be used across many different "artifacts" just by implementing the `CodebaseIndex` class.
_artifact_: something that is generated by indexing and then saved to be used later (e.g. emeddings, full-text search index, or a table of top-level code snippets in each file)
_cacheKey_: a key that determines whether two files can be considered the same to avoid re-indexing (always hash of file contents at this point)
_`CodebaseIndex`_: a class that makes it easy to use the indexing system to help you generate a new artifact
The indexing process does the following:
1. Check the modified timestamps of all files in the repo (this may seem extreme, but checking timestamps is significantly faster than actually reading a file. Git does the same thing.)
2. Compare these to a "catalog" (stored in SQLite) of the last time that we indexed each of these files to get a list of files to "add" or "remove". If the file exists in the repo but not in the catalog, then we must "add" the file. If it exists in the catalog but not the repo, we must "remove" the file. If it exists in both and was modified after last indexed, then we must update the file. In this case we also add it to the "add" list.
3. For each file to "add", check whether it was indexed on another branch. Here we use a SQLite table that acts as a cache for indexed files. If we find an entry in this table for a file with the same cacheKey, then we only need to add a tag to this entry for the current branch ("addTag"). Otherwise, we must "compute" the artifact.
4. For each file in "remove", check whether it was indexed on another branch. If we find only one entry with the same cacheKey (presumably this should be the entry for the current branch, or something has gone wrong), then this entry should be removed and there will be no more branches that need the artifact, so we want to "delete" it. If there is more than one tag on this artifact, then we should just remove the tag for this branch ("removeTag").
5. After having calculated these four lists of files ("compute", "delete", "addTag", "removeTag"), we pass them to the `CodebaseIndex` so that it can update whatever index-specific storage it might have. Many of them use SQLite and/or LanceDB. The `CodebaseIndex` implements a method called "update" that accepts the four lists and yields progress updates as it iterates over the lists. These progress updates are used to officially mark a file as having been indexed, so that if the extension is closed mid-indexing we don't falsely record progress.
## Existing `CodebaseIndex`es
All indexes must be returned by `getIndexesToBuild` in [`indexCodebase.ts`](./indexCodebase.ts) if they are to be used.
`CodeSnippetsCodebaseIndex`: uses tree-sitter queries to get a list of functions, classes, and other top-level code objects in each file
`FullTextSearchCodebaseIndex`: creates a full-text search index using SQLite FTS5
`ChunkCodebaseIndex`: chunks files recursively by code structure, for use in other embeddings providers like `LanceDbCodebaseIndex`
`LanceDbCodebaseIndex`: calculates embeddings for each chunk and adds them to the LanceDB vector database, with metadata going into SQLite
## Known problems:
- `FullTextSearchCodebaseIndex` doesn't differentiate between tags (branch, repo), so results may come from any branch/repo. LanceDB does this by creating separate tables for each tag (see `tableNameForTag`). The chunk index does this with a second table

View file

@ -1,11 +1,10 @@
import { IndexingProgressUpdate } from "../..";
import { IndexTag, IndexingProgressUpdate } from "../..";
import { MAX_CHUNK_SIZE } from "../../llm/constants";
import { getBasename } from "../../util";
import { DatabaseConnection, SqliteDb, tagToString } from "../refreshIndex";
import {
CodebaseIndex,
IndexResultType,
IndexTag,
MarkCompleteCallback,
RefreshIndexResults,
} from "../types";
@ -106,7 +105,17 @@ export class ChunkCodebaseIndex implements CodebaseIndex {
// Remove tag
for (const item of results.removeTag) {
await db.run(`DELETE FROM chunk_tags WHERE tag = ?`, [tagString]);
await db.run(
`
DELETE FROM chunk_tags
WHERE tag = ?
AND chunkId IN (
SELECT id FROM chunks
WHERE cacheKey = ? AND path = ?
)
`,
[tagString, item.cacheKey, item.path],
);
markComplete([item], IndexResultType.RemoveTag);
}

View file

@ -2,7 +2,9 @@ import { ChunkWithoutID } from "../..";
import { countTokens } from "../../llm/countTokens";
import { basicChunker } from "./basic";
function cleanFragment(fragment: string | undefined): string | undefined {
export function cleanFragment(
fragment: string | undefined,
): string | undefined {
if (!fragment) {
return undefined;
}
@ -28,7 +30,7 @@ function cleanFragment(fragment: string | undefined): string | undefined {
return fragment;
}
function cleanHeader(header: string | undefined): string | undefined {
export function cleanHeader(header: string | undefined): string | undefined {
if (!header) {
return undefined;
}
@ -43,7 +45,10 @@ function cleanHeader(header: string | undefined): string | undefined {
}
// Remove all special characters except alphanumeric, hyphen, space, and underscore
header = header.replace(/[^\w-\s]/g, "").trim();
header = header
.replace(/[^\w-\s]/g, "")
.replace("¶", "")
.trim();
return header;
}

View file

@ -0,0 +1,158 @@
import { Readability } from "@mozilla/readability";
import { Chunk } from "../..";
import { MAX_CHUNK_SIZE } from "../../llm/constants";
import { cleanFragment, cleanHeader } from "../chunk/markdown";
import { PageData } from "./crawl"
export type ArticleComponent = {
title: string;
body: string;
};
export type Article = {
url: string;
subpath: string;
title: string;
article_components: ArticleComponent[];
};
function breakdownArticleComponent(
url: string,
article: ArticleComponent,
subpath: string,
): Chunk[] {
let chunks: Chunk[] = [];
let lines = article.body.split("\n");
let startLine = 0;
let endLine = 0;
let content = "";
let index = 0;
for (let i = 0; i < lines.length; i++) {
let line = lines[i];
if (content.length + line.length <= MAX_CHUNK_SIZE) {
content += line + "\n";
endLine = i;
} else {
chunks.push({
content: content.trim(),
startLine: startLine,
endLine: endLine,
otherMetadata: {
title: cleanHeader(article.title),
},
index: index,
filepath: new URL(
subpath + `#${cleanFragment(article.title)}`,
url,
).toString(),
digest: subpath,
});
content = line + "\n";
startLine = i;
endLine = i;
index += 1;
}
}
// Push the last chunk
if (content) {
chunks.push({
content: content.trim(),
startLine: startLine,
endLine: endLine,
otherMetadata: {
title: cleanHeader(article.title),
},
index: index,
filepath: new URL(
subpath + `#${cleanFragment(article.title)}`,
url,
).toString(),
digest: subpath,
});
}
// Don't use small chunks. Probably they're a mistake. Definitely they'll confuse the embeddings model.
return chunks.filter((c) => c.content.trim().length > 20);
}
export function chunkArticle(articleResult: Article): Chunk[] {
let chunks: Chunk[] = [];
for (let article of articleResult.article_components) {
let articleChunks = breakdownArticleComponent(
articleResult.url,
article,
articleResult.subpath,
);
chunks = [...chunks, ...articleChunks];
}
return chunks;
}
async function extractTitlesAndBodies(
html: string,
): Promise<ArticleComponent[]> {
const { JSDOM } = await import("jsdom");
const dom = new JSDOM(html);
const document = dom.window.document;
const titles = Array.from(document.querySelectorAll("h2"));
const result = titles.map((titleElement) => {
const title = titleElement.textContent || "";
let body = "";
let nextSibling = titleElement.nextElementSibling;
while (nextSibling && nextSibling.tagName !== "H2") {
body += nextSibling.textContent || "";
nextSibling = nextSibling.nextElementSibling;
}
return { title, body };
});
return result;
}
export async function stringToArticle(
url: string,
htmlContent: string,
subpath: string,
): Promise<Article | undefined> {
try {
const { JSDOM } = await import("jsdom");
const dom = new JSDOM(htmlContent);
let reader = new Readability(dom.window.document);
let article = reader.parse();
if (!article) {
return undefined;
}
let article_components = await extractTitlesAndBodies(article.content);
return {
url,
subpath,
title: article.title,
article_components,
};
} catch (err) {
console.error("Error converting URL to article components", err);
return undefined;
}
}
export async function pageToArticle(
page: PageData
): Promise<Article | undefined> {
try {
return stringToArticle(page.url, page.html, page.path);
} catch (err) {
console.error("Error converting URL to article components", err);
return undefined;
}
}

View file

@ -1,13 +1,12 @@
import { Octokit } from "@octokit/rest";
import cheerio from "cheerio";
import fetch from "node-fetch";
// const HCCrawler = require("headless-chrome-crawler");
import { URL } from "url";
const IGNORE_PATHS_ENDING_IN = [
"favicon.ico",
"robots.txt",
".rst.txt",
// ReadTheDocs
"genindex",
"py-modindex",
"search.html",
@ -19,70 +18,6 @@ const IGNORE_PATHS_ENDING_IN = [
const GITHUB_PATHS_TO_TRAVERSE = ["/blob/", "/tree/"];
function shouldFilterPath(pathname: string, baseUrl: URL): boolean {
if (pathname.includes("#")) {
pathname = pathname.slice(0, pathname.indexOf("#"));
}
if (pathname.endsWith("/")) {
pathname = pathname.slice(0, -1);
}
if (baseUrl.hostname === "github.com") {
if (
pathname.split("/").length > 3 &&
!GITHUB_PATHS_TO_TRAVERSE.some((path) => pathname.includes(path))
)
return true;
return false;
}
if (IGNORE_PATHS_ENDING_IN.some((path) => pathname.endsWith(path)))
return true;
return false;
}
async function* crawlLinks(
path: string,
baseUrl: URL,
visited: Set<string>,
): AsyncGenerator<number> {
if (visited.has(path) || shouldFilterPath(path, baseUrl)) {
return;
}
visited.add(path);
yield visited.size;
const response = await fetch(new URL(path, baseUrl));
const text = await response.text();
const $ = cheerio.load(text);
const children: string[] = [];
$("a").each((_, element) => {
const href = $(element).attr("href");
if (!href) {
return;
}
const parsedUrl = new URL(href, baseUrl);
if (
parsedUrl.hostname === baseUrl.hostname &&
!visited.has(parsedUrl.pathname) &&
parsedUrl.pathname.startsWith(baseUrl.pathname)
) {
children.push(parsedUrl.pathname);
}
});
await Promise.all(
children.map(async (child) => {
for await (const _ of crawlLinks(child, baseUrl, visited)) {
}
}),
);
yield visited.size;
}
async function crawlGithubRepo(baseUrl: URL) {
const octokit = new Octokit({
auth: undefined,
@ -109,114 +44,129 @@ async function crawlGithubRepo(baseUrl: URL) {
);
const paths = tree.data.tree
.filter(
(file) => file.type === "blob" && file.path?.endsWith(".md"),
// ||
// file.path?.endsWith(".rst") ||
// file.path?.split("/").includes("documentation") ||
// file.path?.split("/").includes("docs") ||
// file.path?.split("/").includes("doc") ||
// file.path?.split("/").includes("examples") ||
// file.path?.split("/").includes("example")
)
.filter((file) => file.type === "blob" && file.path?.endsWith(".md"))
.map((file) => baseUrl.pathname + "/tree/main/" + file.path);
return paths;
}
export async function* crawlSubpages(
baseUrl: URL,
): AsyncGenerator<number, string[]> {
// Special case for GitHub repos
if (baseUrl.hostname === "github.com") {
return crawlGithubRepo(baseUrl);
async function getLinksFromUrl(url: string, path: string) {
const baseUrl = new URL(url);
const location = new URL(path, url);
let response;
try {
response = await fetch(location.toString());
} catch (error: unknown) {
if (error instanceof Error && error.message.includes("maximum redirect")) {
console.error("Maximum redirect reached for: ", location.toString());
return {
html: "",
links: [],
};
} else {
console.error(error);
return {
html: "",
links: [],
};
}
}
// First, check if the parent of the path redirects to the same page
if (baseUrl.pathname.endsWith("/")) {
baseUrl.pathname = baseUrl.pathname.slice(0, -1);
const html = await response.text();
let links: string[] = [];
if (url.includes("github.com")) {
return {
html,
links,
};
}
let realBaseUrl = new URL(baseUrl);
while (true) {
let parentUrl = new URL(realBaseUrl);
parentUrl.pathname = parentUrl.pathname.split("/").slice(0, -1).join("/");
const $ = cheerio.load(html);
$("a").each((_, element) => {
const href = $(element).attr("href");
if (!href) {
return;
}
const parsedUrl = new URL(href, url);
if (
parentUrl.pathname === realBaseUrl.pathname ||
parentUrl.pathname === ""
parsedUrl.hostname === baseUrl.hostname
// parsedUrl.pathname.startsWith(baseUrl.pathname)
) {
break;
links.push(parsedUrl.pathname);
}
const response = await fetch(parentUrl);
const redirected = response.url.toString() === baseUrl.toString() + "/";
if (!redirected) {
break;
}
realBaseUrl = parentUrl;
}
});
const visited = new Set<string>();
for await (const count of crawlLinks(
realBaseUrl.pathname || "/",
realBaseUrl,
visited,
)) {
yield count;
}
return [...visited];
links = [...new Set(links)].filter((link) => {
return (
!link.includes("#") &&
!IGNORE_PATHS_ENDING_IN.some((ending) => link.endsWith(ending))
);
});
return {
html,
links,
};
}
// class NoEscapeTurndownService extends TurndownService {
// escape(str: string): string {
// return str;
// }
// }
function splitUrl(url: URL) {
const baseUrl = `${url.protocol}//${url.hostname}`;
const basePath = url.pathname;
return {
baseUrl,
basePath,
};
}
// async function convertURLToMarkdown(url: string): Promise<string> {
// try {
// const response = await fetch(url);
// const htmlContent = await response.text();
// const turndown = new NoEscapeTurndownService({
// codeBlockStyle: "fenced",
// headingStyle: "atx",
// }).use([turndownPluginGfm.tables, turndownPluginGfm.strikethrough]);
// const markdown = turndown.turndown(htmlContent);
// return markdown;
// } catch (err) {
// console.error(err);
// throw new Error("Error converting URL to markdown");
// }
// }
export type PageData = {
url: string;
path: string;
html: string;
};
// convertURLToMarkdown("https://python-socketio.readthedocs.io/en/stable").then(
// (md) => {
// console.log(md);
// }
// );
export async function* crawlPage(url: URL): AsyncGenerator<PageData> {
const { baseUrl, basePath } = splitUrl(url);
let paths: string[] = [basePath];
let visited = new Set<string>();
const url = new URL("https://python-socketio.readthedocs.io/en/stable");
const url2 = new URL("https://platform.openai.com/docs/api-reference");
// crawlLinks(url.pathname, url, visited).then(() => {
// console.log(visited);
// });
if (url.hostname === "github.com") {
const githubLinks = await crawlGithubRepo(url);
paths = [...paths, ...githubLinks];
}
// async function hcCrawlLinks() {
// const results: any[] = [];
// const crawler = await HCCrawler.launch({
// // Function to be evaluated in browsers
// evaluatePage: () => ({
// title: $("title").text(),
// }),
// // Function to be called with evaluated results from browsers
// onSuccess: (result: any) => {
// console.log(result);
// results.push(result.url);
// },
// });
// // Queue a request
// await crawler.queue(url.toString());
// await crawler.onIdle(); // Resolved when no queue is left
// await crawler.close(); // Close the crawler
let index = 0;
// return results;
// }
while (index < paths.length) {
const promises = paths
.slice(index, index + 50)
.map((path) => getLinksFromUrl(baseUrl, path));
const results = await Promise.all(promises);
for (const { html, links } of results) {
if (html !== "") {
yield {
url: url.toString(),
path: paths[index],
html: html,
};
}
for (let link of links) {
if (!paths.includes(link)) {
paths.push(link);
}
}
index++;
}
paths = paths.filter((path) =>
results.some(
(result) => result.html !== "" && result.links.includes(path),
),
);
}
}

View file

@ -3,6 +3,9 @@ import sqlite3 from "sqlite3";
import { Chunk } from "../..";
import { getDocsSqlitePath, getLanceDbPath } from "../../util/paths";
import { downloadPreIndexedDocs } from "./preIndexed";
import { default as configs } from "./preIndexedDocs";
const DOCS_TABLE_NAME = "docs";
interface LanceDbDocsRow {
@ -17,28 +20,71 @@ interface LanceDbDocsRow {
[key: string]: any;
}
async function createDocsTable(db: Database<sqlite3.Database>) {
db.exec(`CREATE TABLE IF NOT EXISTS docs (
let dbDocs:Database;
async function getDBDocs() {
if (!dbDocs) {
dbDocs = await open({
filename: getDocsSqlitePath(),
driver: sqlite3.Database,
});
dbDocs.exec(`CREATE TABLE IF NOT EXISTS docs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title STRING NOT NULL,
baseUrl STRING NOT NULL UNIQUE
)`);
}
return dbDocs;
}
export async function retrieveDocs(
baseUrl: string,
vector: number[],
nRetrieve: number,
embeddingsProviderId: string,
nested: boolean = false,
): Promise<Chunk[]> {
const lancedb = await import("vectordb");
const db = await getDBDocs();
const lance = await lancedb.connect(getLanceDbPath());
const downloadDocs = async () => {
const config = configs.find((config) => config.startUrl === baseUrl);
if (config) {
await downloadPreIndexedDocs(embeddingsProviderId, config.title);
return await retrieveDocs(
baseUrl,
vector,
nRetrieve,
embeddingsProviderId,
true,
);
}
return undefined;
};
const tableNames = await lance.tableNames();
if (!tableNames.includes(DOCS_TABLE_NAME)) {
const downloaded = await downloadDocs();
if (downloaded) return downloaded;
}
const table = await lance.openTable(DOCS_TABLE_NAME);
const docs: LanceDbDocsRow[] = await table
let docs: LanceDbDocsRow[] = await table
.search(vector)
.limit(nRetrieve)
.where(`baseUrl = '${baseUrl}'`)
.execute();
docs = docs.filter((doc) => doc.baseUrl === baseUrl);
if ((!docs || docs.length === 0) && !nested) {
const downloaded = await downloadDocs();
if (downloaded) return downloaded;
}
return docs.map((doc) => ({
digest: doc.path,
filepath: doc.path,
@ -79,11 +125,7 @@ export async function addDocs(
}
// Only after add it to SQLite
const db = await open({
filename: getDocsSqlitePath(),
driver: sqlite3.Database,
});
await createDocsTable(db);
const db = await getDBDocs();
await db.run(
`INSERT INTO docs (title, baseUrl) VALUES (?, ?)`,
title,
@ -94,11 +136,13 @@ export async function addDocs(
export async function listDocs(): Promise<
{ title: string; baseUrl: string }[]
> {
const db = await open({
filename: getDocsSqlitePath(),
driver: sqlite3.Database,
});
await createDocsTable(db);
const docs = await db.all(`SELECT title, baseUrl FROM docs`);
const db = await getDBDocs();
const docs = db.all(`SELECT title, baseUrl FROM docs`);
return docs;
}
export async function hasDoc(baseUrl: string) {
const db = await getDBDocs();
const doc = await db.get(`SELECT title FROM docs WHERE baseUrl =?`, baseUrl);
return!!doc;
}

View file

@ -1,18 +0,0 @@
const esbuild = require("esbuild");
(async () => {
// Bundles the extension into one file
await esbuild.build({
entryPoints: ["crawl.ts"],
bundle: true,
outfile: "crawl.js",
external: ["jquery"],
format: "cjs",
platform: "node",
sourcemap: true,
loader: {
// eslint-disable-next-line @typescript-eslint/naming-convention
".node": "file",
},
});
})();

View file

@ -1,22 +1,19 @@
import {
Chunk,
ChunkWithoutID,
EmbeddingsProvider,
IndexingProgressUpdate,
} from "../..";
import { MAX_CHUNK_SIZE } from "../../llm/constants";
import { markdownChunker } from "../chunk/markdown";
import { crawlSubpages } from "./crawl";
import { addDocs, listDocs } from "./db";
import { convertURLToMarkdown } from "./urlToMarkdown";
import { crawlPage } from "./crawl";
import { addDocs, hasDoc } from "./db";
import { pageToArticle, chunkArticle, Article } from "./article";
export async function* indexDocs(
title: string,
baseUrl: URL,
embeddingsProvider: EmbeddingsProvider,
): AsyncGenerator<IndexingProgressUpdate> {
const existingDocs = await listDocs();
if (existingDocs.find((doc) => doc.baseUrl === baseUrl.toString())) {
if (await hasDoc(baseUrl.toString())) {
yield {
progress: 1,
desc: "Already indexed",
@ -29,72 +26,37 @@ export async function* indexDocs(
desc: "Finding subpages",
};
const subpathGenerator = crawlSubpages(baseUrl);
let { value, done } = await subpathGenerator.next();
while (true) {
if (done) {
break;
}
const articles: Article[] = [];
for await (const page of crawlPage(baseUrl)) {
const article = await pageToArticle(page);
if (!article) continue;
articles.push(article);
yield {
progress: 0,
desc: `Finding subpages (${value})`,
desc: `Finding subpages (${page.path})`,
};
const next = await subpathGenerator.next();
value = next.value;
done = next.done;
}
let subpaths = value as string[];
const chunks: Chunk[] = [];
const embeddings: number[][] = [];
let markdownForSubpaths = await Promise.all(
subpaths.map((subpath) => convertURLToMarkdown(new URL(subpath, baseUrl))),
);
// Filter out undefineds
let filteredSubpaths: string[] = [];
let filteredMarkdown: string[] = [];
for (let i = 0; i < subpaths.length; i++) {
if (markdownForSubpaths[i]) {
filteredSubpaths.push(subpaths[i]);
filteredMarkdown.push(markdownForSubpaths[i]!);
}
}
subpaths = filteredSubpaths;
markdownForSubpaths = filteredMarkdown;
for (let i = 0; i < subpaths.length; i++) {
const subpath = subpaths[i];
for (const article of articles) {
yield {
progress: Math.max(1, Math.floor(100 / (subpaths.length + 1))),
desc: `${subpath}`,
progress: Math.max(1, Math.floor(100 / (articles.length + 1))),
desc: `${article.subpath}`,
};
const markdown = markdownForSubpaths[i]!;
const markdownChunks: ChunkWithoutID[] = [];
for await (const chunk of markdownChunker(markdown, MAX_CHUNK_SIZE, 0)) {
markdownChunks.push(chunk);
}
const subpathEmbeddings = await embeddingsProvider.embed(
markdownChunks.map((chunk) => chunk.content),
chunkArticle(article).map(chunk => {
chunks.push(chunk);
return chunk.content;
})
);
markdownChunks.forEach((chunk, index) => {
chunks.push({
...chunk,
filepath:
subpath +
(chunk.otherMetadata?.fragment
? `#${chunk.otherMetadata.fragment}`
: ""),
otherMetadata: chunk.otherMetadata,
index,
digest: subpath,
});
});
embeddings.push(...subpathEmbeddings);
}

View file

@ -0,0 +1,59 @@
import { Chunk } from "../..";
import { addDocs } from "./db";
const request = require("request");
export async function downloadFromS3(
bucket: string,
fileName: string,
region: string,
): Promise<string> {
return new Promise<string>((resolve, reject) => {
let data = "";
const download = request({
url: `https://${bucket}.s3.${region}.amazonaws.com/${fileName}`,
});
download.on("response", (response: any) => {
if (response.statusCode !== 200) {
reject(new Error("No body returned when downloading from S3 bucket"));
}
});
download.on("error", (err: any) => {
reject(err);
});
download.on("data", (chunk: any) => {
data += chunk;
});
download.on("end", () => {
resolve(data);
});
});
}
export interface SiteIndexingResults {
chunks: (Chunk & { embedding: number[] })[];
url: string;
title: string;
}
export async function downloadPreIndexedDocs(
embeddingsProviderId: string,
title: string,
) {
const data = await downloadFromS3(
"continue-indexed-docs",
`${embeddingsProviderId}/${title}`,
"us-west-1",
);
const results = JSON.parse(data) as SiteIndexingResults;
await addDocs(
results.title,
new URL(results.url),
results.chunks,
results.chunks.map((c) => c.embedding),
);
}

View file

@ -0,0 +1,216 @@
export interface SiteIndexingConfig {
startUrl: string;
title: string;
rootUrl: string;
}
const configs: SiteIndexingConfig[] = [
{
title: "Jinja",
startUrl: "https://jinja.palletsprojects.com/en/3.1.x/",
rootUrl: "https://jinja.palletsprojects.com/en/3.1.x/",
},
{
title: "React",
startUrl: "https://react.dev/reference/",
rootUrl: "https://react.dev/reference/",
},
{
title: "PostHog",
startUrl: "https://posthog.com/docs",
rootUrl: "https://posthog.com/docs",
},
{
title: "Express",
startUrl: "https://expressjs.com/en/5x/api.html",
rootUrl: "https://expressjs.com/en/5x/",
},
{
title: "OpenAI",
startUrl: "https://platform.openai.com/docs/",
rootUrl: "https://platform.openai.com/docs/",
},
{
title: "Prisma",
startUrl: "https://www.prisma.io/docs",
rootUrl: "https://www.prisma.io/docs",
},
{
title: "Boto3",
startUrl:
"https://boto3.amazonaws.com/v1/documentation/api/latest/index.html",
rootUrl: "https://boto3.amazonaws.com/v1/documentation/api/latest/",
},
{
title: "Pytorch",
startUrl: "https://pytorch.org/docs/stable/",
rootUrl: "https://pytorch.org/docs/stable/",
},
{
title: "Redis",
startUrl: "https://redis.io/docs/",
rootUrl: "https://redis.io/docs/",
},
{
title: "Axios",
startUrl: "https://axios-http.com/docs/intro",
rootUrl: "https://axios-http.com/docs",
},
{
title: "Redwood JS",
startUrl: "https://redwoodjs.com/docs/introduction",
rootUrl: "https://redwoodjs.com/docs",
},
{
title: "GraphQL",
startUrl: "https://graphql.org/learn/",
rootUrl: "https://graphql.org/learn/",
},
{
title: "Typescript",
startUrl: "https://www.typescriptlang.org/docs/",
rootUrl: "https://www.typescriptlang.org/docs/",
},
{
title: "Jest",
startUrl: "https://jestjs.io/docs/getting-started",
rootUrl: "https://jestjs.io/docs",
},
{
title: "Tailwind CSS",
startUrl: "https://tailwindcss.com/docs/installation",
rootUrl: "https://tailwindcss.com/docs",
},
{
title: "Vue.js",
startUrl: "https://vuejs.org/guide/introduction.html",
rootUrl: "https://vuejs.org",
},
{
title: "Svelte",
startUrl: "https://svelte.dev/docs/introduction",
rootUrl: "https://svelte.dev/docs",
},
{
title: "GitHub Actions",
startUrl: "https://docs.github.com/en/actions",
rootUrl: "https://docs.github.com/en/actions",
},
{
title: "NodeJS",
startUrl: "https://nodejs.org/docs/latest/api/",
rootUrl: "https://nodejs.org/docs/latest/api/",
},
{
title: "Socket.io",
startUrl: "https://socket.io/docs/v4/",
rootUrl: "https://socket.io/docs/v4/",
},
{
title: "Gradle",
startUrl: "https://docs.gradle.org/current/userguide/userguide.html",
rootUrl: "https://docs.gradle.org/current",
},
{
title: "Redux Toolkit",
startUrl: "https://redux-toolkit.js.org/introduction/getting-started",
rootUrl: "https://redux-toolkit.js.org",
},
{
title: "Chroma",
startUrl: "https://docs.trychroma.com/",
rootUrl: "https://docs.trychroma.com/",
},
{
title: "SQLite",
startUrl: "https://www.sqlite.org/docs.html",
rootUrl: "https://www.sqlite.org",
},
{
title: "Redux",
startUrl: "https://redux.js.org/introduction/getting-started",
rootUrl: "https://redux.js.org",
},
{
title: "Prettier",
startUrl: "https://prettier.io/docs/en/",
rootUrl: "https://prettier.io/docs/en/",
},
{
title: "VS Code Extension API",
startUrl: "https://code.visualstudio.com/api",
rootUrl: "https://code.visualstudio.com/api",
},
{
title: "Continue",
startUrl: "https://continue.dev/docs/intro",
rootUrl: "https://continue.dev/docs",
},
{
title: "jQuery",
startUrl: "https://api.jquery.com/",
rootUrl: "https://api.jquery.com/",
},
{
title: "Python",
startUrl: "https://docs.python.org/3/",
rootUrl: "https://docs.python.org/3/",
},
{
title: "Rust",
startUrl: "https://doc.rust-lang.org/book/",
rootUrl: "https://doc.rust-lang.org/book/",
},
{
title: "IntelliJ Platform SDK",
startUrl: "https://plugins.jetbrains.com/docs/intellij/welcome.html",
rootUrl: "https://plugins.jetbrains.com/docs/intellij",
},
{
title: "Docker",
startUrl: "https://docs.docker.com/",
rootUrl: "https://docs.docker.com/",
},
{
title: "NPM",
startUrl: "https://docs.npmjs.com/",
rootUrl: "https://docs.npmjs.com/",
},
{
title: "TipTap",
startUrl: "https://tiptap.dev/docs/editor/introduction",
rootUrl: "https://tiptap.dev/docs",
},
{
title: "esbuild",
startUrl: "https://esbuild.github.io/",
rootUrl: "https://esbuild.github.io/",
},
{
title: "Tree Sitter",
startUrl: "https://tree-sitter.github.io/tree-sitter/",
rootUrl: "https://tree-sitter.github.io/tree-sitter/",
},
{
title: "Netlify",
startUrl: "https://docs.netlify.com/",
rootUrl: "https://docs.netlify.com/",
},
{
title: "Replicate",
startUrl: "https://replicate.com/docs",
rootUrl: "https://replicate.com/docs",
},
{
title: "HTML",
startUrl: "https://www.w3schools.com/html/default.asp",
rootUrl: "https://www.w3schools.com/html",
},
{
title: "CSS",
startUrl: "https://www.w3schools.com/css/default.asp",
rootUrl: "https://www.w3schools.com/css",
},
];
export default configs;

View file

@ -1,94 +0,0 @@
import { Octokit } from "@octokit/rest";
import { NodeHtmlMarkdown, PostProcessResult } from "node-html-markdown";
const nhm = new NodeHtmlMarkdown(
{},
{
a: {
postprocess: (ctx) => {
if (ctx.node.tagName === "A") {
// Remove sections links (e.g. '<a href="#section-name" title="Link to this heading">#</a>')
if (ctx.content.length <= 1) {
return PostProcessResult.RemoveNode;
}
}
return ctx.content;
},
},
},
undefined,
);
const STRIP_BEFORE = ["\n# "];
const STRIP_AFTER_AND_INCLUDING = ["Was this page helpful?"];
const octokit = new Octokit({
auth: undefined,
});
async function retrieveGitHubBlob(url: URL): Promise<string | undefined> {
const [_, owner, repo, _tree, _main, ...path] = url.pathname.split("/");
const response = await octokit.repos.getContent({
owner,
repo,
path: path.join("/"),
});
if (response.status !== 200) {
return undefined;
}
const content = Buffer.from(
(response.data as any).content || "",
"base64",
).toString();
const fileExtension = url.pathname.split(".").slice(-1)[0];
if (fileExtension === "md") {
return content;
}
return `\`\`\`${fileExtension} title=${path.join("/")}\n${content}\n\`\`\``;
}
export async function convertURLToMarkdown(
url: URL,
): Promise<string | undefined> {
try {
if (url.hostname === "github.com") {
return await retrieveGitHubBlob(url);
}
const response = await fetch(url);
if (!response.ok) {
return undefined;
}
const htmlContent = await response.text();
let markdown = nhm.translate(htmlContent).trimEnd();
// Check for 404
if (markdown.includes("404 Not Found")) {
return undefined;
}
// Strip above and below certain phrases
STRIP_BEFORE.forEach((phrase) => {
const index = markdown.indexOf(phrase);
if (index !== -1) {
markdown = markdown.slice(index);
}
});
STRIP_AFTER_AND_INCLUDING.forEach((phrase) => {
const index = markdown.lastIndexOf(phrase);
if (index !== -1) {
markdown = markdown.slice(0, index);
}
});
return markdown;
} catch (err) {
console.error("Error converting URL to markdown", err);
return undefined;
}
}

View file

@ -1,5 +1,6 @@
import { EmbedOptions } from "../..";
import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider";
import { fetchWithExponentialBackoff } from "./util";
class DeepInfraEmbeddingsProvider extends BaseEmbeddingsProvider {
static defaultOptions: Partial<EmbedOptions> | undefined = {
@ -7,11 +8,11 @@ class DeepInfraEmbeddingsProvider extends BaseEmbeddingsProvider {
};
get id(): string {
return "deepinfra::" + this.options.model;
return this.options.model ?? "deepinfra";
}
async embed(chunks: string[]) {
const resp = await fetch(
const resp = await fetchWithExponentialBackoff(
`https://api.deepinfra.com/v1/inference/${this.options.model}`,
{
method: "POST",
@ -22,7 +23,6 @@ class DeepInfraEmbeddingsProvider extends BaseEmbeddingsProvider {
},
);
const data = await resp.json();
console.log(data);
return data.embeddings;
}
}

View file

@ -2,7 +2,7 @@ import { EmbedOptions } from "../..";
import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider";
async function embedOne(chunk: string, options: EmbedOptions) {
const resp = await fetch(`${options.apiBase}/api/embeddings`, {
const resp = await fetch(new URL("api/embeddings", options.apiBase), {
method: "POST",
body: JSON.stringify({
model: options.model,
@ -19,11 +19,11 @@ async function embedOne(chunk: string, options: EmbedOptions) {
class OllamaEmbeddingsProvider extends BaseEmbeddingsProvider {
static defaultOptions: Partial<EmbedOptions> | undefined = {
apiBase: "http://localhost:11434",
apiBase: "http://localhost:11434/",
};
get id(): string {
return "ollama::" + this.options.model;
return this.options.model ?? "ollama";
}
async embed(chunks: string[]) {

View file

@ -1,35 +1,34 @@
import { EmbedOptions } from "../..";
import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider";
import { fetchWithExponentialBackoff } from "./util";
class OpenAIEmbeddingsProvider extends BaseEmbeddingsProvider {
static defaultOptions: Partial<EmbedOptions> | undefined = {
apiBase: "https://api.openai.com/v1",
apiBase: "https://api.openai.com/v1/",
model: "text-embedding-3-small",
};
get id(): string {
return "openai::" + this.options.model;
return this.options.model ?? "openai";
}
async embed(chunks: string[]) {
let apiBase = this.options.apiBase;
if (apiBase?.endsWith("/")) {
apiBase = apiBase.slice(0, -1);
}
return await Promise.all(
chunks.map(async (chunk) => {
const resp = await fetch(`${apiBase}/embeddings`, {
method: "POST",
body: JSON.stringify({
input: chunk,
model: this.options.model,
}),
headers: {
Authorization: `Bearer ${this.options.apiKey}`,
"Content-Type": "application/json",
const resp = await fetchWithExponentialBackoff(
new URL("embeddings", this.options.apiBase).toString(),
{
method: "POST",
body: JSON.stringify({
input: chunk,
model: this.options.model,
}),
headers: {
Authorization: `Bearer ${this.options.apiKey}`,
"Content-Type": "application/json",
},
},
});
);
const data = await resp.json();
return data.data[0].embedding;
}),

View file

@ -36,7 +36,7 @@ class TransformersJsEmbeddingsProvider extends BaseEmbeddingsProvider {
}
get id(): string {
return "transformers-js";
return "sentence-transformers/all-MiniLM-L6-v2";
}
async embed(chunks: string[]) {

View file

@ -0,0 +1,23 @@
export const fetchWithExponentialBackoff = async (
url: string,
options: RequestInit,
retries: number = 5,
delay: number = 1000,
): Promise<Response> => {
try {
const response = await fetch(url, options);
if (!response.ok && response.status === 429 && retries > 0) {
// Wait for delay milliseconds and retry
await new Promise((resolve) => setTimeout(resolve, delay));
return fetchWithExponentialBackoff(url, options, retries - 1, delay * 2);
}
return response;
} catch (error) {
if (retries > 0) {
// Wait for delay milliseconds and retry
await new Promise((resolve) => setTimeout(resolve, delay));
return fetchWithExponentialBackoff(url, options, retries - 1, delay * 2);
}
throw error;
}
};

View file

@ -1,10 +1,11 @@
import { IDE, IndexingProgressUpdate } from "..";
import { IDE, IndexTag, IndexingProgressUpdate } from "..";
import { ConfigHandler } from "../config/handler";
import { CodeSnippetsCodebaseIndex } from "./CodeSnippetsIndex";
import { FullTextSearchCodebaseIndex } from "./FullTextSearch";
import { LanceDbIndex } from "./LanceDbIndex";
import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex";
import { getComputeDeleteAddRemove } from "./refreshIndex";
import { CodebaseIndex, IndexTag } from "./types";
import { CodebaseIndex } from "./types";
export class PauseToken {
constructor(private _paused: boolean) {}
@ -39,6 +40,7 @@ export class CodebaseIndexer {
this.ide.readFile.bind(this.ide),
),
new FullTextSearchCodebaseIndex(),
new CodeSnippetsCodebaseIndex(this.ide),
];
return indexes;
@ -57,7 +59,7 @@ export class CodebaseIndexer {
let completedDirs = 0;
yield {
progress: 0,
progress: 0.01,
desc: "Starting indexing...",
};

View file

@ -2,12 +2,11 @@ import crypto from "crypto";
import * as fs from "fs";
import { Database, open } from "sqlite";
import sqlite3 from "sqlite3";
import { IndexingProgressUpdate } from "..";
import { IndexTag, IndexingProgressUpdate } from "..";
import { getIndexSqlitePath } from "../util/paths";
import {
CodebaseIndex,
IndexResultType,
IndexTag,
LastModifiedMap,
MarkCompleteCallback,
PathAndCacheKey,

View file

@ -1,4 +1,4 @@
import { IndexingProgressUpdate } from "..";
import { IndexTag, IndexingProgressUpdate } from "..";
export enum IndexResultType {
Compute = "compute",
@ -26,12 +26,6 @@ export type PathAndCacheKey = {
cacheKey: string;
};
export interface IndexTag {
directory: string;
branch: string;
artifactId: string;
}
export type RefreshIndexResults = {
compute: PathAndCacheKey[];
del: PathAndCacheKey[];

View file

@ -4,6 +4,7 @@ import {
chatmlTemplateMessages,
codeLlama70bTemplateMessages,
deepseekTemplateMessages,
gemmaTemplateMessage,
llama2TemplateMessages,
llavaTemplateMessages,
neuralChatTemplateMessages,
@ -20,6 +21,7 @@ import {
codeLlama70bEditPrompt,
codellamaEditPrompt,
deepseekEditPrompt,
gemmaEditPrompt,
mistralEditPrompt,
neuralChatEditPrompt,
openchatEditPrompt,
@ -44,7 +46,8 @@ const PROVIDER_SUPPORTS_IMAGES: ModelProvider[] = [
"ollama",
"google-palm",
"free-trial",
"msty"
"msty",
"anthropic",
];
function modelSupportsImages(provider: ModelProvider, model: string): boolean {
@ -56,6 +59,10 @@ function modelSupportsImages(provider: ModelProvider, model: string): boolean {
return true;
}
if (model.includes("claude-3")) {
return true;
}
if (["gpt-4-vision-preview"].includes(model)) {
return true;
}
@ -126,6 +133,10 @@ function autodetectTemplateType(model: string): TemplateType | undefined {
return "chatml";
}
if (lower.includes("gemma")) {
return "gemma";
}
if (lower.includes("phi2")) {
return "phi2";
}
@ -181,7 +192,7 @@ function autodetectTemplateFunction(
return null;
}
const templateType = explicitTemplate || autodetectTemplateType(model);
const templateType = explicitTemplate ?? autodetectTemplateType(model);
if (templateType) {
const mapping: Record<TemplateType, any> = {
@ -198,6 +209,7 @@ function autodetectTemplateFunction(
"neural-chat": neuralChatTemplateMessages,
llava: llavaTemplateMessages,
"codellama-70b": codeLlama70bTemplateMessages,
gemma: gemmaTemplateMessage,
none: null,
};
@ -211,7 +223,7 @@ function autodetectPromptTemplates(
model: string,
explicitTemplate: TemplateType | undefined = undefined,
) {
const templateType = explicitTemplate || autodetectTemplateType(model);
const templateType = explicitTemplate ?? autodetectTemplateType(model);
const templates: Record<string, any> = {};
let editTemplate = null;
@ -242,6 +254,8 @@ function autodetectPromptTemplates(
editTemplate = codeLlama70bEditPrompt;
} else if (templateType === "anthropic") {
editTemplate = claudeEditPrompt;
} else if (templateType === "gemma") {
editTemplate = gemmaEditPrompt;
} else if (templateType) {
editTemplate = simplestEditPrompt;
}

View file

@ -44,7 +44,7 @@ function countTokens(
return content.reduce((acc, part) => {
return acc + part.type === "imageUrl"
? countImageTokens(part)
: encoding.encode(part.text || "", "all", []).length;
: encoding.encode(part.text ?? "", "all", []).length;
}, 0);
} else {
return encoding.encode(content, "all", []).length;
@ -205,19 +205,15 @@ function pruneChatHistory(
for (let i = 0; i < longerThanOneThird.length; i++) {
// Prune line-by-line from the top
const message = longerThanOneThird[i];
let lines = stripImages(message.content).split("\n");
let tokensRemoved = 0;
while (
tokensRemoved < distanceFromThird[i] &&
totalTokens > contextLength &&
lines.length > 0
) {
const delta = countTokens("\n" + lines.shift()!, modelName);
tokensRemoved += delta;
totalTokens -= delta;
}
message.content = lines.join("\n");
let content = stripImages(message.content);
const deltaNeeded = totalTokens - contextLength;
const delta = Math.min(deltaNeeded, distanceFromThird[i]);
message.content = pruneStringFromTop(
modelName,
countTokens(message.content, modelName) - delta,
content,
);
totalTokens -= delta;
}
// 1. Replace beyond last 5 messages with summary

View file

@ -29,6 +29,7 @@ import {
compileChatMessages,
countTokens,
pruneRawPromptFromTop,
stripImages,
} from "./countTokens";
import CompletionOptionsForModels from "./templates/options";
@ -79,22 +80,22 @@ export abstract class BaseLLM implements ILLM {
};
const templateType =
options.template || autodetectTemplateType(options.model);
options.template ?? autodetectTemplateType(options.model);
this.title = options.title;
this.uniqueId = options.uniqueId || "None";
this.uniqueId = options.uniqueId ?? "None";
this.model = options.model;
this.systemMessage = options.systemMessage;
this.contextLength = options.contextLength || DEFAULT_CONTEXT_LENGTH;
this.contextLength = options.contextLength ?? DEFAULT_CONTEXT_LENGTH;
this.completionOptions = {
...options.completionOptions,
model: options.model || "gpt-4",
maxTokens: options.completionOptions?.maxTokens || DEFAULT_MAX_TOKENS,
maxTokens: options.completionOptions?.maxTokens ?? DEFAULT_MAX_TOKENS,
};
if (CompletionOptionsForModels[options.model as ModelName]) {
this.completionOptions = mergeJson(
this.completionOptions,
CompletionOptionsForModels[options.model as ModelName] || {},
CompletionOptionsForModels[options.model as ModelName] ?? {},
);
}
this.requestOptions = options.requestOptions;
@ -103,7 +104,7 @@ export abstract class BaseLLM implements ILLM {
...options.promptTemplates,
};
this.templateMessages =
options.templateMessages ||
options.templateMessages ??
autodetectTemplateFunction(
options.model,
this.providerName,
@ -113,8 +114,8 @@ export abstract class BaseLLM implements ILLM {
this.llmRequestHook = options.llmRequestHook;
this.apiKey = options.apiKey;
this.apiBase = options.apiBase;
if (this.apiBase?.endsWith("/")) {
this.apiBase = this.apiBase.slice(0, -1);
if (this.apiBase && !this.apiBase.endsWith("/")) {
this.apiBase = this.apiBase + "/";
}
this.engine = options.engine;
@ -146,7 +147,7 @@ export abstract class BaseLLM implements ILLM {
options.model,
messages,
contextLength,
options.maxTokens || DEFAULT_MAX_TOKENS,
options.maxTokens ?? DEFAULT_MAX_TOKENS,
this.supportsImages(),
undefined,
functions,
@ -219,7 +220,7 @@ ${prompt}`;
// Most of the requestOptions aren't available in the browser
const headers = new Headers(init?.headers);
for (const [key, value] of Object.entries(
this.requestOptions?.headers || {},
this.requestOptions?.headers ?? {},
)) {
headers.append(key, value as string);
}
@ -245,8 +246,13 @@ ${prompt}`;
}
private _formatChatMessages(messages: ChatMessage[]): string {
const msgsCopy = messages ? messages.map((msg) => ({ ...msg })) : [];
let formatted = "";
for (let msg of messages) {
for (let msg of msgsCopy) {
if ("content" in msg && Array.isArray(msg.content)) {
const content = stripImages(msg.content);
msg.content = content;
}
formatted += `<${msg.role}>\n${msg.content || ""}\n\n`;
}
return formatted;
@ -263,7 +269,7 @@ ${prompt}`;
completionOptions.model,
this.contextLength,
prompt,
completionOptions.maxTokens || DEFAULT_MAX_TOKENS,
completionOptions.maxTokens ?? DEFAULT_MAX_TOKENS,
);
if (!raw) {
@ -302,7 +308,7 @@ ${prompt}`;
completionOptions.model,
this.contextLength,
prompt,
completionOptions.maxTokens || DEFAULT_MAX_TOKENS,
completionOptions.maxTokens ?? DEFAULT_MAX_TOKENS,
);
if (!raw) {

View file

@ -16,7 +16,7 @@ class Anthropic extends BaseLLM {
model: "claude-3-opus-20240229",
maxTokens: 4096,
},
apiBase: "https://api.anthropic.com/v1",
apiBase: "https://api.anthropic.com/v1/",
};
constructor(options: LLMOptions) {
@ -36,11 +36,40 @@ class Anthropic extends BaseLLM {
return finalOptions;
}
private _convertMessages(msgs: ChatMessage[]): any[] {
const messages = msgs
.filter((m) => m.role !== "system")
.map((message) => {
if (typeof message.content === "string") {
return message;
} else {
return {
...message,
content: message.content.map((part) => {
if (part.type === "text") {
return part;
} else {
return {
type: "image",
source: {
type: "base64",
media_type: "image/jpeg",
data: part.imageUrl?.url.split(",")[1],
},
};
}
}),
};
}
});
return messages;
}
protected async *_streamChat(
messages: ChatMessage[],
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
const response = await this.fetch(this.apiBase + "/messages", {
const response = await this.fetch(new URL("messages", this.apiBase), {
method: "POST",
headers: {
"Content-Type": "application/json",
@ -50,7 +79,7 @@ class Anthropic extends BaseLLM {
},
body: JSON.stringify({
...this._convertArgs(options),
messages: messages.filter((m) => m.role !== "system"),
messages: this._convertMessages(messages),
system: this.systemMessage,
stream: true,
}),

View file

@ -4,7 +4,7 @@ import OpenAI from "./OpenAI";
class DeepInfra extends OpenAI {
static providerName: ModelProvider = "deepinfra";
static defaultOptions: Partial<LLMOptions> = {
apiBase: "https://api.deepinfra.com/v1/openai",
apiBase: "https://api.deepinfra.com/v1/openai/",
};
}

View file

@ -3,7 +3,7 @@ import { ChatMessage, CompletionOptions, ModelProvider } from "../..";
import { streamResponse } from "../stream";
// const SERVER_URL = "http://localhost:3000";
const SERVER_URL = "https://node-proxy-server-blue-l6vsfbzhba-uw.a.run.app";
const SERVER_URL = "https://node-proxy-server-green-l6vsfbzhba-uw.a.run.app";
class FreeTrial extends BaseLLM {
static providerName: ModelProvider = "free-trial";
@ -21,7 +21,10 @@ class FreeTrial extends BaseLLM {
frequency_penalty: options.frequencyPenalty,
presence_penalty: options.presencePenalty,
max_tokens: options.maxTokens,
stop: options.stop?.slice(0, 2),
stop:
options.model === "starcoder2-15b"
? options.stop
: options.stop?.slice(0, 2),
temperature: options.temperature,
top_p: options.topP,
};

View file

@ -14,7 +14,7 @@ class GooglePalm extends BaseLLM {
static defaultOptions: Partial<LLMOptions> = {
model: "gemini-pro",
apiBase: "https://generativelanguage.googleapis.com",
apiBase: "https://generativelanguage.googleapis.com/",
};
protected async *_streamComplete(
@ -82,7 +82,10 @@ class GooglePalm extends BaseLLM {
messages: ChatMessage[],
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
const apiURL = `${this.apiBase}/v1/models/${options.model}:streamGenerateContent?key=${this.apiKey}`;
const apiURL = new URL(
`v1/models/${options.model}:streamGenerateContent?key=${this.apiKey}`,
this.apiBase,
);
const body = {
contents: messages.map((msg) => {
return {
@ -157,7 +160,10 @@ class GooglePalm extends BaseLLM {
msgList.push({ content: message.content });
}
const apiURL = `${this.apiBase}/v1beta2/models/${options.model}:generateMessage?key=${this.apiKey}`;
const apiURL = new URL(
`v1beta2/models/${options.model}:generateMessage?key=${this.apiKey}`,
this.apiBase,
);
const body = { prompt: { messages: msgList } };
const response = await this.fetch(apiURL, {
method: "POST",

View file

@ -5,13 +5,13 @@ import { streamSse } from "../stream";
class HuggingFaceTGI extends BaseLLM {
static providerName: ModelProvider = "huggingface-tgi";
static defaultOptions: Partial<LLMOptions> = {
apiBase: "http://localhost:8080",
apiBase: "http://localhost:8080/",
};
constructor(options: LLMOptions) {
super(options);
this.fetch(`${this.apiBase}/info`, {
this.fetch(new URL("info", this.apiBase), {
method: "GET",
}).then(async (response) => {
if (response.status !== 200) {
@ -48,13 +48,16 @@ class HuggingFaceTGI extends BaseLLM {
): AsyncGenerator<string> {
const args = this._convertArgs(options, prompt);
const response = await this.fetch(`${this.apiBase}/generate_stream`, {
method: "POST",
headers: {
"Content-Type": "application/json",
const response = await this.fetch(
new URL("generate_stream", this.apiBase),
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ inputs: prompt, parameters: args }),
},
body: JSON.stringify({ inputs: prompt, parameters: args }),
});
);
for await (const value of streamSse(response)) {
yield value.token.text;

View file

@ -4,7 +4,7 @@ import OpenAI from "./OpenAI";
class LMStudio extends OpenAI {
static providerName: ModelProvider = "lmstudio";
static defaultOptions: Partial<LLMOptions> = {
apiBase: "http://localhost:1234/v1",
apiBase: "http://localhost:1234/v1/",
};
}

View file

@ -5,7 +5,7 @@ import { streamSse } from "../stream";
class LlamaCpp extends BaseLLM {
static providerName: ModelProvider = "llama.cpp";
static defaultOptions: Partial<LLMOptions> = {
apiBase: "http://127.0.0.1:8080",
apiBase: "http://127.0.0.1:8080/",
};
private _convertArgs(options: CompletionOptions, prompt: string) {
@ -30,7 +30,7 @@ class LlamaCpp extends BaseLLM {
...this.requestOptions?.headers,
};
const resp = await this.fetch(`${this.apiBase}/completion`, {
const resp = await this.fetch(new URL("completion", this.apiBase), {
method: "POST",
headers,
body: JSON.stringify({

View file

@ -4,7 +4,7 @@ import OpenAI from "./OpenAI";
class Mistral extends OpenAI {
static providerName: ModelProvider = "mistral";
static defaultOptions: Partial<LLMOptions> = {
apiBase: "https://api.mistral.ai/v1",
apiBase: "https://api.mistral.ai/v1/",
model: "mistral-small",
};
}

View file

@ -11,7 +11,7 @@ import { streamResponse } from "../stream";
class Ollama extends BaseLLM {
static providerName: ModelProvider = "ollama";
static defaultOptions: Partial<LLMOptions> = {
apiBase: "http://localhost:11434",
apiBase: "http://localhost:11434/",
model: "codellama-7b",
};
@ -21,7 +21,7 @@ class Ollama extends BaseLLM {
if (options.model === "AUTODETECT") {
return;
}
this.fetch(`${this.apiBase}/api/show`, {
this.fetch(this.getEndpoint("api/show"), {
method: "POST",
headers: {},
body: JSON.stringify({ name: this._getModel() }),
@ -90,7 +90,7 @@ class Ollama extends BaseLLM {
"starcoder-1b": "starcoder:1b",
"starcoder-3b": "starcoder:3b",
"stable-code-3b": "stable-code:3b",
}[this.model] || this.model
}[this.model] ?? this.model
);
}
@ -115,7 +115,7 @@ class Ollama extends BaseLLM {
const finalOptions: any = {
model: this._getModel(),
raw: true,
keep_alive: 60 * 30, // 30 minutes
keep_alive: options.keepAlive ?? 60 * 30, // 30 minutes
options: {
temperature: options.temperature,
top_p: options.topP,
@ -137,11 +137,20 @@ class Ollama extends BaseLLM {
return finalOptions;
}
private getEndpoint(endpoint: string): URL {
let base = this.apiBase;
if (process.env.IS_BINARY) {
base = base?.replace("localhost", "127.0.0.1");
}
return new URL(endpoint, base);
}
protected async *_streamComplete(
prompt: string,
options: CompletionOptions,
): AsyncGenerator<string> {
const response = await this.fetch(`${this.apiBase}/api/generate`, {
const response = await this.fetch(this.getEndpoint("api/generate"), {
method: "POST",
headers: {
"Content-Type": "application/json",
@ -180,7 +189,7 @@ class Ollama extends BaseLLM {
messages: ChatMessage[],
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
const response = await this.fetch(`${this.apiBase}/api/chat`, {
const response = await this.fetch(this.getEndpoint("api/chat"), {
method: "POST",
headers: {
"Content-Type": "application/json",
@ -218,9 +227,13 @@ class Ollama extends BaseLLM {
}
async listModels(): Promise<string[]> {
const response = await this.fetch(`${this.apiBase}/api/tags`, {
method: "GET",
});
const response = await this.fetch(
// localhost was causing fetch failed in pkg binary only for this Ollama endpoint
this.getEndpoint("api/tags"),
{
method: "GET",
},
);
const data = await response.json();
return data.models.map((model: any) => model.name);
}

View file

@ -41,7 +41,7 @@ class OpenAI extends BaseLLM {
static providerName: ModelProvider = "openai";
static defaultOptions: Partial<LLMOptions> = {
apiBase: "https://api.openai.com/v1",
apiBase: "https://api.openai.com/v1/",
};
protected _convertMessage(message: ChatMessage) {
@ -71,9 +71,11 @@ class OpenAI extends BaseLLM {
top_p: options.topP,
frequency_penalty: options.frequencyPenalty,
presence_penalty: options.presencePenalty,
stop: this.apiBase?.includes(":1337")
? options.stop?.slice(0, 4)
: options.stop,
stop:
// Jan + Azure OpenAI don't truncate and will throw an error
this.apiBase?.includes(":1337") || this.apiType === "azure"
? options.stop?.slice(0, 4)
: options.stop,
};
return finalOptions;
@ -95,22 +97,21 @@ class OpenAI extends BaseLLM {
}
private _getEndpoint(
endpoint: "/chat/completions" | "/completions" | "/models",
endpoint: "chat/completions" | "completions" | "models",
) {
if (this.apiType === "azure") {
return `${this.apiBase}/openai/deployments/${this.engine}${endpoint}?api-version=${this.apiVersion}`;
return new URL(
`openai/deployments/${this.engine}/${endpoint}?api-version=${this.apiVersion}`,
this.apiBase,
);
} else {
let url = this.apiBase;
if (!url) {
if (!this.apiBase) {
throw new Error(
"No API base URL provided. Please set the 'apiBase' option in config.json",
);
}
if (url.endsWith("/")) {
url = url.slice(0, -1);
}
return url + endpoint;
return new URL(endpoint, this.apiBase);
}
}
@ -134,12 +135,12 @@ class OpenAI extends BaseLLM {
args.prompt = prompt;
delete args.messages;
const response = await this.fetch(this._getEndpoint("/completions"), {
const response = await this.fetch(this._getEndpoint("completions"), {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${this.apiKey}`,
"api-key": this.apiKey || "", // For Azure
"api-key": this.apiKey ?? "", // For Azure
},
body: JSON.stringify({
...args,
@ -184,12 +185,12 @@ class OpenAI extends BaseLLM {
...m,
content: m.content === "" ? " " : m.content,
})) as any;
const response = await this.fetch(this._getEndpoint("/chat/completions"), {
const response = await this.fetch(this._getEndpoint("chat/completions"), {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${this.apiKey}`,
"api-key": this.apiKey || "", // For Azure
"api-key": this.apiKey ?? "", // For Azure
},
body: JSON.stringify(body),
});
@ -202,11 +203,11 @@ class OpenAI extends BaseLLM {
}
async listModels(): Promise<string[]> {
const response = await this.fetch(this._getEndpoint("/models"), {
const response = await this.fetch(this._getEndpoint("models"), {
method: "GET",
headers: {
Authorization: `Bearer ${this.apiKey}`,
"api-key": this.apiKey || "", // For Azure
"api-key": this.apiKey ?? "", // For Azure
},
});

View file

@ -4,7 +4,7 @@ import OpenAI from "./OpenAI";
class TextGenWebUI extends OpenAI {
static providerName: ModelProvider = "text-gen-webui";
static defaultOptions: Partial<LLMOptions> = {
apiBase: "http://localhost:5000/v1",
apiBase: "http://localhost:5000/v1/",
};
}

View file

@ -10,7 +10,7 @@ import OpenAI from "./OpenAI";
class Together extends OpenAI {
static providerName: ModelProvider = "together";
static defaultOptions: Partial<LLMOptions> = {
apiBase: "https://api.together.xyz/v1",
apiBase: "https://api.together.xyz/v1/",
};
private static MODEL_IDS: { [name: string]: string } = {

View file

@ -115,7 +115,7 @@ export async function llmFromDescription(
...desc.completionOptions,
};
systemMessage = desc.systemMessage || systemMessage;
systemMessage = desc.systemMessage ?? systemMessage;
if (systemMessage !== undefined) {
systemMessage = await renderTemplatedString(systemMessage, readFile);
}
@ -124,14 +124,14 @@ export async function llmFromDescription(
...desc,
completionOptions: {
...finalCompletionOptions,
model: desc.model || cls.defaultOptions?.model || "codellama-7b", // TODO: Fix up all the ?'s
maxTokens:
finalCompletionOptions.maxTokens ||
cls.defaultOptions?.completionOptions?.maxTokens ||
DEFAULT_MAX_TOKENS,
model: (desc.model || cls.defaultOptions?.model) ?? "codellama-7b",
maxTokens: (
finalCompletionOptions.maxTokens ??
cls.defaultOptions?.completionOptions?.maxTokens
) ?? DEFAULT_MAX_TOKENS,
},
systemMessage,
};
};
return new cls(options);
}

View file

@ -287,11 +287,30 @@ function codeLlama70bTemplateMessages(msgs: ChatMessage[]): string {
return prompt;
}
/**
<start_of_turn>user
What is Cramer's Rule?<end_of_turn>
<start_of_turn>model
*/
function gemmaTemplateMessage(msgs: ChatMessage[]): string {
let prompt = "";
for (const msg of msgs) {
prompt += `<start_of_turn>${
msg.role === "assistant" ? "model" : "user"
}\n${stripImages(msg.content).trim()}<end_of_turn>\n`;
}
prompt += "<start_of_turn>model\n";
return prompt;
}
export {
anthropicTemplateMessages,
chatmlTemplateMessages,
codeLlama70bTemplateMessages,
deepseekTemplateMessages,
gemmaTemplateMessage,
llama2TemplateMessages,
llavaTemplateMessages,
neuralChatTemplateMessages,

View file

@ -171,6 +171,19 @@ Output only a code block with the rewritten code:
\`\`\`${otherData.language}`,
},
];
const gemmaEditPrompt = `<start_of_turn>user
You are an expert programmer and write code on the first attempt without any errors or fillers. Rewrite the code to satisfy this request: "{{{userInput}}}"
\`\`\`{{{language}}}
{{{codeToEdit}}}
\`\`\`<end_of_turn>
<start_of_turn>model
Sure! Here's the code you requested:
\`\`\`{{{language}}}
`;
export {
alpacaEditPrompt,
claudeEditPrompt,
@ -178,6 +191,7 @@ export {
codellamaEditPrompt,
codellamaInfillEditPrompt,
deepseekEditPrompt,
gemmaEditPrompt,
gptEditPrompt,
mistralEditPrompt,
neuralChatEditPrompt,

1011
core/package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -19,7 +19,10 @@
"ts-jest": "^29.1.1"
},
"dependencies": {
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.0.2",
"@types/jsdom": "^21.1.6",
"@types/mozilla-readability": "^0.2.1",
"@types/node-fetch": "^2.6.11",
"@xenova/transformers": "^2.14.0",
"adf-to-md": "^1.1.0",
@ -34,7 +37,9 @@
"http-proxy-agent": "^7.0.1",
"https-proxy-agent": "^7.0.3",
"js-tiktoken": "^1.0.8",
"jsdom": "^24.0.0",
"llama-tokenizer-js": "^1.1.3",
"llm-code-highlighter": "^0.0.14",
"node-fetch": "^3.3.2",
"node-html-markdown": "^1.3.0",
"ollama": "^0.4.6",
@ -42,6 +47,7 @@
"pg": "^8.11.3",
"posthog-node": "^3.6.2",
"replicate": "^0.26.0",
"request": "^2.88.2",
"socket.io-client": "^4.7.3",
"sqlite": "^5.1.1",
"sqlite3": "^5.1.7",
@ -52,5 +58,9 @@
},
"puppeteer": {
"chromium_revision": "119.0.6045.105"
},
"engine-strict": true,
"engines": {
"node": ">=20.11.0"
}
}

View file

@ -10,6 +10,8 @@ import {
SerializedContinueConfig,
SessionInfo,
} from ".";
import { AutocompleteInput } from "./autocomplete/completionProvider";
import { IdeProtocol } from "./web/webviewProtocol";
export type ProtocolGeneratorType<T> = AsyncGenerator<{
done?: boolean;
@ -34,6 +36,7 @@ export type Protocol = {
{ model: SerializedContinueConfig["models"][number] },
void,
];
"config/ideSettingsUpdate": [IdeSettings, void];
"config/getBrowserSerialized": [
undefined,
Promise<BrowserSerializedContinueConfig>,
@ -54,10 +57,9 @@ export type Protocol = {
Promise<ContextSubmenuItem[]>,
];
"context/addDocs": [{ title: string; url: string }, void];
"autocomplete/complete": [
{ filepath: string; line: number; column: number },
string[],
];
"autocomplete/complete": [AutocompleteInput, Promise<string[]>];
"autocomplete/cancel": [undefined, void];
"autocomplete/accept": [{ completionId: string }, void];
"command/run": [
{
input: string;
@ -96,3 +98,13 @@ export type Protocol = {
ProtocolGeneratorType<MessageContent>,
];
};
export interface IdeSettings {
remoteConfigServerUrl: string | undefined;
remoteConfigSyncPeriod: number;
userToken: string;
}
export type ReverseProtocol = IdeProtocol & {
getIdeSettings: [undefined, IdeSettings];
};

View file

@ -0,0 +1,9 @@
(struct_specifier name: (type_identifier) @name.definition.class body:(_)) @definition.class
(declaration type: (union_specifier name: (type_identifier) @name.definition.class)) @definition.class
(function_declarator declarator: (identifier) @name.definition.function) @definition.function
(type_definition declarator: (type_identifier) @name.definition.type) @definition.type
(enum_specifier name: (type_identifier) @name.definition.type) @definition.type

View file

@ -0,0 +1,46 @@
(class_declaration
name: (identifier) @name.definition.class
) @definition.class
(class_declaration
bases: (base_list (_) @name.reference.class)
) @reference.class
(interface_declaration
name: (identifier) @name.definition.interface
) @definition.interface
(interface_declaration
bases: (base_list (_) @name.reference.interface)
) @reference.interface
(method_declaration
name: (identifier) @name.definition.method
) @definition.method
(object_creation_expression
type: (identifier) @name.reference.class
) @reference.class
(type_parameter_constraints_clause
target: (identifier) @name.reference.class
) @reference.class
(type_constraint
type: (identifier) @name.reference.class
) @reference.class
(variable_declaration
type: (identifier) @name.reference.class
) @reference.class
(invocation_expression
function:
(member_access_expression
name: (identifier) @name.reference.send
)
) @reference.send
(namespace_declaration
name: (identifier) @name.definition.module
) @definition.module

View file

@ -0,0 +1,15 @@
(struct_specifier name: (type_identifier) @name.definition.class body:(_)) @definition.class
(declaration type: (union_specifier name: (type_identifier) @name.definition.class)) @definition.class
(function_declarator declarator: (identifier) @name.definition.function) @definition.function
(function_declarator declarator: (field_identifier) @name.definition.function) @definition.function
(function_declarator declarator: (qualified_identifier scope: (namespace_identifier) @scope name: (identifier) @name.definition.method)) @definition.method
(type_definition declarator: (type_identifier) @name.definition.type) @definition.type
(enum_specifier name: (type_identifier) @name.definition.type) @definition.type
(class_specifier name: (type_identifier) @name.definition.class) @definition.class

View file

@ -0,0 +1,8 @@
;; defun/defsubst
(function_definition name: (symbol) @name.definition.function) @definition.function
;; Treat macros as function definitions for the sake of TAGS.
(macro_definition name: (symbol) @name.definition.function) @definition.function
;; Match function calls
(list (symbol) @name.reference.function) @reference.function

View file

@ -0,0 +1,54 @@
; Definitions
; * modules and protocols
(call
target: (identifier) @ignore
(arguments (alias) @name.definition.module)
(#match? @ignore "^(defmodule|defprotocol)$")) @definition.module
; * functions/macros
(call
target: (identifier) @ignore
(arguments
[
; zero-arity functions with no parentheses
(identifier) @name.definition.function
; regular function clause
(call target: (identifier) @name.definition.function)
; function clause with a guard clause
(binary_operator
left: (call target: (identifier) @name.definition.function)
operator: "when")
])
(#match? @ignore "^(def|defp|defdelegate|defguard|defguardp|defmacro|defmacrop|defn|defnp)$")) @definition.function
; References
; ignore calls to kernel/special-forms keywords
(call
target: (identifier) @ignore
(#match? @ignore "^(def|defp|defdelegate|defguard|defguardp|defmacro|defmacrop|defn|defnp|defmodule|defprotocol|defimpl|defstruct|defexception|defoverridable|alias|case|cond|else|for|if|import|quote|raise|receive|require|reraise|super|throw|try|unless|unquote|unquote_splicing|use|with)$"))
; ignore module attributes
(unary_operator
operator: "@"
operand: (call
target: (identifier) @ignore))
; * function call
(call
target: [
; local
(identifier) @name.reference.call
; remote
(dot
right: (identifier) @name.reference.call)
]) @reference.call
; * pipe into function call
(binary_operator
operator: "|>"
right: (identifier) @name.reference.call) @reference.call
; * modules
(alias) @name.reference.module @reference.module

View file

@ -0,0 +1,19 @@
(value_declaration (function_declaration_left (lower_case_identifier) @name.definition.function)) @definition.function
(function_call_expr (value_expr (value_qid) @name.reference.function)) @reference.function
(exposed_value (lower_case_identifier) @name.reference.function)) @reference.function
(type_annotation ((lower_case_identifier) @name.reference.function) (colon)) @reference.function
(type_declaration ((upper_case_identifier) @name.definition.type) ) @definition.type
(type_ref (upper_case_qid (upper_case_identifier) @name.reference.type)) @reference.type
(exposed_type (upper_case_identifier) @name.reference.type)) @reference.type
(type_declaration (union_variant (upper_case_identifier) @name.definition.union)) @definition.union
(value_expr (upper_case_qid (upper_case_identifier) @name.reference.union)) @reference.union
(module_declaration
(upper_case_qid (upper_case_identifier)) @name.definition.module
) @definition.module

View file

@ -0,0 +1,30 @@
(
(comment)* @doc
.
(function_declaration
name: (identifier) @name.definition.function) @definition.function
(#strip! @doc "^//\\s*")
(#set-adjacent! @doc @definition.function)
)
(
(comment)* @doc
.
(method_declaration
name: (field_identifier) @name.definition.method) @definition.method
(#strip! @doc "^//\\s*")
(#set-adjacent! @doc @definition.method)
)
(call_expression
function: [
(identifier) @name.reference.call
(parenthesized_expression (identifier) @name.reference.call)
(selector_expression field: (field_identifier) @name.reference.call)
(parenthesized_expression (selector_expression field: (field_identifier) @name.reference.call))
]) @reference.call
(type_spec
name: (type_identifier) @name.definition.type) @definition.type
(type_identifier) @name.reference.type @reference.type

View file

@ -0,0 +1,20 @@
(class_declaration
name: (identifier) @name.definition.class) @definition.class
(method_declaration
name: (identifier) @name.definition.method) @definition.method
(method_invocation
name: (identifier) @name.reference.call
arguments: (argument_list) @reference.call)
(interface_declaration
name: (identifier) @name.definition.interface) @definition.interface
(type_list
(type_identifier) @name.reference.implementation) @reference.implementation
(object_creation_expression
type: (type_identifier) @name.reference.class) @reference.class
(superclass (type_identifier) @name.reference.class) @reference.class

View file

@ -0,0 +1,88 @@
(
(comment)* @doc
.
(method_definition
name: (property_identifier) @name.definition.method) @definition.method
(#not-eq? @name.definition.method "constructor")
(#strip! @doc "^[\\s\\*/]+|^[\\s\\*/]$")
(#select-adjacent! @doc @definition.method)
)
(
(comment)* @doc
.
[
(class
name: (_) @name.definition.class)
(class_declaration
name: (_) @name.definition.class)
] @definition.class
(#strip! @doc "^[\\s\\*/]+|^[\\s\\*/]$")
(#select-adjacent! @doc @definition.class)
)
(
(comment)* @doc
.
[
(function
name: (identifier) @name.definition.function)
(function_declaration
name: (identifier) @name.definition.function)
(generator_function
name: (identifier) @name.definition.function)
(generator_function_declaration
name: (identifier) @name.definition.function)
] @definition.function
(#strip! @doc "^[\\s\\*/]+|^[\\s\\*/]$")
(#select-adjacent! @doc @definition.function)
)
(
(comment)* @doc
.
(lexical_declaration
(variable_declarator
name: (identifier) @name.definition.function
value: [(arrow_function) (function)]) @definition.function)
(#strip! @doc "^[\\s\\*/]+|^[\\s\\*/]$")
(#select-adjacent! @doc @definition.function)
)
(
(comment)* @doc
.
(variable_declaration
(variable_declarator
name: (identifier) @name.definition.function
value: [(arrow_function) (function)]) @definition.function)
(#strip! @doc "^[\\s\\*/]+|^[\\s\\*/]$")
(#select-adjacent! @doc @definition.function)
)
(assignment_expression
left: [
(identifier) @name.definition.function
(member_expression
property: (property_identifier) @name.definition.function)
]
right: [(arrow_function) (function)]
) @definition.function
(pair
key: (property_identifier) @name.definition.function
value: [(arrow_function) (function)]) @definition.function
(
(call_expression
function: (identifier) @name.reference.call) @reference.call
(#not-match? @name.reference.call "^(require)$")
)
(call_expression
function: (member_expression
property: (property_identifier) @name.reference.call)
arguments: (_) @reference.call)
(new_expression
constructor: (_) @name.reference.class) @reference.class

View file

@ -0,0 +1,116 @@
; Modules
;--------
(
(comment)? @doc .
(module_definition (module_binding (module_name) @name.definition.module) @definition.module)
(#strip! @doc "^\\(\\*\\*?\\s*|\\s\\*\\)$")
)
(module_path (module_name) @name.reference.module) @reference.module
; Modules types
;--------------
(
(comment)? @doc .
(module_type_definition (module_type_name) @name.definition.interface) @definition.interface
(#strip! @doc "^\\(\\*\\*?\\s*|\\s\\*\\)$")
)
(module_type_path (module_type_name) @name.reference.implementation) @reference.implementation
; Functions
;----------
(
(comment)? @doc .
(value_definition
[
(let_binding
pattern: (value_name) @name.definition.function
(parameter))
(let_binding
pattern: (value_name) @name.definition.function
body: [(fun_expression) (function_expression)])
] @definition.function
)
(#strip! @doc "^\\(\\*\\*?\\s*|\\s\\*\\)$")
)
(
(comment)? @doc .
(external (value_name) @name.definition.function) @definition.function
(#strip! @doc "^\\(\\*\\*?\\s*|\\s\\*\\)$")
)
(application_expression
function: (value_path (value_name) @name.reference.call)) @reference.call
(infix_expression
left: (value_path (value_name) @name.reference.call)
(infix_operator) @reference.call
(#eq? @reference.call "@@"))
(infix_expression
(infix_operator) @reference.call
right: (value_path (value_name) @name.reference.call)
(#eq? @reference.call "|>"))
; Operator
;---------
(
(comment)? @doc .
(value_definition
(let_binding
pattern: (parenthesized_operator [
(prefix_operator)
(infix_operator)
(hash_operator)
(indexing_operator)
(let_operator)
(and_operator)
(match_operator)
] @name.definition.function)) @definition.function)
(#strip! @doc "^\\(\\*\\*?\\s*|\\s\\*\\)$")
)
[
(prefix_operator)
(sign_operator)
(infix_operator)
(hash_operator)
(indexing_operator)
(let_operator)
(and_operator)
(match_operator)
] @name.reference.call @reference.call
; Classes
;--------
(
(comment)? @doc .
[
(class_definition (class_binding (class_name) @name.definition.class) @definition.class)
(class_type_definition (class_type_binding (class_type_name) @name.definition.class) @definition.class)
]
(#strip! @doc "^\\(\\*\\*?\\s*|\\s\\*\\)$")
)
[
(class_path (class_name) @name.reference.class)
(class_type_path (class_type_name) @name.reference.class)
] @reference.class
; Methods
;--------
(
(comment)? @doc .
(method_definition (method_name) @name.definition.method) @definition.method
(#strip! @doc "^\\(\\*\\*?\\s*|\\s\\*\\)$")
)
(method_invocation (method_name) @name.reference.call) @reference.call

View file

@ -0,0 +1,26 @@
(class_declaration
name: (name) @name.definition.class) @definition.class
(function_definition
name: (name) @name.definition.function) @definition.function
(method_declaration
name: (name) @name.definition.function) @definition.function
(object_creation_expression
[
(qualified_name (name) @name.reference.class)
(variable_name (name) @name.reference.class)
]) @reference.class
(function_call_expression
function: [
(qualified_name (name) @name.reference.call)
(variable_name (name)) @name.reference.call
]) @reference.call
(scoped_call_expression
name: (name) @name.reference.call) @reference.call
(member_call_expression
name: (name) @name.reference.call) @reference.call

View file

@ -0,0 +1,12 @@
(class_definition
name: (identifier) @name.definition.class) @definition.class
(function_definition
name: (identifier) @name.definition.function) @definition.function
(call
function: [
(identifier) @name.reference.call
(attribute
attribute: (identifier) @name.reference.call)
]) @reference.call

View file

@ -0,0 +1,26 @@
(classlessPredicate
name: (predicateName) @name.definition.function) @definition.function
(memberPredicate
name: (predicateName) @name.definition.method) @definition.method
(aritylessPredicateExpr
name: (literalId) @name.reference.call) @reference.call
(module
name: (moduleName) @name.definition.module) @definition.module
(dataclass
name: (className) @name.definition.class) @definition.class
(datatype
name: (className) @name.definition.class) @definition.class
(datatypeBranch
name: (className) @name.definition.class) @definition.class
(qualifiedRhs
name: (predicateName) @name.reference.call) @reference.call
(typeExpr
name: (className) @name.reference.type) @reference.type

View file

@ -0,0 +1,64 @@
; Method definitions
(
(comment)* @doc
.
[
(method
name: (_) @name.definition.method) @definition.method
(singleton_method
name: (_) @name.definition.method) @definition.method
]
(#strip! @doc "^#\\s*")
(#select-adjacent! @doc @definition.method)
)
(alias
name: (_) @name.definition.method) @definition.method
(setter
(identifier) @ignore)
; Class definitions
(
(comment)* @doc
.
[
(class
name: [
(constant) @name.definition.class
(scope_resolution
name: (_) @name.definition.class)
]) @definition.class
(singleton_class
value: [
(constant) @name.definition.class
(scope_resolution
name: (_) @name.definition.class)
]) @definition.class
]
(#strip! @doc "^#\\s*")
(#select-adjacent! @doc @definition.class)
)
; Module definitions
(
(module
name: [
(constant) @name.definition.module
(scope_resolution
name: (_) @name.definition.module)
]) @definition.module
)
; Calls
(call method: (identifier) @name.reference.call) @reference.call
(
[(identifier) (constant)] @name.reference.call @reference.call
(#is-not? local)
(#not-match? @name.reference.call "^(lambda|load|require|require_relative|__FILE__|__LINE__)$")
)

View file

@ -0,0 +1,60 @@
; ADT definitions
(struct_item
name: (type_identifier) @name.definition.class) @definition.class
(enum_item
name: (type_identifier) @name.definition.class) @definition.class
(union_item
name: (type_identifier) @name.definition.class) @definition.class
; type aliases
(type_item
name: (type_identifier) @name.definition.class) @definition.class
; method definitions
(declaration_list
(function_item
name: (identifier) @name.definition.method)) @definition.method
; function definitions
(function_item
name: (identifier) @name.definition.function) @definition.function
; trait definitions
(trait_item
name: (type_identifier) @name.definition.interface) @definition.interface
; module definitions
(mod_item
name: (identifier) @name.definition.module) @definition.module
; macro definitions
(macro_definition
name: (identifier) @name.definition.macro) @definition.macro
; references
(call_expression
function: (identifier) @name.reference.call) @reference.call
(call_expression
function: (field_expression
field: (field_identifier) @name.reference.call)) @reference.call
(macro_invocation
macro: (identifier) @name.reference.call) @reference.call
; implementations
(impl_item
trait: (type_identifier) @name.reference.implementation) @reference.implementation
(impl_item
type: (type_identifier) @name.reference.implementation
!trait) @reference.implementation

View file

@ -0,0 +1,23 @@
(function_signature
name: (identifier) @name.definition.function) @definition.function
(method_signature
name: (property_identifier) @name.definition.method) @definition.method
(abstract_method_signature
name: (property_identifier) @name.definition.method) @definition.method
(abstract_class_declaration
name: (type_identifier) @name.definition.class) @definition.class
(module
name: (identifier) @name.definition.module) @definition.module
(interface_declaration
name: (type_identifier) @name.definition.interface) @definition.interface
(type_annotation
(type_identifier) @name.reference.type) @reference.type
(new_expression
constructor: (identifier) @name.reference.class) @reference.class

View file

@ -1,8 +1,12 @@
import * as fs from "fs";
import { ContinueRcJson, IDE, IdeInfo, Problem, Range } from "..";
import { ContinueRcJson, IDE, IdeInfo, IndexTag, Problem, Range, Thread } from "..";
import { getContinueGlobalPath } from "./paths";
class FileSystemIde implements IDE {
getTags(artifactId: string): Promise<IndexTag[]> {
return Promise.resolve([]);
}
getIdeInfo(): Promise<IdeInfo> {
return Promise.resolve({
ideType: "vscode",
@ -33,10 +37,22 @@ class FileSystemIde implements IDE {
getTerminalContents(): Promise<string> {
return Promise.resolve("");
}
async getDebugLocals(threadIndex: number): Promise<string> {
return Promise.resolve("");
}
async getTopLevelCallStackSources(
threadIndex: number,
stackDepth: number
): Promise<string[]> {
return Promise.resolve([]);
}
async getAvailableThreads(): Promise<Thread[]> {
return Promise.resolve([]);
}
showLines(
filepath: string,
startLine: number,
endLine: number,
endLine: number
): Promise<void> {
return Promise.resolve();
}
@ -101,7 +117,7 @@ class FileSystemIde implements IDE {
showDiff(
filepath: string,
newContents: string,
stepIndex: number,
stepIndex: number
): Promise<void> {
return Promise.resolve();
}

View file

@ -121,7 +121,7 @@ export function renderPromptTemplate(
}
export function getBasename(filepath: string, n: number = 1): string {
return filepath.split(/[\\/]/).pop() || "";
return filepath.split(/[\\/]/).pop() ?? "";
}
export function getLastNPathParts(filepath: string, n: number): string {

View file

@ -1,9 +1,27 @@
import { ContinueRcJson, IDE, IdeInfo, Problem, Range } from "..";
import { ContinueRcJson, IDE, IdeInfo, IndexTag, Problem, Range, Thread } from "..";
export class MessageIde implements IDE {
constructor(
private readonly request: (messageType: string, data: any) => Promise<any>,
private readonly request: (messageType: string, data: any) => Promise<any>
) {}
getDebugLocals(threadIndex: number): Promise<string> {
return this.request("getDebugLocals", { threadIndex });
}
getTopLevelCallStackSources(
threadIndex: number,
stackDepth: number
): Promise<string[]> {
return this.request("getTopLevelCallStackSources", {
threadIndex,
stackDepth,
});
}
getAvailableThreads(): Promise<Thread[]> {
return this.request("getAvailableThreads", undefined);
}
getTags(artifactId: string): Promise<IndexTag[]> {
return this.request("getTags", artifactId);
}
getIdeInfo(): Promise<IdeInfo> {
return this.request("getIdeInfo", undefined);
}
@ -45,7 +63,7 @@ export class MessageIde implements IDE {
async showLines(
filepath: string,
startLine: number,
endLine: number,
endLine: number
): Promise<void> {
return await this.request("showLines", { filepath, startLine, endLine });
}
@ -90,7 +108,7 @@ export class MessageIde implements IDE {
async showDiff(
filepath: string,
newContents: string,
stepIndex: number,
stepIndex: number
): Promise<void> {
await this.request("showDiff", { filepath, newContents, stepIndex });
}

View file

@ -16,6 +16,7 @@ export class Telemetry {
}
static async setup(allow: boolean, uniqueId: string) {
Telemetry.uniqueId = uniqueId;
if (!allow) {
Telemetry.client = undefined;
} else {

25
core/util/ranges.ts Normal file
View file

@ -0,0 +1,25 @@
import { Range } from "..";
export function getRangeInString(content: string, range: Range): string {
const lines = content.split("\n");
if (range.start.line === range.end.line) {
return (
lines[range.start.line]?.substring(
range.start.character,
range.end.character + 1,
) ?? ""
);
}
const firstLine =
lines[range.start.line]?.substring(
range.start.character,
lines[range.start.line].length,
) ?? "";
const middleLines = lines.slice(range.start.line + 1, range.end.line);
const lastLine =
lines[range.end.line]?.substring(0, range.end.character) ?? "";
return [firstLine, ...middleLines, lastLine].join("\n");
}

View file

@ -1,4 +1,5 @@
import * as path from "path";
import { Language } from "web-tree-sitter";
const Parser = require("web-tree-sitter");
export const supportedLanguages: { [key: string]: string } = {
@ -7,6 +8,14 @@ export const supportedLanguages: { [key: string]: string } = {
cc: "cpp",
cxx: "cpp",
hxx: "cpp",
cp: "cpp",
hh: "cpp",
inc: "cpp",
// Depended on this PR: https://github.com/tree-sitter/tree-sitter-cpp/pull/173
// ccm: "cpp",
// c++m: "cpp",
// cppm: "cpp",
// cxxm: "cpp",
cs: "c_sharp",
c: "c",
h: "c",
@ -68,18 +77,31 @@ export const supportedLanguages: { [key: string]: string } = {
};
export async function getParserForFile(filepath: string) {
if (process.env.IS_BINARY) {
return undefined;
}
try {
await Parser.init();
const parser = new Parser();
const language = await getLanguageForFile(filepath);
parser.setLanguage(language);
return parser;
} catch (e) {
console.error("Unable to load language for file", filepath, e);
return undefined;
}
}
export async function getLanguageForFile(
filepath: string,
): Promise<Language | undefined> {
try {
await Parser.init();
const extension = path.extname(filepath).slice(1);
if (!supportedLanguages[extension]) {
console.warn(
"Unable to load language for file",
extension,
"from path: ",
filepath,
);
return undefined;
}
@ -89,8 +111,7 @@ export async function getParserForFile(filepath: string) {
`tree-sitter-${supportedLanguages[extension]}.wasm`,
);
const language = await Parser.Language.load(wasmPath);
parser.setLanguage(language);
return parser;
return language;
} catch (e) {
console.error("Unable to load language for file", filepath, e);
return undefined;

View file

@ -21,7 +21,7 @@ function constructPrompt(
return renderPromptTemplate(template, [], {
userInput,
codeToEdit,
language: language || "",
language: language ?? "",
});
}

View file

@ -10,5 +10,9 @@
"license": "Apache-2.0",
"dependencies": {
"@xenova/transformers": "^2.14.0"
},
"engine-strict": true,
"engines": {
"node": ">=20.11.0"
}
}

View file

@ -1,11 +1,15 @@
import {
ContextItemWithId,
ContextSubmenuItem,
ContinueRcJson,
DiffLine,
IndexTag,
Problem,
Range,
Thread,
} from "..";
import { RangeInFileWithContents } from "../commands/util";
import { Protocol } from "../protocol";
export type IdeProtocol = {
@ -23,7 +27,7 @@ export type IdeProtocol = {
readFile: [{ filepath: string }, string];
showDiff: [
{ filepath: string; newContents: string; stepIndex: number },
void,
void
];
diffLine: [
{
@ -32,7 +36,7 @@ export type IdeProtocol = {
startLine: number;
endLine: number;
},
void,
void
];
getProblems: [{ filepath: string }, Problem[]];
getBranch: [{ dir: string }, string];
@ -43,8 +47,15 @@ export type IdeProtocol = {
getDiff: [undefined, string];
getWorkspaceConfigs: [undefined, ContinueRcJson[]];
getTerminalContents: [undefined, string];
getDebugLocals: [{ threadIndex: Number }, string];
getTopLevelCallStackSources: [
{ threadIndex: number; stackDepth: number },
string[]
];
getAvailableThreads: [undefined, Thread[]];
isTelemetryEnabled: [undefined, boolean];
getUniqueId: [undefined, string];
getTags: [string, IndexTag[]];
};
export type WebviewProtocol = Protocol &
@ -57,7 +68,7 @@ export type WebviewProtocol = Protocol &
workspacePaths: string[];
vscMachineId: string;
vscMediaUrl: string;
},
}
];
errorPopup: [{ message: string }, void];
@ -83,7 +94,11 @@ export type ReverseWebviewProtocol = {
historyIndex: number;
item: ContextItemWithId;
},
void,
void
];
updateSubmenuItems: [
{ provider: string; submenuItems: ContextSubmenuItem[] },
void
];
getDefaultModelTitle: [undefined, string];
newSessionWithPrompt: [{ prompt: string }, void];

5952
core/yarn.lock Normal file

File diff suppressed because it is too large Load diff

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