Merge branch 'dev' into Lesteer/discord-context

This commit is contained in:
Nate Sesti 2024-10-12 21:52:30 -07:00 • committed by GitHub
commit 966bf8e33d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
296 changed files with 6997 additions and 4715 deletions

View file

@ -0,0 +1,7 @@
## 0.0.72 - 2024-10-04
### Added
* Listen for changes to Intellij settings without requiring window reload
### Changed
* Updated tutorial file
### Fixed
* Fix ability to load config.ts in JetBrains IDEs

View file

@ -0,0 +1,4 @@
project: extensions/vscode
kind: Added
body: Improved loading/accept/reject UI for apply
time: 2024-09-27T14:29:40.283176-07:00

View file

@ -0,0 +1,4 @@
project: extensions/vscode
kind: Added
body: Polished chat sidebar, especially context dropdown
time: 2024-09-27T14:30:05.576347-07:00

View file

@ -0,0 +1,4 @@
project: extensions/vscode
kind: Added
body: Further prompt caching with Anthropic
time: 2024-09-29T09:56:27.946259-07:00

View file

@ -0,0 +1,4 @@
project: extensions/vscode
kind: Changed
body: Updated tutorial file
time: 2024-09-23T16:03:02.944462-07:00

View file

@ -0,0 +1,4 @@
project: extensions/vscode
kind: Changed
body: Improved styling on "More" page
time: 2024-09-29T09:54:07.999324-07:00

View file

@ -0,0 +1,4 @@
project: extensions/vscode
kind: Fixed
body: Fixed a number of apply bugs
time: 2024-09-27T14:29:24.69568-07:00

View file

@ -0,0 +1,4 @@
project: extensions/vscode
kind: Fixed
body: Fixed autoscrolling behavior
time: 2024-09-29T09:55:25.835696-07:00

View file

@ -0,0 +1,5 @@
project: extensions/intellij
kind: Fixed
body: Off-screen rendering to solve white flash on load and lack of changing cursor
type
time: 2024-10-07T18:38:20.733658-07:00

18
.github/workflows/auto-assign.yaml vendored Normal file
View file

@ -0,0 +1,18 @@
name: Issue assignment
on:
issues:
types: [opened]
jobs:
auto-assign:
runs-on: ubuntu-latest
permissions:
issues: write
steps:
- name: "Auto-assign issue"
uses: pozil/auto-assign-issue@v2
with:
repo-token: ${{ secrets.CI_GITHUB_TOKEN }}
assignees: sestinj,Patrick-Erichsen
numOfAssignee: 1

4
.gitignore vendored
View file

@ -169,4 +169,6 @@ Icon?
.prompts/
.aider*
notes.md
notes.md
manual-testing-sandbox/Continue/.idea/vcs.xml

1
.idea/gradle.xml generated
View file

@ -5,7 +5,6 @@
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>
<option name="externalProjectPath" value="$PROJECT_DIR$/extensions/intellij" />
<option name="gradleJvm" value="corretto-17" />
<option name="modules">
<set>
<option value="$PROJECT_DIR$/extensions/intellij" />

View file

@ -1,3 +1,4 @@
extensions/vscode/continue_rc_schema.json
**/.continueignore
CHANGELOG.md
CHANGELOG.md
**/continue_tutorial.py

19
.prompts/test.prompt Normal file
View file

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

2
.vscode/launch.json vendored
View file

@ -12,7 +12,7 @@
"cwd": "${workspaceFolder}/extensions/vscode",
"args": [
// Pass a directory to manually test in
"${workspaceFolder}/gui",
"${workspaceFolder}/manual-testing-sandbox",
"${workspaceFolder}/manual-testing-sandbox/test.js",
"--extensionDevelopmentPath=${workspaceFolder}/extensions/vscode"
],

View file

@ -17,9 +17,9 @@
"**/binary": true,
"binary/": false,
"**/core/vendor/**": true,
"**/gui/dist": true
"**/gui/dist": true,
"**/extensions/vscode/gui/**": true,
"**/extensions/vscode/out/**": true
},
"eslint.workingDirectories": [
"./core"
]
"eslint.workingDirectories": ["./core"]
}

View file

@ -68,12 +68,18 @@ You can run the documentation server locally using either of the following metho
#### Method 1: NPM Script
1. Open your terminal and navigate to the root directory of the project.
1. Open your terminal and navigate to the `docs` subdirectory of the project. The `docusaurus.config.js` file you'll see there is a sign you're in the right place.
2. Run the following command to start the documentation server:
2. Run the following command to install the necessary dependencies for the documentation server:
```bash
npm run start --prefix docs
npm install
```
3. Run the following command to start the documentation server:
```bash
npm run start
```
#### Method 2: VS Code Task

View file

@ -54,7 +54,7 @@
## Getting Started
Learn about how to install and use Continue in the docs [here](https://continue.dev/docs/getting-started)
Learn about how to install and use Continue in the docs [here](https://continue.dev/docs/getting-started/install)
## Contributing
@ -62,4 +62,4 @@ Check out the [contribution ideas board](https://github.com/orgs/continuedev/pro
## License
[Apache 2.0 © 2023 Continue Dev, Inc.](./LICENSE)
[Apache 2.0 © 2023-2024 Continue Dev, Inc.](./LICENSE)

View file

@ -74,6 +74,7 @@
"jsdom": "^24.0.0",
"launchdarkly-node-client-sdk": "^3.2.0",
"llm-code-highlighter": "^0.0.14",
"lru-cache": "^10.2.2",
"mac-ca": "^3.1.0",
"node-fetch": "^3.3.2",
"node-html-markdown": "^1.3.0",

View file

@ -2,6 +2,8 @@ import Parser from "web-tree-sitter";
import { RangeInFileWithContents } from "../commands/util.js";
import { getParserForFile } from "../util/treeSitter.js";
export type AstPath = Parser.SyntaxNode[];
export async function getAst(
filepath: string,
fileContents: string,
@ -23,7 +25,7 @@ export async function getAst(
export async function getTreePathAtCursor(
ast: Parser.Tree,
cursorIndex: number,
): Promise<Parser.SyntaxNode[] | undefined> {
): Promise<AstPath> {
const path = [ast.rootNode];
while (path[path.length - 1].childCount > 0) {
let foundChild = false;

View file

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

View file

@ -22,20 +22,18 @@ import {
} from "../util/parameters.js";
import { Telemetry } from "../util/posthog.js";
import { getRangeInString } from "../util/ranges.js";
import { ImportDefinitionsService } from "./ImportDefinitionsService.js";
import { BracketMatchingService } from "./brackets.js";
import AutocompleteLruCache from "./cache.js";
import {
noFirstCharNewline,
onlyWhitespaceAfterEndOfLine,
stopAtStopTokens,
} from "./charStream.js";
import {
constructAutocompletePrompt,
languageForFilepath,
} from "./constructPrompt.js";
import { isOnlyPunctuationAndWhitespace } from "./filter.js";
import { AutocompleteLanguageInfo } from "./languages.js";
import { postprocessCompletion } from "./postprocessing.js";
import { AutocompleteSnippet } from "./ranking.js";
import { RecentlyEditedRange } from "./recentlyEdited.js";
import { RootPathContextService } from "./services/RootPathContextService.js";
import {
avoidPathLineAndEmptyComments,
noTopLevelKeywordsMidline,
@ -44,15 +42,19 @@ import {
stopAtRepeatingLines,
stopAtSimilarLine,
streamWithNewLines,
} from "./lineStream.js";
import { postprocessCompletion } from "./postprocessing.js";
import { AutocompleteSnippet } from "./ranking.js";
import { RecentlyEditedRange } from "./recentlyEdited.js";
} from "./streamTransforms/lineStream.js";
import { getTemplateForModel } from "./templates.js";
import { GeneratorReuseManager } from "./util.js";
// @prettier-ignore
import Handlebars from "handlebars";
import { getConfigJsonPath } from "../util/paths.js";
import { BracketMatchingService } from "./services/BracketMatchingService.js";
import { ImportDefinitionsService } from "./services/ImportDefinitionsService.js";
import {
noFirstCharNewline,
onlyWhitespaceAfterEndOfLine,
stopAtStopTokens,
} from "./streamTransforms/charStream.js";
export interface AutocompleteInput {
completionId: string;
@ -158,9 +160,14 @@ export class CompletionProvider {
this.onError.bind(this),
);
this.importDefinitionsService = new ImportDefinitionsService(this.ide);
this.rootPathContextService = new RootPathContextService(
this.importDefinitionsService,
this.ide,
);
}
private importDefinitionsService: ImportDefinitionsService;
private rootPathContextService: RootPathContextService;
private generatorReuseManager: GeneratorReuseManager;
private autocompleteCache = AutocompleteLruCache.get();
public errorsShown: Set<string> = new Set();
@ -204,7 +211,7 @@ export class CompletionProvider {
const outcome = this._outcomes.get(completionId)!;
outcome.accepted = true;
logDevData("autocomplete", outcome);
Telemetry.capture(
void Telemetry.capture(
"autocomplete",
{
accepted: outcome.accepted,
@ -378,7 +385,7 @@ export class CompletionProvider {
outcome.accepted = false;
logDevData("autocomplete", outcome);
const { prompt, completion, ...restOfOutcome } = outcome;
Telemetry.capture(
void Telemetry.capture(
"autocomplete",
{
...restOfOutcome,
@ -542,6 +549,7 @@ export class CompletionProvider {
llm.model,
extrasSnippets,
this.importDefinitionsService,
this.rootPathContextService,
);
// If prefix is manually passed

View file

@ -1,4 +1,3 @@
import Parser from "web-tree-sitter";
import { RangeInFileWithContents } from "../commands/util.js";
import { TabAutocompleteOptions } from "../index.js";
@ -7,8 +6,7 @@ import {
pruneLinesFromBottom,
pruneLinesFromTop,
} from "../llm/countTokens.js";
import { ImportDefinitionsService } from "./ImportDefinitionsService.js";
import { getAst, getTreePathAtCursor } from "./ast.js";
import { AstPath, getAst, getTreePathAtCursor } from "./ast.js";
import {
AutocompleteLanguageInfo,
LANGUAGES,
@ -22,6 +20,8 @@ import {
type AutocompleteSnippet,
} from "./ranking.js";
import { RecentlyEditedRange, findMatchingRange } from "./recentlyEdited.js";
import { ImportDefinitionsService } from "./services/ImportDefinitionsService.js";
import { RootPathContextService } from "./services/RootPathContextService.js";
export function languageForFilepath(
filepath: string,
@ -32,7 +32,7 @@ export function languageForFilepath(
const BLOCK_TYPES = ["body", "statement_block"];
function shouldCompleteMultilineAst(
treePath: Parser.SyntaxNode[],
treePath: AstPath,
cursorLine: number,
): boolean {
// If at the base of the file, do multiline
@ -63,7 +63,7 @@ function isMidlineCompletion(prefix: string, suffix: string): boolean {
}
async function shouldCompleteMultiline(
filepath: string,
treePath: AstPath | undefined,
fullPrefix: string,
fullSuffix: string,
language: AutocompleteLanguageInfo,
@ -94,18 +94,6 @@ async function shouldCompleteMultiline(
}
// Use AST to determine whether to complete multiline
let treePath: Parser.SyntaxNode[] | undefined;
try {
const ast = await getAst(filepath, fullPrefix + fullSuffix);
if (!ast) {
return true;
}
treePath = await getTreePathAtCursor(ast, fullPrefix.length);
} catch (e) {
console.error("Failed to parse AST", e);
}
let completeMultiline = false;
if (treePath) {
const cursorLine = fullPrefix.split("\n").length - 1;
@ -127,6 +115,7 @@ export async function constructAutocompletePrompt(
modelName: string,
extraSnippets: AutocompleteSnippet[],
importDefinitionsService: ImportDefinitionsService,
rootPathContextService: RootPathContextService,
): Promise<{
prefix: string;
suffix: string;
@ -145,6 +134,17 @@ export async function constructAutocompletePrompt(
);
const suffix = pruneLinesFromBottom(fullSuffix, maxSuffixTokens, modelName);
// Calculate AST Path
let treePath: AstPath | undefined;
try {
const ast = await getAst(filepath, fullPrefix + fullSuffix);
if (ast) {
treePath = await getTreePathAtCursor(ast, fullPrefix.length);
}
} catch (e) {
console.error("Failed to parse AST", e);
}
// Find external snippets
let snippets: AutocompleteSnippet[] = [];
@ -215,6 +215,14 @@ export async function constructAutocompletePrompt(
snippets.push(...importSnippets);
}
if (options.useRootPathContext && treePath) {
const ctx = await rootPathContextService.getContextForPath(
filepath,
treePath,
);
snippets.push(...ctx);
}
// Filter out empty snippets and ones that are already in the prefix/suffix
snippets = snippets
.map((snippet) => ({ ...snippet }))
@ -269,7 +277,7 @@ export async function constructAutocompletePrompt(
suffix,
useFim: true,
completeMultiline: await shouldCompleteMultiline(
filepath,
treePath,
fullPrefix,
fullSuffix,
language,

View file

@ -1,4 +1,4 @@
import type { LineFilter } from "./lineStream.js";
import { LineFilter } from "./streamTransforms/lineStream";
export interface AutocompleteLanguageInfo {
name: string;
@ -26,7 +26,7 @@ export const Python = {
name: "Python",
// """"#" is for .ipynb files, where we add '"""' surrounding markdown blocks.
// This stops the model from trying to complete the start of a new markdown block
topLevelKeywords: ["def", "class", "\"\"\"#"],
topLevelKeywords: ["def", "class", '"""#'],
singleLineComment: "#",
endOfLine: [],
};

View file

@ -1,5 +1,5 @@
import { jest } from "@jest/globals";
import * as lineStream from "./lineStream";
import * as lineStream from "./streamTransforms/lineStream";
describe("lineStream", () => {
let mockFullStop: jest.Mock;

View file

@ -1,6 +1,6 @@
import type { ILLM } from "../index.js";
import { longestCommonSubsequence } from "../util/lcs.js";
import { lineIsRepeated } from "./lineStream.js";
import { lineIsRepeated } from "./streamTransforms/lineStream.js";
function rewritesLineAbove(completion: string, prefix: string): boolean {
const lineAbove = prefix

View file

@ -80,7 +80,7 @@ export function deduplicateSnippets(
function mergeSnippetsByRange(
snippets: Required<AutocompleteSnippet>[],
): Required<AutocompleteSnippet>[] {
if (snippets.length === 0) {
if (snippets.length <= 1) {
return snippets;
}

View file

@ -1,11 +1,11 @@
import { IDE } from "../index.js";
import { RangeInFileWithContents } from "../commands/util.js";
import { PrecalculatedLruCache } from "../util/LruCache.js";
import { IDE } from "../..";
import { RangeInFileWithContents } from "../../commands/util";
import { PrecalculatedLruCache } from "../../util/LruCache";
import {
TSQueryType,
getParserForFile,
getQueryForFile,
} from "../util/treeSitter.js";
} from "../../util/treeSitter";
interface FileInfo {
imports: { [key: string]: RangeInFileWithContents[] };

View file

@ -0,0 +1,45 @@
import { IDE, Location } from "../..";
import { LANGUAGES } from "../languages";
import { getSymbolsForSnippet } from "../ranking";
interface FileInfo {
filepath: string;
}
export class NearbyDefinitionsService {
static N = 10;
constructor(private readonly ide: IDE) {}
async getDefinitionsForLine(filepath: string, line: number) {
const lineContent = await this.ide.readRangeInFile(filepath, {
start: {
line,
character: 0,
},
end: {
line: line + 1,
character: 0,
},
});
// Remove keywords
const lang = LANGUAGES[filepath.split(".").slice(-1)[0]];
const symbols = Array.from(getSymbolsForSnippet(lineContent))
.filter((s) => s.length > 0)
.filter((s) => !(lang && lang?.stopWords?.includes(s)));
return Promise.all(
symbols.map((s) => {
const character = lineContent.indexOf(s);
const pos: Location = {
filepath,
position: {
line,
character,
},
};
}),
);
}
}

View file

@ -0,0 +1,129 @@
import { createHash } from "crypto";
import { LRUCache } from "lru-cache";
import Parser from "web-tree-sitter";
import { IDE } from "../..";
import { getQueryForFile, TSQueryType } from "../../util/treeSitter";
import { AstPath } from "../ast";
import { AutocompleteSnippet } from "../ranking";
import { ImportDefinitionsService } from "./ImportDefinitionsService";
export class RootPathContextService {
private cache = new LRUCache<string, AutocompleteSnippet[]>({
max: 100,
});
constructor(
private readonly importDefinitionsService: ImportDefinitionsService,
private readonly ide: IDE,
) {}
private static getNodeId(node: Parser.SyntaxNode): string {
return `${node.startIndex}`;
}
private static TYPES_TO_USE = new Set([
"program",
"function_declaration",
"method_definition",
]);
/**
* Key comes from hash of parent key and node type and node id.
*/
private static keyFromNode(
parentKey: string,
astNode: Parser.SyntaxNode,
): string {
return createHash("sha256")
.update(parentKey)
.update(astNode.type)
.update(RootPathContextService.getNodeId(astNode))
.digest("hex");
}
private async getSnippetsForNode(
filepath: string,
node: Parser.SyntaxNode,
): Promise<AutocompleteSnippet[]> {
const snippets: AutocompleteSnippet[] = [];
let query: Parser.Query | undefined;
switch (node.type) {
case "program":
this.importDefinitionsService.get(filepath);
break;
case "function_declaration":
query = await getQueryForFile(
filepath,
TSQueryType.FunctionDeclaration,
);
break;
case "method_definition":
query = await getQueryForFile(filepath, TSQueryType.MethodDefinition);
break;
case "function_definition":
query = await getQueryForFile(filepath, TSQueryType.FunctionDefinition);
break;
case "method_declaration":
query = await getQueryForFile(filepath, TSQueryType.MethodDeclaration);
break;
default:
break;
}
if (!query) {
return snippets;
}
await Promise.all(
query.matches(node).map(async (match) => {
const startPosition = match.captures[0].node.startPosition;
const endPosition = match.captures[0].node.endPosition;
const definitions = await this.ide.gotoDefinition({
filepath,
position: {
line: endPosition.row,
character: endPosition.column,
},
});
const newSnippets = await Promise.all(
definitions.map(async (def) => ({
...def,
contents: await this.ide.readRangeInFile(def.filepath, def.range),
})),
);
snippets.push(...newSnippets);
}),
);
return snippets;
}
async getContextForPath(
filepath: string,
astPath: AstPath,
// cursorIndex: number,
): Promise<AutocompleteSnippet[]> {
const snippets: AutocompleteSnippet[] = [];
let parentKey = filepath;
for (const astNode of astPath.filter((node) =>
RootPathContextService.TYPES_TO_USE.has(node.type),
)) {
const key = RootPathContextService.keyFromNode(parentKey, astNode);
const foundInCache = this.cache.get(key);
const newSnippets =
foundInCache ?? (await this.getSnippetsForNode(filepath, astNode));
snippets.push(...newSnippets);
if (!foundInCache) {
this.cache.set(key, newSnippets);
}
parentKey = key;
}
return snippets;
}
}

View file

@ -1,6 +1,6 @@
import { distance } from "fastest-levenshtein";
import { DiffLine } from "../";
import { LineStream } from "../diff/util";
import { DiffLine } from "../..";
import { LineStream } from "../../diff/util";
export type LineFilter = (args: {
lines: LineStream;

View file

@ -47,6 +47,7 @@ const qwenCoderFimTemplate: AutocompleteTemplate = {
"<|fim_prefix|>{{{prefix}}}<|fim_suffix|>{{{suffix}}}<|fim_middle|>",
completionOptions: {
stop: [
"<|endoftext|>",
"<|fim_prefix|>",
"<|fim_middle|>",
"<|fim_suffix|>",

View file

@ -1,3 +1,4 @@
import { ContextItemWithId, ILLM, SlashCommand } from "../../";
import {
filterCodeBlockLines,
filterEnglishLinesAtEnd,
@ -5,16 +6,15 @@ import {
fixCodeLlamaFirstLineIndentation,
stopAtLines,
streamWithNewLines,
} from "../../autocomplete/lineStream";
} from "../../autocomplete/streamTransforms/lineStream";
import { streamLines } from "../../diff/util";
import { ContextItemWithId, ILLM, SlashCommand } from "../../";
import { stripImages } from "../../llm/images";
import {
dedentAndGetCommonWhitespace,
getMarkdownLanguageTagForFile,
} from "../../util/";
import {
contextItemToRangeInFileWithContents,
ctxItemToRifWithContents,
type RangeInFileWithContents,
} from "../util";
@ -250,7 +250,7 @@ const EditSlashCommand: SlashCommand = {
}
const rif: RangeInFileWithContents =
contextItemToRangeInFileWithContents(contextItemToEdit);
ctxItemToRifWithContents(contextItemToEdit);
await ide.saveFile(rif.filepath);
const fullFileContents = await ide.readFile(rif.filepath);

View file

@ -1,4 +1,4 @@
import { ContextItemWithId } from "../index.js";
import { ContextItemWithId } from "../";
export interface RangeInFileWithContents {
filepath: string;
@ -9,20 +9,29 @@ export interface RangeInFileWithContents {
contents: string;
}
export function contextItemToRangeInFileWithContents(
export function ctxItemToRifWithContents(
item: ContextItemWithId,
): RangeInFileWithContents {
const lines = item.name.split("(")[1].split(")")[0].split("-");
let startLine = 0;
let endLine = 0;
const nameSplit = item.name.split("(");
if (nameSplit.length > 1) {
const lines = nameSplit[1].split(")")[0].split("-");
startLine = Number.parseInt(lines[0], 10);
endLine = Number.parseInt(lines[1], 10);
}
const rif: RangeInFileWithContents = {
filepath: item.id.itemId,
filepath: item.uri?.value || "",
range: {
start: {
line: Number.parseInt(lines[0]),
line: startLine,
character: 0,
},
end: {
line: Number.parseInt(lines[1]),
line: endLine,
character: 0,
},
},

View file

@ -21,9 +21,11 @@ export const DEFAULT_AUTOCOMPLETE_MODEL_CONFIG: ModelDescription = {
export const FREE_TRIAL_MODELS: ModelDescription[] = [
{
title: "Claude 3 Sonnet (Free Trial)",
title: "Claude 3.5 Sonnet (Free Trial)",
provider: "free-trial",
model: "claude-3-sonnet-20240229",
model: "claude-3-5-sonnet-20240620",
systemMessage:
"You are an expert software developer. You give helpful and concise responses.",
},
{
title: "GPT-4o (Free Trial)",
@ -33,16 +35,18 @@ export const FREE_TRIAL_MODELS: ModelDescription[] = [
"You are an expert software developer. You give helpful and concise responses.",
},
{
title: "Llama3 70b (Free Trial)",
title: "Llama3.1 70b (Free Trial)",
provider: "free-trial",
model: "llama3-70b",
model: "llama3.1-70b",
systemMessage:
"You are an expert software developer. You give helpful and concise responses. Whenever you write a code block you include the language after the opening ticks.",
"You are an expert software developer. You give helpful and concise responses.",
},
{
title: "Codestral (Free Trial)",
provider: "free-trial",
model: "codestral",
model: "codestral-latest",
systemMessage:
"You are an expert software developer. You give helpful and concise responses.",
},
];

View file

@ -595,7 +595,24 @@ async function loadFullConfigNode(
try {
// Try config.ts first
const configJsPath = getConfigJsPath();
const module = await import(configJsPath);
let module: any;
try {
module = await import(configJsPath);
} catch (e) {
console.log(e);
console.log(
"Could not load config.ts as absolute path, retrying as file url ...",
);
try {
module = await import(`file://${configJsPath}`);
} catch (e) {
throw new Error("Could not load config.ts as file url either", {
cause: e,
});
}
}
if (typeof require !== "undefined") {
delete require.cache[require.resolve(configJsPath)];
}

View file

@ -47,6 +47,7 @@ declare global {
llmRequestHook?: (model: string, prompt: string) => any;
apiKey?: string;
apiBase?: string;
cacheBehavior?: CacheBehavior;
engine?: string;
apiVersion?: string;
@ -313,6 +314,7 @@ declare global {
apiKey?: string;
aiGatewaySlug?: string;
apiBase?: string;
cacheBehavior?: CacheBehavior;
useLegacyCompletionsEndpoint?: boolean;
@ -341,8 +343,6 @@ declare global {
watsonxProjectId?: string;
watsonxStopToken?: string;
watsonxApiVersion?: string;
cacheSystemMessage?: boolean;
}
type RequireAtLeastOne<T, Keys extends keyof T = keyof T> = Pick<
T,
@ -547,7 +547,8 @@ declare global {
| "docs"
| "gitlab-mr"
| "os"
| "currentFile";
| "currentFile"
| "greptile";
type TemplateType =
| "llama2"
@ -687,6 +688,11 @@ declare global {
clientCertificate?: ClientCertificateOptions;
}
export interface CacheBehavior {
cacheSystemMessage?: boolean;
cacheConversation?: boolean;
}
export interface ClientCertificateOptions {
cert: string;
key: string;
@ -749,6 +755,7 @@ declare global {
requestOptions?: RequestOptions;
promptTemplates?: { [key: string]: string };
capabilities?: ModelCapability;
cacheBehavior?: CacheBehavior;
}
export type EmbeddingsProviderName =

View file

@ -29,7 +29,7 @@ export function addContextProvider(provider: ContextProviderWithParams) {
});
}
export function addModel(model: ModelDescription) {
export function addModel(model: ModelDescription, role?: keyof ModelRoles) {
editConfigJson((config) => {
if (config.models?.some((m: any) => stringify(m) === stringify(model))) {
return config;
@ -39,6 +39,18 @@ export function addModel(model: ModelDescription) {
}
config.models.push(model);
// Set the role for the model
if (role) {
if (!config.experimental) {
config.experimental = {};
}
if (!config.experimental.modelRoles) {
config.experimental.modelRoles = {};
}
config.experimental.modelRoles[role] = model.title;
}
return config;
});
}

View file

@ -2,9 +2,9 @@ import {
ContextItem,
ContextProviderDescription,
ContextProviderExtras,
} from "../../index.js";
import { getBasename } from "../../util/index.js";
import { BaseContextProvider } from "../index.js";
} from "../../";
import { getBasename } from "../../util/";
import { BaseContextProvider } from "../";
class CurrentFileContextProvider extends BaseContextProvider {
static description: ContextProviderDescription = {
@ -32,6 +32,10 @@ class CurrentFileContextProvider extends BaseContextProvider {
currentFile,
)}\n${contents}\n\`\`\``,
name: getBasename(currentFile),
uri: {
type: "file",
value: currentFile,
},
},
];
}

View file

@ -91,7 +91,7 @@ class DocsContextProvider extends BaseContextProvider {
await docsService.isJetBrainsAndPreIndexedDocsProvider();
if (isJetBrainsAndPreIndexedDocsProvider) {
extras.ide.showToast(
await extras.ide.showToast(
"error",
`${DocsService.preIndexedDocsEmbeddingsProvider.id} is configured as ` +
"the embeddings provider, but it cannot be used with JetBrains. " +
@ -105,7 +105,7 @@ class DocsContextProvider extends BaseContextProvider {
const preIndexedDoc = preIndexedDocs[query];
if (!!preIndexedDoc) {
Telemetry.capture("docs_pre_indexed_doc_used", {
void Telemetry.capture("docs_pre_indexed_doc_used", {
doc: preIndexedDoc["title"],
});
}
@ -147,6 +147,10 @@ class DocsContextProvider extends BaseContextProvider {
: chunk.otherMetadata?.title || chunk.filepath,
description: chunk.filepath,
content: chunk.content,
uri: {
type: "url" as const,
value: chunk.filepath,
},
}))
.reverse(),
{

View file

@ -4,14 +4,14 @@ import {
ContextProviderExtras,
ContextSubmenuItem,
LoadSubmenuItemsArgs,
} from "../../index.js";
import { walkDir } from "../../indexing/walkDir.js";
} from "../../";
import { walkDir } from "../../indexing/walkDir";
import {
getBasename,
getUniqueFilePath,
groupByLastNPathParts,
} from "../../util/index.js";
import { BaseContextProvider } from "../index.js";
} from "../../util/";
import { BaseContextProvider } from "../";
const MAX_SUBMENU_ITEMS = 10_000;
@ -36,6 +36,10 @@ class FileContextProvider extends BaseContextProvider {
name: query.split(/[\\/]/).pop() ?? query,
description: query,
content: `\`\`\`${query}\n${content}\n\`\`\``,
uri: {
type: "file",
value: query,
},
},
];
}

View file

@ -64,9 +64,7 @@ const getSubprocess = async (extras: ContextProviderExtras) => {
const workingDir = await extras.ide.getWorkspaceDirs().then(trimFirstElement);
return (command: string) =>
extras.ide
.subprocess(`cd ${workingDir}; ${command}`)
.then(trimFirstElement);
extras.ide.subprocess(command, workingDir).then(trimFirstElement);
};
class GitLabMergeRequestContextProvider extends BaseContextProvider {
@ -269,7 +267,7 @@ class GitLabMergeRequestContextProvider extends BaseContextProvider {
if (ex instanceof AxiosError) {
if (ex.response) {
const errorMessage = ex.response?.data
? ex.response.data.message ?? JSON.stringify(ex.response?.data)
? (ex.response.data.message ?? JSON.stringify(ex.response?.data))
: `${ex.response.status}: ${ex.response.statusText}`;
content += `GitLab Error: ${errorMessage}`;
} else {

View file

@ -0,0 +1,186 @@
import {
ContextItem,
ContextProviderDescription,
ContextProviderExtras,
} from "../../index.js";
import { BaseContextProvider } from "../index.js";
import { execSync } from "child_process";
import * as path from "path";
import * as fs from "fs";
class GreptileContextProvider extends BaseContextProvider {
static description: ContextProviderDescription = {
title: "greptile",
displayTitle: "Greptile",
description: "Insert query to Greptile",
type: "query",
};
async getContextItems(
query: string,
extras: ContextProviderExtras,
): Promise<ContextItem[]> {
const greptileToken = this.getGreptileToken();
if (!greptileToken) {
throw new Error("Greptile token not found.");
}
const githubToken = this.getGithubToken();
if (!githubToken) {
throw new Error("GitHub token not found.");
}
let absPath = await this.getWorkspaceDir(extras);
if (!absPath) {
throw new Error("Failed to determine the workspace directory.");
}
var remoteUrl = getRemoteUrl(absPath)
remoteUrl = getRemoteUrl(absPath);
const repoName = extractRepoName(remoteUrl);
const branch = getCurrentBranch(absPath);
const remoteType = getRemoteType(remoteUrl);
if (!remoteType) {
throw new Error("Unable to determine remote type.");
}
const options = {
method: 'POST',
headers: {
Authorization: `Bearer ${greptileToken}`,
'X-GitHub-Token': githubToken,
'Content-Type': 'application/json',
},
body: JSON.stringify({
messages: [{ id: "<string>", content: query, role: "user" }],
repositories: [{
remote: remoteType,
branch: branch,
repository: repoName
}],
sessionId: extras.config.userToken || "default-session",
stream: false,
genius: true,
}),
};
try {
const response = await extras.fetch('https://api.greptile.com/v2/query', options);
const rawText = await response.text();
// Check for HTTP errors
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
// Parse the response as JSON
const json = JSON.parse(rawText);
return json.sources.map((source: any) => ({
description: source.filepath,
content: `File: ${source.filepath}\nLines: ${source.linestart}-${source.lineend}\n\n${source.summary}`,
name: (source.filepath.split("/").pop() ?? "").split("\\").pop() ?? "",
}));
} catch (error) {
console.error("Error getting context items from Greptile:", error);
throw new Error(`Error getting context items from Greptile`);
}
}
private getGreptileToken(): string | undefined {
return this.options.GreptileToken || process.env.GREPTILE_AUTH_TOKEN;
}
private getGithubToken(): string | undefined {
return this.options.GithubToken || process.env.GITHUB_TOKEN;
}
private async getWorkspaceDir(extras: ContextProviderExtras): Promise<string | null> {
try {
const workspaceDirs = await extras.ide.getWorkspaceDirs();
if (workspaceDirs && workspaceDirs.length > 0) {
return workspaceDirs[0];
} else {
console.warn(`extras.ide.getWorkspaceDirs() returned undefined or empty array.`);
}
} catch (err) {
console.warn(`Failed to get workspace directories from extras.ide.getWorkspaceDirs():`);
}
// Fallback to using Git commands
try {
const currentDir = process.cwd();
if (this.isGitRepository(currentDir)) {
const workspaceDir = execSync('git rev-parse --show-toplevel').toString().trim();
return workspaceDir;
} else {
console.warn(`Current directory is not a Git repository: ${currentDir}`);
return null;
}
} catch (err) {
console.warn(`Failed to get workspace directory using Git commands: `);
return null;
}
}
private isGitRepository(dir: string): boolean {
try {
const gitDir = path.join(dir, '.git');
return fs.existsSync(gitDir);
} catch (err) {
console.warn(`Failed to check if directory is a Git repository:`);
return false;
}
}
}
// Helper functions
function getRemoteUrl(absPath: string): string {
try {
const remote = execSync(`git -C ${absPath} remote get-url origin`).toString().trim();
return remote;
} catch (err) {
console.warn(`Failed to get remote URL`);
return "";
}
}
function getCurrentBranch(absPath: string): string {
try {
const branch = execSync(`git -C ${absPath} rev-parse --abbrev-ref HEAD`).toString().trim();
return branch;
} catch (err) {
console.warn(`Failed to get current branch`);
return "master"; // Default to 'master' if the current branch cannot be determined
}
}
function extractRepoName(remote: string): string {
if (remote.startsWith("http://") || remote.startsWith("https://")) {
const parts = remote.split("/");
if (parts.length >= 2) {
return parts[parts.length - 2] + "/" + parts[parts.length - 1].replace(".git", "");
}
} else if (remote.startsWith("git@")) {
const parts = remote.split(":");
if (parts.length >= 2) {
return parts[1].replace(".git", "");
}
}
return "";
}
function getRemoteType(remote: string): string {
if (remote.includes("github.com")) {
return "github";
} else if (remote.includes("gitlab.com")) {
return "gitlab";
} else if (remote.includes("azure.com")) {
return "azure";
}
return "";
}
export default GreptileContextProvider;

View file

@ -11,6 +11,7 @@ class HttpContextProvider extends BaseContextProvider {
displayTitle: "HTTP",
description: "Retrieve a context item from a custom server",
type: "normal",
renderInlineAs: "",
};
override get description(): ContextProviderDescription {
@ -36,17 +37,29 @@ class HttpContextProvider extends BaseContextProvider {
body: JSON.stringify({
query: query || "",
fullInput: extras.fullInput,
options: this.options.options,
}),
});
const json: any = await response.json();
return [
{
description: json.description || "HTTP Context Item",
content: json.content || "",
name: json.name || this.options.title || "HTTP",
},
];
const json = await response.json();
try {
const createContextItem = (item: any) => ({
description: item.description ?? "HTTP Context Item",
content: item.content ?? "",
name: item.name ?? this.options.title ?? "HTTP",
});
return Array.isArray(json)
? json.map(createContextItem)
: [createContextItem(json)];
} catch (e) {
console.warn(
`Failed to parse response from custom HTTP context provider.\nError:\n${e}\nResponse from server:\n`,
json,
);
return [];
}
}
}

View file

@ -28,10 +28,15 @@ class OpenFilesContextProvider extends BaseContextProvider {
openFiles.map(async (filepath: string) => {
return {
description: filepath,
content: `\`\`\`${await getRelativePath(filepath, workspaceDirs)}\n${await ide.readFile(
content: `\`\`\`${await getRelativePath(
filepath,
)}\n\`\`\``,
workspaceDirs,
)}\n${await ide.readFile(filepath)}\n\`\`\``,
name: (filepath.split("/").pop() ?? "").split("\\").pop() ?? "",
uri: {
type: "file",
value: filepath,
},
};
}),
);

View file

@ -9,7 +9,7 @@ class TerminalContextProvider extends BaseContextProvider {
static description: ContextProviderDescription = {
title: "terminal",
displayTitle: "Terminal",
description: "Reference the contents of the terminal",
description: "Reference the last terminal command",
type: "normal",
};

View file

@ -1,12 +1,13 @@
import { Readability } from "@mozilla/readability";
import { JSDOM } from "jsdom";
import { NodeHtmlMarkdown } from "node-html-markdown";
import { BaseContextProvider } from "../index.js";
import { BaseContextProvider } from "../";
import {
ContextItem,
ContextProviderDescription,
ContextProviderExtras,
} from "../../index.js";
import { fetchFavicon } from "../../util/fetchFavicon";
class URLContextProvider extends BaseContextProvider {
static description: ContextProviderDescription = {
@ -22,6 +23,7 @@ class URLContextProvider extends BaseContextProvider {
): Promise<ContextItem[]> {
try {
const url = new URL(query);
const icon = await fetchFavicon(url);
const resp = await extras.fetch(url);
const html = await resp.text();
@ -37,11 +39,17 @@ class URLContextProvider extends BaseContextProvider {
);
const title = article?.title || url.pathname;
return [
{
description: title,
icon,
description: url.toString(),
content: markdown,
name: title,
uri: {
type: "url",
value: url.toString(),
},
},
];
} catch (e) {

View file

@ -23,6 +23,7 @@ import TerminalContextProvider from "./TerminalContextProvider";
import URLContextProvider from "./URLContextProvider";
import RepoMapContextProvider from "./RepoMapContextProvider";
import DiscordContextProvider from "./DiscordContextProvider";
import GreptileContextProvider from "./GreptileContextProvider";
/**
* Note: We are currently omitting the following providers due to bugs:
@ -55,6 +56,7 @@ export const Providers: (typeof BaseContextProvider)[] = [
ContinueProxyContextProvider,
RepoMapContextProvider,
DiscordContextProvider,
GreptileContextProvider,
];
export function contextProviderClassFromName(

View file

@ -24,7 +24,7 @@ export class VoyageReranker implements Reranker {
body: JSON.stringify({
query,
documents: chunks.map((chunk) => chunk.content),
model: this.params.model ?? "rerank-lite-1",
model: this.params.model ?? "rerank-2",
}),
});
const data: any = await resp.json();

View file

@ -1,12 +1,14 @@
import path from "path";
import { BranchAndDir, ContextItem, ContextProviderExtras } from "../../";
import TransformersJsEmbeddingsProvider from "../../indexing/embeddings/TransformersJsEmbeddingsProvider";
import { resolveRelativePathInWorkspace } from "../../util/ideUtils";
import { getRelativePath } from "../../util/";
import { INSTRUCTIONS_BASE_ITEM } from "../providers/utils";
import { RetrievalPipelineOptions } from "./pipelines/BaseRetrievalPipeline";
import NoRerankerRetrievalPipeline from "./pipelines/NoRerankerRetrievalPipeline";
import RerankerRetrievalPipeline from "./pipelines/RerankerRetrievalPipeline";
const DEFAULT_N_FINAL = 25;
export async function retrieveContextItemsFromEmbeddings(
extras: ContextProviderExtras,
options: any | undefined,
@ -42,7 +44,8 @@ export async function retrieveContextItemsFromEmbeddings(
const contextLength = extras.llm.contextLength;
const tokensPerSnippet = 512;
const nFinal =
options?.nFinal ?? Math.min(50, contextLength / tokensPerSnippet / 2);
options?.nFinal ??
Math.min(DEFAULT_N_FINAL, contextLength / tokensPerSnippet / 2);
const useReranking = !!extras.reranker;
const nRetrieve = useReranking ? options?.nRetrieve || 2 * nFinal : nFinal;
@ -94,21 +97,32 @@ export async function retrieveContextItemsFromEmbeddings(
}
return [
...results.map((r) => {
const name = `${getRelativePath(r.filepath, workspaceDirs)} (${
r.startLine
}-${r.endLine})`;
const description = `${r.filepath} (${r.startLine}-${r.endLine})`;
return {
name,
description,
content: `\`\`\`${name}\n${r.content}\n\`\`\``,
};
}),
{
...INSTRUCTIONS_BASE_ITEM,
content:
"Use the above code to answer the following question. You should not reference any files outside of what is shown, unless they are commonly known files, like a .gitignore or package.json. Reference the filenames whenever possible. If there isn't enough information to answer the question, suggest where the user might look to learn more.",
},
...results
.sort((a, b) => a.filepath.localeCompare(b.filepath))
.map((r) => {
const name = `${path.basename(r.filepath)} (${r.startLine}-${
r.endLine
})`;
const description = `${r.filepath}`;
if (r.filepath.includes("package.json")) {
console.log();
}
return {
name,
description,
content: `\`\`\`${name}\n${r.content}\n\`\`\``,
uri: {
type: "file" as const,
value: r.filepath,
},
};
}),
];
}

View file

@ -21,7 +21,8 @@ export interface ControlPlaneModelDescription extends ModelDescription {}
export const DEFAULT_CONTROL_PLANE_PROXY_URL =
process.env.CONTROL_PLANE_ENV === "local"
? "http://localhost:3001/"
: "https://control-plane-proxy.continue.dev/";
: "https://control-plane-api-service-i3dqylpbqa-uc.a.run.app/";
// : "https://control-plane-proxy.continue.dev/";
export const CONTROL_PLANE_URL =
process.env.CONTROL_PLANE_ENV === "local"

View file

@ -140,7 +140,7 @@ export class Core {
// Respect pauseCodebaseIndexOnStart user settings
if (ideSettings.pauseCodebaseIndexOnStart) {
await this.messenger.request("indexProgress", {
progress: 100,
progress: 1,
desc: "Initial Indexing Skipped",
status: "paused",
});
@ -226,7 +226,7 @@ export class Core {
// Edit config
on("config/addModel", (msg) => {
const model = msg.data.model;
addModel(model);
addModel(model, msg.data.role);
void this.configHandler.reloadConfig();
});
@ -571,7 +571,9 @@ export class Core {
);
return outcome ? [outcome.completion] : [];
});
on("autocomplete/accept", async (msg) => {});
on("autocomplete/accept", async (msg) => {
this.completionProvider.accept(msg.data.completionId);
});
on("autocomplete/cancel", async (msg) => {
this.completionProvider.cancel();
});

View file

@ -8,6 +8,7 @@ import { LineStream, matchLine } from "./util.js";
* - old + same = oldLinesCopy.length
* ^ (above two guarantee that all lines get represented)
* - Lines are always output in order, at least among old and new separately
* - Old lines in a hunk are always output before the new lines
*/
export async function* streamDiff(
oldLines: string[],

View file

@ -154,4 +154,8 @@ describe("deterministicApplyLazyEdit(", () => {
test("no lazy blocks in single top level class", async () => {
await expectDiff("no-lazy-single-class.js");
});
test("should acknowledge jsx_expression lazy comments", async () => {
await expectDiff("migration-page.tsx");
});
});

View file

@ -135,10 +135,10 @@ export async function deterministicApplyLazyEdit(
}
}
const acc: AstReplacements = [];
findLazyBlockReplacements(oldTree.rootNode, newTree.rootNode, acc);
const replacements: AstReplacements = [];
findLazyBlockReplacements(oldTree.rootNode, newTree.rootNode, replacements);
const newFullFile = reconstructNewFile(oldFile, newLazyFile, acc);
const newFullFile = reconstructNewFile(oldFile, newLazyFile, replacements);
const diff = myersDiff(oldFile, newFullFile);
// If the diff is too messy and seems likely borked, we fall back to LLM strategy
@ -155,9 +155,27 @@ export function isLazyLine(text: string): boolean {
}
function isLazyBlock(node: Parser.SyntaxNode): boolean {
// Special case for "{/* ... existing code ... */}"
if (
node.type === "jsx_expression" &&
node.namedChildCount === 1 &&
isLazyBlock(node.namedChildren[0])
) {
return true;
}
return node.type.includes("comment") && isLazyLine(node.text);
}
function stringsWithinLevDistThreshold(
a: string,
b: string,
threshold: number,
) {
const dist = distance(a, b);
return dist / Math.min(a.length, b.length) <= threshold;
}
/**
* Determine whether two nodes are similar
* @param a
@ -184,11 +202,23 @@ function nodesAreSimilar(a: Parser.SyntaxNode, b: Parser.SyntaxNode): boolean {
return true;
}
// Matching jsx_elements needs to be different because they have such a minimal first line
if (
a.type === "jsx_element" &&
b.type === "jsx_element" &&
// Check that the tag names match
a.namedChildren[0]?.children[1]?.text ===
b.namedChildren[0]?.children[1]?.text
) {
if (stringsWithinLevDistThreshold(a.text, b.text, 0.3)) {
return true;
}
}
const lineOneA = a.text.split("\n")[0];
const lineOneB = b.text.split("\n")[0];
const levDist = distance(lineOneA, lineOneB);
return levDist / Math.min(lineOneA.length, lineOneB.length) <= 0.2;
return stringsWithinLevDistThreshold(lineOneA, lineOneB, 0.2);
}
function nodesAreExact(a: Parser.SyntaxNode, b: Parser.SyntaxNode): boolean {
@ -204,7 +234,7 @@ function nodesAreExact(a: Parser.SyntaxNode, b: Parser.SyntaxNode): boolean {
function findLazyBlockReplacements(
oldNode: Parser.SyntaxNode,
newNode: Parser.SyntaxNode,
acc: AstReplacements,
replacements: AstReplacements,
): void {
// Base case
if (nodesAreExact(oldNode, newNode)) {
@ -254,7 +284,7 @@ function findLazyBlockReplacements(
}
// then recurse at the match
findLazyBlockReplacements(L, rightChildren[0], acc);
findLazyBlockReplacements(L, rightChildren[0], replacements);
// then consume L and R
leftChildren.shift();
@ -263,7 +293,7 @@ function findLazyBlockReplacements(
// Exit "lazy mode"
if (isLazy) {
// Record the replacement lines
acc.push({
replacements.push({
nodeToReplace: currentLazyBlockNode!,
replacementNodes: [...currentLazyBlockReplacementNodes],
});
@ -275,7 +305,7 @@ function findLazyBlockReplacements(
}
if (isLazy) {
acc.push({
replacements.push({
nodeToReplace: currentLazyBlockNode!,
replacementNodes: [...currentLazyBlockReplacementNodes, ...leftChildren],
});
@ -284,7 +314,7 @@ function findLazyBlockReplacements(
// Cut out any extraneous lazy blocks
for (const R of rightChildren) {
if (isLazyBlock(R)) {
acc.push({
replacements.push({
nodeToReplace: R,
replacementNodes: [],
});

View file

@ -2,7 +2,7 @@ import { ILLM } from "../..";
import {
filterLeadingNewline,
stopAtLines,
} from "../../autocomplete/lineStream";
} from "../../autocomplete/streamTransforms/lineStream";
import { streamLines } from "../../diff/util";
import { dedent } from "../../util";

View file

@ -2,7 +2,7 @@ import {
filterLeadingAndTrailingNewLineInsertion,
filterLeadingNewline,
stopAtLines,
} from "../../autocomplete/lineStream.js";
} from "../../autocomplete/streamTransforms/lineStream";
import { streamDiff } from "../../diff/streamDiff.js";
import { LineStream, streamLines } from "../../diff/util.js";
import { DiffLine, ILLM } from "../../index.js";

View file

@ -0,0 +1,166 @@
import { useNavigate } from "react-router-dom";
import ContinueButton from "../components/mainInput/ContinueButton";
function MigrationPage() {
const navigate = useNavigate();
return (
<div className="p-8">
<h1>
Migration to <code>config.json</code>
</h1>
<p>
Continue now uses a .json config file. We hope that this takes the
guesswork out of setting up.
</p>
<p>
Your configuration should have been automatically migrated, but we
recommend double-checking that everything looks correct.
</p>
<p>
For a summary of what changed and examples of <code>config.json</code>,
please see the{" "}
<a
href="https://docs.continue.dev/walkthroughs/config-file-migration"
target="_blank"
>
migration walkthrough
</a>
, and if you have any questions please reach out to us on{" "}
<a href="https://discord.gg/Y83xkG3uUW" target="_blank">
Discord
</a>
.
</p>
<i>
Note: If you are running the server manually and have not updated the
server, this message does not apply.
</i>
<ContinueButton
showStop={false}
onClick={() => {
navigate("/");
}}
disabled={false}
/>
</div>
);
}
export default MigrationPage;
---
import { useNavigate } from "react-router-dom";
import ContinueButton from "../components/mainInput/ContinueButton";
function MigrationPage() {
const navigate = useNavigate();
return (
<div className="p-8">
<h1>
Migration to <code>config.json</code>
</h1>
<p className="text-sm">
Continue now uses a .json config file. We hope that this takes the
guesswork out of setting up.
</p>
<p className="text-sm">
Your configuration should have been automatically migrated, but we
recommend double-checking that everything looks correct.
</p>
<p className="text-sm">
For a summary of what changed and examples of <code>config.json</code>,
please see the{" "}
<a
href="https://docs.continue.dev/walkthroughs/config-file-migration"
target="_blank"
>
migration walkthrough
</a>
, and if you have any questions please reach out to us on{" "}
<a href="https://discord.gg/Y83xkG3uUW" target="_blank">
Discord
</a>
.
</p>
<i className="text-sm">
Note: If you are running the server manually and have not updated the
server, this message does not apply.
</i>
{/* ... existing code ... */}
</div>
);
}
export default MigrationPage;
---
import { useNavigate } from "react-router-dom";
import ContinueButton from "../components/mainInput/ContinueButton";
function MigrationPage() {
const navigate = useNavigate();
return (
<div className="p-8">
<h1>
Migration to <code>config.json</code>
</h1>
- <p>
+ <p className="text-sm">
Continue now uses a .json config file. We hope that this takes the
guesswork out of setting up.
</p>
- <p>
+ <p className="text-sm">
Your configuration should have been automatically migrated, but we
recommend double-checking that everything looks correct.
</p>
- <p>
+ <p className="text-sm">
For a summary of what changed and examples of <code>config.json</code>,
please see the{" "}
<a
href="https://docs.continue.dev/walkthroughs/config-file-migration"
target="_blank"
>
migration walkthrough
</a>
, and if you have any questions please reach out to us on{" "}
<a href="https://discord.gg/Y83xkG3uUW" target="_blank">
Discord
</a>
.
</p>
- <i>
+ <i className="text-sm">
Note: If you are running the server manually and have not updated the
server, this message does not apply.
</i>
<ContinueButton
showStop={false}
onClick={() => {
navigate("/");
}}
disabled={false}
/>
</div>
);
}
export default MigrationPage;

View file

@ -5,7 +5,7 @@ import {
filterLeadingAndTrailingNewLineInsertion,
skipLines,
stopAtLines,
} from "../autocomplete/lineStream.js";
} from "../autocomplete/streamTransforms/lineStream.js";
import { streamDiff } from "../diff/streamDiff.js";
import { streamLines } from "../diff/util.js";
import {

31
core/index.d.ts vendored
View file

@ -70,6 +70,7 @@ export interface ILLM extends LLMOptions {
llmRequestHook?: (model: string, prompt: string) => any;
apiKey?: string;
apiBase?: string;
cacheBehavior?: CacheBehavior;
engine?: string;
apiVersion?: string;
@ -271,6 +272,13 @@ export interface ContextItemId {
itemId: string;
}
export type ContextItemUriTypes = "file" | "url";
export interface ContextItemUri {
type: ContextItemUriTypes;
value: string;
}
export interface ContextItem {
content: string;
name: string;
@ -278,16 +286,11 @@ export interface ContextItem {
editing?: boolean;
editable?: boolean;
icon?: string;
uri?: ContextItemUri;
}
export interface ContextItemWithId {
content: string;
name: string;
description: string;
export interface ContextItemWithId extends ContextItem {
id: ContextItemId;
editing?: boolean;
editable?: boolean;
icon?: string;
}
export interface InputModifiers {
@ -340,6 +343,7 @@ export interface LLMOptions {
apiKey?: string;
aiGatewaySlug?: string;
apiBase?: string;
cacheBehavior?: CacheBehavior;
useLegacyCompletionsEndpoint?: boolean;
@ -369,8 +373,6 @@ export interface LLMOptions {
watsonxStopToken?: string;
watsonxApiVersion?: string;
watsonxFullUrl?: string;
cacheSystemMessage?: boolean;
}
type RequireAtLeastOne<T, Keys extends keyof T = keyof T> = Pick<
T,
@ -498,7 +500,7 @@ export interface IDE {
getCurrentFile(): Promise<string | undefined>;
getPinnedFiles(): Promise<string[]>;
getSearchResults(query: string): Promise<string>;
subprocess(command: string): Promise<[string, string]>;
subprocess(command: string, cwd?: string): Promise<[string, string]>;
getProblems(filepath?: string | undefined): Promise<Problem[]>;
getBranch(dir: string): Promise<string>;
getTags(artifactId: string): Promise<IndexTag[]>;
@ -578,6 +580,7 @@ type ContextProviderName =
| "gitlab-mr"
| "os"
| "currentFile"
| "greptile"
| "outline"
| "continue-proxy"
| "highlights"
@ -727,6 +730,11 @@ export interface RequestOptions {
clientCertificate?: ClientCertificateOptions;
}
export interface CacheBehavior {
cacheSystemMessage?: boolean;
cacheConversation?: boolean;
}
export interface ClientCertificateOptions {
cert: string;
key: string;
@ -789,9 +797,11 @@ export interface ModelDescription {
requestOptions?: RequestOptions;
promptTemplates?: { [key: string]: string };
capabilities?: ModelCapability;
cacheBehavior?: CacheBehavior;
}
export type EmbeddingsProviderName =
| "sagemaker"
| "bedrock"
| "huggingface-tei"
| "transformers.js"
@ -873,6 +883,7 @@ export interface TabAutocompleteOptions {
recentLinePrefixMatchMinLength: number;
disableInFiles?: string[];
useImports?: boolean;
useRootPathContext?: boolean;
}
export interface ContinueUIConfig {

View file

@ -341,6 +341,10 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex {
name: row.title,
description: getLastNPathParts(row.path, 2),
content: `\`\`\`${getBasename(row.path)}\n${row.content}\n\`\`\``,
uri: {
type: "file",
value: row.path,
},
};
}

View file

@ -249,10 +249,11 @@ export class CodebaseIndexer {
}
}
yield {
progress: 100,
progress: 1,
desc: "Indexing Complete",
status: "done",
};
this.logProgress(beginTime, 0, 1);
}
private handleErrorAndGetProgressUpdate(
@ -303,9 +304,9 @@ export class CodebaseIndexer {
const seconds = Math.round(timeTaken / 1000);
const progressPercentage = (progress * 100).toFixed(1);
const filesPerSec = (completedFileCount / seconds).toFixed(2);
console.debug(
`Indexing: ${progressPercentage}% complete, elapsed time: ${seconds}s, ${filesPerSec} file/sec`,
);
// console.debug(
// `Indexing: ${progressPercentage}% complete, elapsed time: ${seconds}s, ${filesPerSec} file/sec`,
// );
}
private async *yieldUpdateAndPause(): AsyncGenerator<IndexingProgressUpdate> {

View file

@ -32,6 +32,7 @@ import {
SiteIndexingResults,
} from "./preIndexed";
import preIndexedDocs from "./preIndexedDocs";
import { fetchFavicon, getFaviconBase64 } from "../../util/fetchFavicon";
// Purposefully lowercase because lancedb converts
export interface LanceDbDocsRow {
@ -154,7 +155,10 @@ export default class DocsService {
params: {},
});
this.ide.showToast("info", "Successfuly added docs context provider");
await this.ide.showToast(
"info",
"Successfuly added docs context provider",
);
}
return res === actionMsg;
@ -177,7 +181,7 @@ export default class DocsService {
while (!(await generator.next()).done) {}
}
this.ide.showToast("info", "Docs indexing completed");
await this.ide.showToast("info", "Docs indexing completed");
}
async list() {
@ -250,7 +254,7 @@ export default class DocsService {
}
}
Telemetry.capture("docs_pages_crawled", {
void Telemetry.capture("docs_pages_crawled", {
count: processedPages,
});
@ -321,7 +325,7 @@ export default class DocsService {
await this.delete(startUrl);
}
const favicon = await this.fetchFavicon(siteIndexingConfig);
const favicon = await fetchFavicon(new URL(siteIndexingConfig.startUrl));
await this.add({
siteIndexingConfig,
@ -460,14 +464,14 @@ export default class DocsService {
for (const doc of newDocs) {
console.log(`Indexing new doc: ${doc.startUrl}`);
Telemetry.capture("add_docs_config", { url: doc.startUrl });
void Telemetry.capture("add_docs_config", { url: doc.startUrl });
const generator = this.indexAndAdd(doc);
while (!(await generator.next()).done) {}
}
for (const doc of deletedDocs) {
console.log(`Deleting doc: ${doc.startUrl}`);
// console.debug(`Deleting doc: ${doc.startUrl}`);
await this.delete(doc.startUrl);
}
@ -530,19 +534,24 @@ export default class DocsService {
await table.delete(`title = '${mockRowTitle}'`);
}
private removeInvalidLanceTableNameChars(tableName: string) {
return tableName.replace(/:/g, "");
/**
* From Lance: Table names can only contain alphanumeric characters,
* underscores, hyphens, and periods
*/
private sanitizeLanceTableName(name: string) {
return name.replace(/[^a-zA-Z0-9_.-]/g, "_");
}
private async getLanceTableNameFromEmbeddingsProvider(
isPreIndexedDoc: boolean,
) {
const embeddingsProvider =
await this.getEmbeddingsProvider(isPreIndexedDoc);
const embeddingsProviderId = this.removeInvalidLanceTableNameChars(
embeddingsProvider.id,
const embeddingsProvider = await this.getEmbeddingsProvider(
isPreIndexedDoc,
);
const tableName = this.sanitizeLanceTableName(
`${DocsService.lanceTableName}${embeddingsProvider.id}`,
);
const tableName = `${DocsService.lanceTableName}${embeddingsProviderId}`;
return tableName;
}
@ -694,7 +703,12 @@ export default class DocsService {
const siteEmbeddings = JSON.parse(data) as SiteIndexingResults;
const startUrl = new URL(siteEmbeddings.url).toString();
const favicon = await this.fetchFavicon(preIndexedDocs[startUrl]);
const faviconUrl = preIndexedDocs[startUrl].faviconUrl;
const favicon =
typeof faviconUrl === "string"
? await getFaviconBase64(faviconUrl)
: undefined;
await this.add({
favicon,
@ -707,30 +721,6 @@ export default class DocsService {
});
}
private async fetchFavicon(siteIndexingConfig: SiteIndexingConfig) {
const faviconUrl =
siteIndexingConfig.faviconUrl ??
new URL("/favicon.ico", siteIndexingConfig.startUrl);
try {
const response = await fetch(faviconUrl);
const arrayBuffer = await response.arrayBuffer();
const base64 = btoa(
new Uint8Array(arrayBuffer).reduce(
(data, byte) => data + String.fromCharCode(byte),
"",
),
);
const mimeType = response.headers.get("content-type") || "image/x-icon";
return `data:${mimeType};base64,${base64}`;
} catch {
console.error(`Failed to fetch favicon: ${faviconUrl}`);
}
return undefined;
}
private async shouldReindexDocsOnNewEmbeddingsProvider(
curEmbeddingsProviderId: EmbeddingsProvider["id"],
): Promise<boolean> {

View file

@ -0,0 +1,114 @@
import {
InvokeEndpointCommand,
SageMakerRuntimeClient,
} from "@aws-sdk/client-sagemaker-runtime";
import { fromIni } from "@aws-sdk/credential-providers";
import {
EmbeddingsProviderName,
EmbedOptions,
FetchFunction,
} from "../../index.js";
import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js";
class SageMakerEmbeddingsProvider extends BaseEmbeddingsProvider {
static providerName: EmbeddingsProviderName = "sagemaker";
static defaultOptions: Partial<EmbedOptions> | undefined = {
region: "us-west-2",
maxBatchSize: 1,
};
profile?: string | undefined;
constructor(options: EmbedOptions, fetch: FetchFunction) {
super(options, fetch);
if (!options.apiBase) {
options.apiBase = `https://runtime.sagemaker.${options.region}.amazonaws.com`;
}
if (options.profile) {
this.profile = options.profile;
} else {
this.profile = "sagemaker";
}
}
async embed(chunks: string[]) {
const credentials = await this._getCredentials();
const client = new SageMakerRuntimeClient({
region: this.options.region,
credentials: {
accessKeyId: credentials.accessKeyId,
secretAccessKey: credentials.secretAccessKey,
sessionToken: credentials.sessionToken || "",
},
});
const batchedChunks = this.getBatchedChunks(chunks);
return (
await Promise.all(
batchedChunks.map(async (batch) => {
const input = this._generateInvokeModelCommandInput(
batch,
this.options,
);
const command = new InvokeEndpointCommand(input);
const response = await client.send(command);
if (response.Body) {
const responseBody = JSON.parse(
new TextDecoder().decode(response.Body),
);
// If the body contains a key called "embedding" or "embeddings", return the value, otherwise return the whole body
if (responseBody.embedding) {
return responseBody.embedding;
} else if (responseBody.embeddings) {
return responseBody.embeddings;
} else {
return responseBody;
}
}
}),
)
).flat();
}
private _generateInvokeModelCommandInput(
prompts: string | string[],
options: EmbedOptions,
): any {
const payload = {
inputs: prompts,
normalize: true,
// ...(options.requestOptions?.extraBodyProperties || {}),
};
if (options.requestOptions?.extraBodyProperties) {
Object.assign(payload, options.requestOptions.extraBodyProperties);
}
return {
EndpointName: this.options.model,
Body: JSON.stringify(payload),
ContentType: "application/json",
CustomAttributes: "accept_eula=false",
};
}
private async _getCredentials() {
try {
return await fromIni({
profile: this.profile,
ignoreCache: true,
})();
} catch (e) {
console.warn(
`AWS profile with name ${this.profile} not found in ~/.aws/credentials, using default profile`,
);
return await fromIni()();
}
}
}
export default SageMakerEmbeddingsProvider;

View file

@ -1,5 +1,6 @@
import { EmbeddingsProviderName } from "../../index.js";
import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js";
import SageMakerEmbeddingsProvider from "./SageMakerEmbeddingsProvider.js";
import BedrockEmbeddingsProvider from "./BedrockEmbeddingsProvider.js";
import CohereEmbeddingsProvider from "./CohereEmbeddingsProvider.js";
import ContinueProxyEmbeddingsProvider from "./ContinueProxyEmbeddingsProvider.js";
@ -22,6 +23,7 @@ export const allEmbeddingsProviders: Record<
EmbeddingsProviderName,
EmbeddingsProviderConstructor
> = {
sagemaker: SageMakerEmbeddingsProvider,
bedrock: BedrockEmbeddingsProvider,
ollama: OllamaEmbeddingsProvider,
"transformers.js": TransformersJsEmbeddingsProvider,

View file

@ -68,6 +68,8 @@ export const DEFAULT_IGNORE_FILETYPES = [
"*.uasset",
"*.pdb",
"*.bin",
"*.pag",
"*.swp",
// "*.prompt", // can be incredibly confusing for the LLM to have another set of instructions injected into the prompt
];

View file

@ -74,6 +74,7 @@ const MODEL_SUPPORTS_IMAGES: string[] = [
"sonnet",
"opus",
"haiku",
"pixtral",
];
function modelSupportsImages(

View file

@ -5,9 +5,10 @@ const SYSTEM_MESSAGE = `When generating new code:
1. Always produce a single code block.
2. Never separate the code into multiple code blocks.
3. Only include the code that is being added.
4. Replace existing code with a "lazy" block like this: "// ... existing code ..."
5. You must always provide 1-2 lines of context above and below a "lazy" block
6. If the user submits a code block that contains a filename in the language specifier, always include the filename in any code block you generate based on that file. The filename should be on the same line as the language specifier in your code block.
4. Replace existing code with a "lazy" comment like this: "// ... existing code ..."
5. The "lazy" comment must always be a valid comment in the current context (e.g. "<!-- ... existing code ... -->" for HTML, "// ... existing code ..." for JavaScript, "{/* ... existing code */}" for TSX, etc.)
6. You must always provide 1-2 lines of context above and below a "lazy" comment
7. If the user submits a code block that contains a filename in the language specifier, always include the filename in any code block you generate based on that file. The filename should be on the same line as the language specifier in your code block.
Example 1:
Input:

View file

@ -1,6 +1,7 @@
import { findLlmInfo } from "@continuedev/llm-info";
import Handlebars from "handlebars";
import {
CacheBehavior,
ChatMessage,
ChatMessageRole,
CompletionOptions,
@ -102,6 +103,7 @@ export abstract class BaseLLM implements ILLM {
llmRequestHook?: (model: string, prompt: string) => any;
apiKey?: string;
apiBase?: string;
cacheBehavior?: CacheBehavior;
capabilities?: ModelCapability;
engine?: string;
@ -120,8 +122,6 @@ export abstract class BaseLLM implements ILLM {
watsonxApiVersion?: string;
watsonxFullUrl?: string;
cacheSystemMessage?: boolean;
private _llmOptions: LLMOptions;
constructor(_options: LLMOptions) {
@ -184,6 +184,7 @@ export abstract class BaseLLM implements ILLM {
this.apiKey = options.apiKey;
this.aiGatewaySlug = options.aiGatewaySlug;
this.apiBase = options.apiBase;
this.cacheBehavior = options.cacheBehavior;
// for watsonx only
this.watsonxUrl = options.watsonxUrl;
@ -193,8 +194,6 @@ export abstract class BaseLLM implements ILLM {
this.watsonxApiVersion = options.watsonxApiVersion;
this.watsonxFullUrl = options.watsonxFullUrl;
this.cacheSystemMessage = options.cacheSystemMessage;
if (this.apiBase && !this.apiBase.endsWith("/")) {
this.apiBase = `${this.apiBase}/`;
}
@ -262,16 +261,29 @@ export abstract class BaseLLM implements ILLM {
prompt: string,
completionOptions: CompletionOptions,
): string {
const dict = { contextLength: this.contextLength, ...completionOptions };
const settings = Object.entries(dict)
.map(([key, value]) => `${key}: ${value}`)
.join("\n");
return `Settings:
${settings}
const completionOptionsLog = JSON.stringify(
{
contextLength: this.contextLength,
...completionOptions,
},
null,
2,
);
############################################
let requestOptionsLog = "";
if (this.requestOptions) {
requestOptionsLog = JSON.stringify(this.requestOptions, null, 2);
}
${prompt}`;
return (
"##### Completion options #####\n" +
completionOptionsLog +
(requestOptionsLog
? "\n\n##### Request options #####\n" + requestOptionsLog
: "") +
"\n\n##### Prompt #####\n" +
prompt
);
}
private _logTokensGenerated(
@ -417,7 +429,7 @@ ${prompt}`;
return formatted;
}
async *_streamFim(
protected async *_streamFim(
prefix: string,
suffix: string,
options: CompletionOptions,
@ -703,9 +715,6 @@ ${prompt}`;
this.providerName,
autodetectTemplateType(this.model),
);
if (!templateMessages) {
return rendered;
}
return templateMessages(rendered);
}
return rendered;

View file

@ -35,17 +35,40 @@ class Anthropic extends BaseLLM {
}
private _convertMessages(msgs: ChatMessage[]): any[] {
const messages = msgs
.filter((m) => m.role !== "system")
.map((message) => {
const filteredmessages = msgs.filter((m) => m.role !== "system")
const lastTwoUserMsgIndices = filteredmessages
.map((msg, index) => (msg.role === "user" ? index : -1))
.filter((index) => index !== -1).slice(-2);
const messages = filteredmessages.map((message, filteredMsgIdx) => {
// Add cache_control parameter to the last two user messages
// The second-to-last because it retrieves potentially already cached contents,
// The last one because we want it cached for later retrieval.
// See: https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching
const addCaching = this.cacheBehavior?.cacheConversation && lastTwoUserMsgIndices.includes(filteredMsgIdx);
if (typeof message.content === "string") {
return message;
var chatMessage = {
...message,
content: [{
type: "text",
text: message.content,
...(addCaching? { cache_control: { type: "ephemeral" } } : {})
}]
};
return chatMessage;
}
return {
...message,
content: message.content.map((part) => {
content: message.content.map((part, contentIdx) => {
if (part.type === "text") {
return part;
const newpart = {
...part,
// If multiple text parts, only add cache_control to the last one
...((addCaching && contentIdx == message.content.length - 1) ? { cache_control: { type: "ephemeral" } } : {})
};
return newpart;
}
return {
type: "image",
@ -75,9 +98,7 @@ class Anthropic extends BaseLLM {
messages: ChatMessage[],
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
const shouldCacheSystemMessage =
!!this.systemMessage && !!this.cacheSystemMessage;
const shouldCacheSystemMessage = !!this.systemMessage && this.cacheBehavior?.cacheSystemMessage;
const systemMessage: string = stripImages(
messages.filter((m) => m.role === "system")[0]?.content,
);
@ -89,7 +110,7 @@ class Anthropic extends BaseLLM {
Accept: "application/json",
"anthropic-version": "2023-06-01",
"x-api-key": this.apiKey as string,
...(shouldCacheSystemMessage
...(shouldCacheSystemMessage || this.cacheBehavior?.cacheConversation
? { "anthropic-beta": "prompt-caching-2024-07-31" }
: {}),
},
@ -115,6 +136,7 @@ class Anthropic extends BaseLLM {
}
for await (const value of streamSse(response)) {
if (value.type == "message_start") console.log(value);
if (value.delta?.text) {
yield { role: "assistant", content: value.delta.text };
}

View file

@ -1,8 +1,18 @@
import { ModelProvider } from "../../index.js";
import { LLMOptions, ModelProvider } from "../../index.js";
import OpenAI from "./OpenAI.js";
class Azure extends OpenAI {
static providerName: ModelProvider = "azure";
static defaultOptions: Partial<LLMOptions> = {
apiVersion: "2024-02-15-preview",
apiType: "azure",
};
constructor(options: LLMOptions) {
super(options);
this.engine = options.model;
}
}
export default Azure;

View file

@ -3,6 +3,7 @@ import { BaseLLM } from "../index.js";
import { streamSse } from "../stream.js";
class HuggingFaceTGI extends BaseLLM {
private static MAX_STOP_TOKENS = 4;
static providerName: ModelProvider = "huggingface-tgi";
static defaultOptions: Partial<LLMOptions> = {
apiBase: "http://localhost:8080/",
@ -36,7 +37,10 @@ class HuggingFaceTGI extends BaseLLM {
top_k: options.topK,
presence_penalty: options.presencePenalty,
frequency_penalty: options.frequencyPenalty,
stop: options.stop,
stop: options.stop?.slice(
0,
this.maxStopWords ?? HuggingFaceTGI.MAX_STOP_TOKENS,
),
};
return finalOptions;

View file

@ -15,6 +15,8 @@ class Ollama extends BaseLLM {
model: "codellama-7b",
};
private fimSupported: boolean = false;
constructor(options: LLMOptions) {
super(options);
@ -31,7 +33,7 @@ class Ollama extends BaseLLM {
body: JSON.stringify({ name: this._getModel() }),
})
.then(async (response) => {
if (response.status !== 200) {
if (response?.status !== 200) {
// console.warn(
// "Error calling Ollama /api/show endpoint: ",
// await response.text(),
@ -61,7 +63,7 @@ class Ollama extends BaseLLM {
this.completionOptions.stop.push(JSON.parse(value));
} catch (e) {
console.warn(
"Error parsing stop parameter value \"{value}: ${e}",
'Error parsing stop parameter value "{value}: ${e}',
);
}
break;
@ -70,6 +72,13 @@ class Ollama extends BaseLLM {
}
}
}
/**
* There is no API to get the model's FIM capabilities, so we have to
* make an educated guess. If a ".Suffix" variable appears in the template
* it's a good indication the model supports FIM.
*/
this.fimSupported = !!body?.template?.includes(".Suffix");
})
.catch((e) => {
// console.warn("Error calling the Ollama /api/show endpoint: ", e);
@ -132,11 +141,13 @@ class Ollama extends BaseLLM {
private _convertArgs(
options: CompletionOptions,
prompt: string | ChatMessage[],
suffix?: string,
) {
const finalOptions: any = {
model: this._getModel(),
raw: true,
keep_alive: options.keepAlive ?? 60 * 30, // 30 minutes
suffix,
options: {
temperature: options.temperature,
top_p: options.topP,
@ -248,6 +259,50 @@ class Ollama extends BaseLLM {
}
}
supportsFim(): boolean {
return this.fimSupported;
}
protected async *_streamFim(
prefix: string,
suffix: string,
options: CompletionOptions,
): AsyncGenerator<string> {
const response = await this.fetch(this.getEndpoint("api/generate"), {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${this.apiKey}`,
},
body: JSON.stringify(this._convertArgs(options, prefix, suffix)),
});
let buffer = "";
for await (const value of streamResponse(response)) {
// Append the received chunk to the buffer
buffer += value;
// Split the buffer into individual JSON chunks
const chunks = buffer.split("\n");
buffer = chunks.pop() ?? "";
for (let i = 0; i < chunks.length; i++) {
const chunk = chunks[i];
if (chunk.trim() !== "") {
try {
const j = JSON.parse(chunk);
if ("response" in j) {
yield j.response;
} else if ("error" in j) {
throw new Error(j.error);
}
} catch (e) {
throw new Error(`Error parsing Ollama response: ${e} ${chunk}`);
}
}
}
}
}
async listModels(): Promise<string[]> {
const response = await this.fetch(
// localhost was causing fetch failed in pkg binary only for this Ollama endpoint

View file

@ -264,7 +264,7 @@ class OpenAI extends BaseLLM {
}
}
async *_streamFim(
protected async *_streamFim(
prefix: string,
suffix: string,
options: CompletionOptions,

View file

@ -6,7 +6,6 @@ import {
ModelDescription,
} from "../..";
import { renderTemplatedString } from "../../promptFiles/renderTemplatedString";
import { DEFAULT_MAX_TOKENS } from "../constants";
import { BaseLLM } from "../index";
import Anthropic from "./Anthropic";
import Azure from "./Azure";
@ -112,8 +111,7 @@ export async function llmFromDescription(
model: (desc.model || cls.defaultOptions?.model) ?? "codellama-7b",
maxTokens:
finalCompletionOptions.maxTokens ??
cls.defaultOptions?.completionOptions?.maxTokens ??
DEFAULT_MAX_TOKENS,
cls.defaultOptions?.completionOptions?.maxTokens,
},
systemMessage,
writeLog,

21
core/package-lock.json generated
View file

@ -39,6 +39,7 @@
"jsdom": "^24.0.0",
"launchdarkly-node-client-sdk": "^3.2.0",
"llm-code-highlighter": "^0.0.14",
"lru-cache": "^10.2.2",
"mac-ca": "^3.1.0",
"node-fetch": "^3.3.2",
"node-html-markdown": "^1.3.0",
@ -1342,6 +1343,15 @@
"node": ">=6.9.0"
}
},
"node_modules/@babel/helper-compilation-targets/node_modules/lru-cache": {
"version": "5.1.1",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz",
"integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==",
"dev": true,
"dependencies": {
"yallist": "^3.0.2"
}
},
"node_modules/@babel/helper-compilation-targets/node_modules/semver": {
"version": "6.3.1",
"resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz",
@ -10481,12 +10491,11 @@
"integrity": "sha512-lcHwpNoggQTObv5apGNCTdJrO69eHOZMi4BNC+rTLER8iHAqGrUVeLh/irVIM7zTw2bOXA8T6uNPeujwOLg/2Q=="
},
"node_modules/lru-cache": {
"version": "5.1.1",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz",
"integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==",
"dev": true,
"dependencies": {
"yallist": "^3.0.2"
"version": "10.2.2",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.2.2.tgz",
"integrity": "sha512-9hp3Vp2/hFQUiIwKo8XCeFVnrg8Pk3TYNPIR7tJADKi5YfcF7vEaK7avFHTlSy3kOKYaJQaalfEo6YuXdceBOQ==",
"engines": {
"node": "14 || >=16.14"
}
},
"node_modules/mac-ca": {

View file

@ -69,6 +69,7 @@
"jsdom": "^24.0.0",
"launchdarkly-node-client-sdk": "^3.2.0",
"llm-code-highlighter": "^0.0.14",
"lru-cache": "^10.2.2",
"mac-ca": "^3.1.0",
"node-fetch": "^3.3.2",
"node-html-markdown": "^1.3.0",

View file

@ -1,5 +1,3 @@
import type { AutocompleteInput } from "../autocomplete/completionProvider";
import { ProfileDescription } from "../config/ConfigHandler";
import type {
BrowserSerializedContinueConfig,
ChatMessage,
@ -10,12 +8,15 @@ import type {
LLMFullCompletionOptions,
MessageContent,
ModelDescription,
ModelRoles,
PersistedSessionInfo,
RangeInFile,
SerializedContinueConfig,
SessionInfo,
SiteIndexingConfig,
} from "../";
import type { AutocompleteInput } from "../autocomplete/completionProvider";
import { ProfileDescription } from "../config/ConfigHandler";
export type ProtocolGeneratorType<T> = AsyncGenerator<{
done?: boolean;
@ -50,7 +51,10 @@ export type ToCoreFromIdeOrWebviewProtocol = {
"devdata/log": [{ tableName: string; data: any }, void];
"config/addOpenAiKey": [string, void];
"config/addModel": [
{ model: SerializedContinueConfig["models"][number] },
{
model: SerializedContinueConfig["models"][number];
role?: keyof ModelRoles;
},
void,
];
"config/newPromptFile": [undefined, void];

View file

@ -29,7 +29,7 @@ export type ToIdeFromWebviewOrCoreProtocol = {
openFile: [{ path: string }, void];
runCommand: [{ command: string }, void];
getSearchResults: [{ query: string }, string];
subprocess: [{ command: string }, [string, string]];
subprocess: [{ command: string; cwd?: string }, [string, string]];
saveFile: [{ filepath: string }, void];
fileExists: [{ filepath: string }, boolean];
readFile: [{ filepath: string }, string];
@ -97,4 +97,5 @@ export type ToWebviewOrCoreFromIdeProtocol = {
{ sessionInfo: ControlPlaneSessionInfo | undefined },
void,
];
didChangeIdeSettings: [{ settings: IdeSettings }, void];
};

View file

@ -15,22 +15,28 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
},
];
openUrl: [string, void];
applyToCurrentFile: [{ text: string }, void];
applyToCurrentFile: [{ text: string; streamId: string }, void];
showTutorial: [undefined, void];
showFile: [{ filepath: string }, void];
openConfigJson: [undefined, void];
toggleDevTools: [undefined, void];
reloadWindow: [undefined, void];
focusEditor: [undefined, void];
toggleFullScreen: [undefined, void];
toggleFullScreen: [{ newWindow?: boolean } | undefined, void];
insertAtCursor: [{ text: string }, void];
copyText: [{ text: string }, void];
"jetbrains/editorInsetHeight": [{ height: number }, void];
"vscode/openMoveRightMarkdown": [undefined, void];
setGitHubAuthToken: [{ token: string }, void];
acceptDiff: [{ filepath: string }, void];
rejectDiff: [{ filepath: string }, void];
};
export interface ApplyState {
streamId: string;
status: "streaming" | "done" | "closed";
}
export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & {
setInactive: [undefined, void];
setTTSActive: [boolean, void];
@ -52,8 +58,13 @@ export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & {
},
void,
];
navigateTo: [{ path: string; toggle?: boolean }, void];
addModel: [undefined, void];
openSettings: [undefined, void];
/**
* @deprecated Use navigateTo with a path instead.
*/
viewHistory: [undefined, void];
newSession: [undefined, void];
setTheme: [{ theme: any }, void];
@ -64,4 +75,5 @@ export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & {
incrementFtc: [undefined, void];
openOnboardingCard: [undefined, void];
applyCodeFromChat: [undefined, void];
updateApplyState: [ApplyState, void];
};

View file

@ -0,0 +1,76 @@
// File generated by Continue
import { dedentAndGetCommonWhitespace } from "../../util";
describe("dedentAndGetCommonWhitespace", () => {
let originalString: string;
beforeEach(() => {
// Setup any global variables or states if needed
originalString = " line1\n line2\n line3";
});
afterEach(() => {
// Tear down any changes to global variables or states if needed
originalString = "";
});
test("should dedent and return common whitespace for a simple case", () => {
const input = " line1\n line2\n line3";
const output = dedentAndGetCommonWhitespace(input);
expect(output).toEqual(["line1\nline2\nline3", " "]);
});
test("should handle empty string", () => {
const input = "";
const output = dedentAndGetCommonWhitespace(input);
expect(output).toEqual(["", ""]);
});
test("should handle string with only whitespace", () => {
const input = " ";
const output = dedentAndGetCommonWhitespace(input);
expect(output).toEqual(["", ""]);
});
test("should handle string with mixed whitespace and content", () => {
const input = " line1\n line2\n line3";
const output = dedentAndGetCommonWhitespace(input);
expect(output).toEqual([" line1\nline2\n line3", " "]);
});
test("should handle string with no common leading whitespace", () => {
const input = "line1\n line2\n line3";
const output = dedentAndGetCommonWhitespace(input);
expect(output).toEqual([input, ""]);
});
test("should handle string with empty lines", () => {
const input = " line1\n\n line3";
const output = dedentAndGetCommonWhitespace(input);
expect(output).toEqual(["line1\n\nline3", " "]);
});
test("should handle string with only empty lines", () => {
const input = "\n\n";
const output = dedentAndGetCommonWhitespace(input);
expect(output).toEqual(["\n\n", ""]);
});
test("should handle string with tabs as whitespace", () => {
const input = "\tline1\n\tline2\n\tline3";
const output = dedentAndGetCommonWhitespace(input);
expect(output).toEqual(["line1\nline2\nline3", "\t"]);
});
test("should handle string with mixed tabs and spaces", () => {
const input = "\t line1\n\t line2\n\t line3";
const output = dedentAndGetCommonWhitespace(input);
expect(output).toEqual(["line1\nline2\nline3", "\t "]);
});
test("should handle string with different leading whitespace lengths", () => {
const input = " line1\n line2\n line3";
const output = dedentAndGetCommonWhitespace(input);
expect(output).toEqual([" line1\nline2\n line3", " "]);
});
});

View file

@ -0,0 +1,51 @@
// File generated by Continue
import { getLastNPathParts } from "../../util";
describe("getLastNPathParts", () => {
const SEP_REGEX = /[\\/]+/;
beforeAll(() => {
// Setup code if needed
});
afterAll(() => {
// Teardown code if needed
});
test("returns the last N parts of a filepath with forward slashes", () => {
const filepath = "home/user/documents/project/file.txt";
expect(getLastNPathParts(filepath, 2)).toBe("project/file.txt");
});
test("returns the last N parts of a filepath with backward slashes", () => {
const filepath = "C:\\home\\user\\documents\\project\\file.txt";
expect(getLastNPathParts(filepath, 3)).toBe("documents/project/file.txt");
});
test("returns the last part if N is 1", () => {
const filepath = "/home/user/documents/project/file.txt";
expect(getLastNPathParts(filepath, 1)).toBe("file.txt");
});
test("returns the entire path if N is greater than the number of parts", () => {
const filepath = "home/user/documents/project/file.txt";
expect(getLastNPathParts(filepath, 10)).toBe(
"home/user/documents/project/file.txt",
);
});
test("returns an empty string if N is 0", () => {
const filepath = "home/user/documents/project/file.txt";
expect(getLastNPathParts(filepath, 0)).toBe("");
});
test("handles paths with mixed forward and backward slashes", () => {
const filepath = "home\\user/documents\\project/file.txt";
expect(getLastNPathParts(filepath, 3)).toBe("documents/project/file.txt");
});
test("handles edge case with empty filepath", () => {
const filepath = "";
expect(getLastNPathParts(filepath, 2)).toBe("");
});
});

View file

@ -0,0 +1,40 @@
// This file is generated by Continue
import { longestCommonSubsequence } from "../../util/lcs";
describe("longestCommonSubsequence", () => {
beforeAll(() => {
// Setup if needed
});
afterAll(() => {
// Teardown if needed
});
test("should return the longest common subsequence for non-empty strings", () => {
expect(longestCommonSubsequence("abcde", "ace")).toBe("ace");
expect(longestCommonSubsequence("abc", "abc")).toBe("abc");
expect(longestCommonSubsequence("abc", "def")).toBe("");
});
test("should handle cases where one or both strings are empty", () => {
expect(longestCommonSubsequence("", "abc")).toBe("");
expect(longestCommonSubsequence("abc", "")).toBe("");
expect(longestCommonSubsequence("", "")).toBe("");
});
test("should handle cases with no common subsequence", () => {
expect(longestCommonSubsequence("abc", "def")).toBe("");
expect(longestCommonSubsequence("xyz", "abc")).toBe("");
});
test("should handle cases with special characters", () => {
expect(longestCommonSubsequence("a!@#b$c", "!@#$")).toBe("!@#$");
expect(longestCommonSubsequence("a!@#b$c", "xyz")).toBe("");
});
test("should handle long strings efficiently", () => {
const str1 = "a".repeat(1000) + "b".repeat(1000);
const str2 = "a".repeat(1000) + "c".repeat(1000);
expect(longestCommonSubsequence(str1, str2)).toBe("a".repeat(1000));
});
});

View file

@ -0,0 +1,100 @@
// File generated by Continue
import { mergeJson } from "../../util/merge";
describe("mergeJson", () => {
it("should merge two simple JSON objects", () => {
const first = { a: 1, b: 2 };
const second = { b: 3, c: 4 };
const result = mergeJson(first, second);
expect(result).toEqual({ a: 1, b: 3, c: 4 });
});
it('should overwrite values when mergeBehavior is "overwrite"', () => {
const first = { a: 1, b: 2 };
const second = { b: 3, c: 4 };
const result = mergeJson(first, second, "overwrite");
expect(result).toEqual({ a: 1, b: 3, c: 4 });
});
it("should merge nested objects", () => {
const first = { a: { b: 1 } };
const second = { a: { c: 2 } };
const result = mergeJson(first, second);
expect(result).toEqual({ a: { b: 1, c: 2 } });
});
it("should merge arrays without mergeKeys", () => {
const first = { a: [1, 2] };
const second = { a: [3, 4] };
const result = mergeJson(first, second);
expect(result).toEqual({ a: [1, 2, 3, 4] });
});
it("should merge arrays with mergeKeys", () => {
const first = {
a: [
{ id: 1, value: "first" },
{ id: 2, value: "second" },
],
};
const second = {
a: [
{ id: 2, value: "updated" },
{ id: 3, value: "third" },
],
};
const mergeKeys = {
a: (item1: any, item2: any) => item1.id === item2.id,
};
const result = mergeJson(first, second, undefined, mergeKeys);
expect(result).toEqual({
a: [
{ id: 1, value: "first" },
{ id: 2, value: "updated" },
{ id: 3, value: "third" },
],
});
});
it("should handle non-object values correctly", () => {
const first = { a: 1, b: "string", c: true };
const second = { a: 2, b: "new string", c: false };
const result = mergeJson(first, second);
expect(result).toEqual({ a: 2, b: "new string", c: false });
});
it("should handle null and undefined values correctly", () => {
const first = { a: 1, b: null };
const second = { b: 2, c: undefined };
const result = mergeJson(first, second);
expect(result).toEqual({ a: 1, b: 2, c: undefined });
});
it("should handle empty objects", () => {
const first = {};
const second = { a: 1 };
const result = mergeJson(first, second);
expect(result).toEqual({ a: 1 });
});
it("should handle empty second object", () => {
const first = { a: 1 };
const second = {};
const result = mergeJson(first, second);
expect(result).toEqual({ a: 1 });
});
it("should handle errors gracefully", () => {
const first = { a: 1 };
const second = { b: () => {} }; // Functions are not serializable in JSON
const result = mergeJson(first, second);
expect(result).toEqual({ a: 1, b: expect.any(Function) });
});
it("should merge deeply nested objects", () => {
const first = { a: { b: { c: 1 } } };
const second = { a: { b: { d: 2 } } };
const result = mergeJson(first, second);
expect(result).toEqual({ a: { b: { c: 1, d: 2 } } });
});
});

View file

@ -0,0 +1,105 @@
// This file is generated by Continue
import { getRangeInString } from "../../../util/ranges";
describe.skip("getRangeInString", () => {
let content: string;
beforeEach(() => {
content = `Line 1
Line 2
Line 3
Line 4
Line 5`;
});
afterEach(() => {
content = "";
});
test("should return substring within the same line", () => {
const range = {
start: { line: 1, character: 0 },
end: { line: 1, character: 4 },
};
expect(getRangeInString(content, range)).toBe("Line");
});
test("should return substring spanning multiple lines", () => {
const range = {
start: { line: 1, character: 2 },
end: { line: 3, character: 3 },
};
const expected = `ne 2
Line 3
Line 4`;
expect(getRangeInString(content, range)).toBe(expected);
});
test("should handle range that starts and ends at the same character", () => {
const range = {
start: { line: 2, character: 0 },
end: { line: 2, character: 0 },
};
expect(getRangeInString(content, range)).toBe("L");
});
test("should handle range that spans entire content", () => {
const range = {
start: { line: 0, character: 0 },
end: { line: 4, character: 5 },
};
expect(getRangeInString(content, range)).toBe(content);
});
test("should handle range that spans to the end of the last line", () => {
const range = {
start: { line: 3, character: 2 },
end: { line: 4, character: 5 },
};
const expected = `ne 4
Line 5`;
expect(getRangeInString(content, range)).toBe(expected);
});
test("should handle empty content", () => {
content = "";
const range = {
start: { line: 0, character: 0 },
end: { line: 0, character: 0 },
};
expect(getRangeInString(content, range)).toBe("");
});
test("should handle invalid range (start line > end line)", () => {
const range = {
start: { line: 3, character: 0 },
end: { line: 2, character: 0 },
};
expect(getRangeInString(content, range)).toBe("");
});
test("should handle invalid range (start character > end character on same line)", () => {
const range = {
start: { line: 1, character: 5 },
end: { line: 1, character: 2 },
};
expect(getRangeInString(content, range)).toBe("");
});
test("should handle range that starts and ends at the same line but different characters", () => {
const range = {
start: { line: 1, character: 2 },
end: { line: 1, character: 6 },
};
expect(getRangeInString(content, range)).toBe("ne 2");
});
test("should handle range that starts and ends at the same line and same characters", () => {
const range = {
start: { line: 1, character: 2 },
end: { line: 1, character: 2 },
};
expect(getRangeInString(content, range)).toBe("n");
});
});

View file

@ -0,0 +1,123 @@
// This file is generated by Continue
import { intersection } from "../../../util/ranges";
interface Position {
line: number;
character: number;
}
interface Range {
start: Position;
end: Position;
}
describe("intersection", () => {
let rangeA: Range;
let rangeB: Range;
beforeEach(() => {
rangeA = {
start: { line: 1, character: 0 },
end: { line: 3, character: 5 },
};
rangeB = {
start: { line: 2, character: 2 },
end: { line: 4, character: 0 },
};
});
test("returns correct intersection for overlapping ranges", () => {
const result = intersection(rangeA, rangeB);
expect(result).toEqual({
start: { line: 2, character: 2 },
end: { line: 3, character: 5 },
});
});
test("returns null for non-overlapping ranges", () => {
rangeA = {
start: { line: 1, character: 0 },
end: { line: 2, character: 0 },
};
rangeB = {
start: { line: 3, character: 0 },
end: { line: 4, character: 0 },
};
const result = intersection(rangeA, rangeB);
expect(result).toBeNull();
});
// TODO
test.skip("returns correct intersection for single line overlap", () => {
rangeA = {
start: { line: 1, character: 0 },
end: { line: 1, character: 5 },
};
rangeB = {
start: { line: 1, character: 3 },
end: { line: 2, character: 0 },
};
const result = intersection(rangeA, rangeB);
expect(result).toEqual({
start: { line: 1, character: 3 },
end: { line: 1, character: 5 },
});
});
test("returns null for single line non-overlapping ranges", () => {
rangeA = {
start: { line: 1, character: 0 },
end: { line: 1, character: 2 },
};
rangeB = {
start: { line: 1, character: 3 },
end: { line: 1, character: 5 },
};
const result = intersection(rangeA, rangeB);
expect(result).toBeNull();
});
test("returns correct intersection when one range is fully within another", () => {
rangeA = {
start: { line: 1, character: 0 },
end: { line: 4, character: 5 },
};
rangeB = {
start: { line: 2, character: 2 },
end: { line: 3, character: 3 },
};
const result = intersection(rangeA, rangeB);
expect(result).toEqual({
start: { line: 2, character: 2 },
end: { line: 3, character: 3 },
});
});
test("returns correct intersection when ranges touch at the edge", () => {
rangeA = {
start: { line: 1, character: 0 },
end: { line: 2, character: 0 },
};
rangeB = {
start: { line: 2, character: 0 },
end: { line: 3, character: 0 },
};
const result = intersection(rangeA, rangeB);
expect(result).toEqual({
start: { line: 2, character: 0 },
end: { line: 2, character: 0 },
});
});
});

View file

@ -0,0 +1,70 @@
import { maxPosition, minPosition } from "../../../util/ranges";
// This file is generated by Continue
interface Position {
line: number;
character: number;
}
describe("Position comparison functions", () => {
let pos1: Position;
let pos2: Position;
let pos3: Position;
let pos4: Position;
beforeAll(() => {
// Setup: Initializing positions
pos1 = { line: 1, character: 5 };
pos2 = { line: 2, character: 3 };
pos3 = { line: 1, character: 7 };
pos4 = { line: 2, character: 3 }; // Same as pos2 to test equality
});
describe("maxPosition", () => {
it("should return the position with the greater line number", () => {
expect(maxPosition(pos1, pos2)).toEqual(pos2);
});
it("should return the position with the greater character number when lines are equal", () => {
expect(maxPosition(pos1, pos3)).toEqual(pos3);
});
it("should return the first position when both positions are equal", () => {
expect(maxPosition(pos2, pos4)).toEqual(pos2);
});
it("should handle positions with negative line numbers", () => {
const posNegative = { line: -1, character: 0 };
expect(maxPosition(posNegative, pos1)).toEqual(pos1);
});
it("should handle positions with negative character numbers", () => {
const posNegativeChar = { line: 1, character: -1 };
expect(maxPosition(posNegativeChar, pos1)).toEqual(pos1);
});
});
describe("minPosition", () => {
it("should return the position with the lesser line number", () => {
expect(minPosition(pos1, pos2)).toEqual(pos1);
});
it("should return the position with the lesser character number when lines are equal", () => {
expect(minPosition(pos1, pos3)).toEqual(pos1);
});
it("should return the first position when both positions are equal", () => {
expect(minPosition(pos2, pos4)).toEqual(pos2);
});
it("should handle positions with negative line numbers", () => {
const posNegative = { line: -1, character: 0 };
expect(minPosition(posNegative, pos1)).toEqual(posNegative);
});
it("should handle positions with negative character numbers", () => {
const posNegativeChar = { line: 1, character: -1 };
expect(minPosition(posNegativeChar, pos1)).toEqual(posNegativeChar);
});
});
});

View file

@ -0,0 +1,92 @@
import { union } from "../../../util/ranges";
// This file is generated by Continue
interface Position {
line: number;
character: number;
}
interface Range {
start: Position;
end: Position;
}
describe("union", () => {
let rangeA: Range;
let rangeB: Range;
beforeEach(() => {
rangeA = {
start: { line: 1, character: 0 },
end: { line: 3, character: 5 },
};
rangeB = {
start: { line: 2, character: 3 },
end: { line: 4, character: 2 },
};
});
test("should return the union of two overlapping ranges", () => {
const result = union(rangeA, rangeB);
expect(result).toEqual({
start: { line: 1, character: 0 },
end: { line: 4, character: 2 },
});
});
test("should return the union when ranges are identical", () => {
const result = union(rangeA, rangeA);
expect(result).toEqual(rangeA);
});
test("should return the union when ranges do not overlap but are adjacent", () => {
rangeB = {
start: { line: 3, character: 5 },
end: { line: 4, character: 2 },
};
const result = union(rangeA, rangeB);
expect(result).toEqual({
start: { line: 1, character: 0 },
end: { line: 4, character: 2 },
});
});
test("should return the union when one range is completely within the other", () => {
rangeB = {
start: { line: 2, character: 1 },
end: { line: 2, character: 4 },
};
const result = union(rangeA, rangeB);
expect(result).toEqual(rangeA);
});
test("should return the union when ranges do not overlap and are not adjacent", () => {
rangeB = {
start: { line: 4, character: 3 },
end: { line: 5, character: 1 },
};
const result = union(rangeA, rangeB);
expect(result).toEqual({
start: { line: 1, character: 0 },
end: { line: 5, character: 1 },
});
});
// TODO
test.skip("should handle edge case where start and end lines are the same", () => {
rangeA = {
start: { line: 1, character: 0 },
end: { line: 1, character: 5 },
};
rangeB = {
start: { line: 1, character: 3 },
end: { line: 1, character: 7 },
};
const result = union(rangeA, rangeB);
expect(result).toEqual({
start: { line: 1, character: 0 },
end: { line: 1, character: 7 },
});
});
});

65
core/util/fetchFavicon.ts Normal file
View file

@ -0,0 +1,65 @@
import { JSDOM } from "jsdom";
export async function findFaviconPath(url: URL): Promise<string | undefined> {
const baseUrl = `${url.protocol}//${url.hostname}`;
try {
const response = await fetch(baseUrl);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const html = await response.text();
const dom = new JSDOM(html);
const document = dom.window.document;
// Look for favicon in <link> tags
const linkTags = document.querySelectorAll('link[rel*="icon"]');
for (const link of linkTags) {
const href = link.getAttribute("href");
if (href) {
return new URL(href, baseUrl).toString();
}
}
} catch (error) {
console.debug(`Failed to fetch favicon for ${baseUrl}: ${error}`);
}
console.debug(`Failed to find favicon for ${baseUrl}`);
return undefined;
}
export async function getFaviconBase64(
faviconUrl: string,
): Promise<string | undefined> {
try {
const response = await fetch(faviconUrl);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const arrayBuffer = await response.arrayBuffer();
const base64 = btoa(
new Uint8Array(arrayBuffer).reduce(
(data, byte) => data + String.fromCharCode(byte),
"",
),
);
const mimeType = response.headers.get("content-type") || "image/x-icon";
return `data:${mimeType};base64,${base64}`;
} catch (error) {
console.debug(`Failed to fetch favicon from ${faviconUrl}: ${error}`);
return undefined;
}
}
export async function fetchFavicon(url: URL): Promise<string | undefined> {
const faviconPath = await findFaviconPath(url);
if (faviconPath) {
return getFaviconBase64(faviconPath);
}
return undefined;
}

View file

@ -237,7 +237,7 @@ class FileSystemIde implements IDE {
return Promise.resolve([]);
}
async subprocess(command: string): Promise<[string, string]> {
async subprocess(command: string, cwd?: string): Promise<[string, string]> {
return ["", ""];
}
}

View file

@ -193,8 +193,8 @@ export class MessageIde implements IDE {
return this.request("getProblems", { filepath });
}
subprocess(command: string): Promise<[string, string]> {
return this.request("subprocess", { command });
subprocess(command: string, cwd?: string): Promise<[string, string]> {
return this.request("subprocess", { command, cwd });
}
async getBranch(dir: string): Promise<string> {

View file

@ -20,6 +20,7 @@ export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = {
recentLinePrefixMatchMinLength: 7,
disableInFiles: undefined,
useImports: true,
useRootPathContext: false,
};
export const COUNT_COMPLETION_REJECTED_AFTER = 10_000;

View file

@ -182,7 +182,7 @@ export class ReverseMessageIde {
});
this.on("subprocess", (data) => {
return this.ide.subprocess(data.command);
return this.ide.subprocess(data.command, data.cwd);
});
this.on("getBranch", (data) => {

View file

@ -129,6 +129,11 @@ export async function getLanguageForFile(
export enum TSQueryType {
CodeSnippets = "code-snippet-queries",
Imports = "import-queries",
// Used in RootPathContextService.ts
FunctionDeclaration = "root-path-context-queries/function_declaration",
MethodDefinition = "root-path-context-queries/method_definition",
FunctionDefinition = "root-path-context-queries/function_definition",
MethodDeclaration = "root-path-context-queries/method_declaration",
}
export async function getQueryForFile(

View file

@ -320,7 +320,7 @@ export class NoBadWordsLogitsProcessor extends LogitsProcessor {
* @property {number} [eta_cutoff=0.0] Eta sampling is a hybrid of locally typical sampling and epsilon sampling. If set to float strictly between 0 and 1, a token is only considered if it is greater than either `eta_cutoff` or `sqrt(eta_cutoff) * exp(-entropy(softmax(next_token_logits)))`. The latter term is intuitively the expected next token probability, scaled by `sqrt(eta_cutoff)`. In the paper, suggested values range from 3e-4 to 2e-3, depending on the size of the model. See [Truncation Sampling as Language Model Desmoothing](https://arxiv.org/abs/2210.15191) for more details.
* @property {number} [diversity_penalty=0.0] This value is subtracted from a beam's score if it generates a token same as any beam from other group at a particular time. Note that `diversity_penalty` is only effective if `group beam search` is enabled.
* @property {number} [repetition_penalty=1.0] The parameter for repetition penalty. 1.0 means no penalty. See [this paper](https://arxiv.org/pdf/1909.05858.pdf) for more details.
* @property {number} [encoder_repetition_penalty=1.0] The paramater for encoder_repetition_penalty. An exponential penalty on sequences that are not in the original input. 1.0 means no penalty.
* @property {number} [encoder_repetition_penalty=1.0] The parameter for encoder_repetition_penalty. An exponential penalty on sequences that are not in the original input. 1.0 means no penalty.
* @property {number} [length_penalty=1.0] Exponential penalty to the length that is used with beam-based generation. It is applied as an exponent to the sequence length, which in turn is used to divide the score of the sequence. Since the score is the log likelihood of the sequence (i.e. negative), `length_penalty` > 0.0 promotes longer sequences, while `length_penalty` < 0.0 encourages shorter sequences.
* @property {number} [no_repeat_ngram_size=0] If set to int > 0, all ngrams of that size can only occur once.
* @property {number[][]} [bad_words_ids=null] List of token ids that are not allowed to be generated. In order to get the token ids of the words that should not appear in the generated text, use `(await tokenizer(bad_words, {add_prefix_space: true, add_special_tokens: false})).input_ids`.
@ -488,7 +488,7 @@ export type GenerationConfigType = {
*/
repetition_penalty?: number;
/**
* The paramater for encoder_repetition_penalty. An exponential penalty on sequences that are not in the original input. 1.0 means no penalty.
* The parameter for encoder_repetition_penalty. An exponential penalty on sequences that are not in the original input. 1.0 means no penalty.
*/
encoder_repetition_penalty?: number;
/**
@ -590,4 +590,4 @@ export type GenerationConfigType = {
};
import { Tensor } from './tensor.js';
export {};
//# sourceMappingURL=generation.d.ts.map
//# sourceMappingURL=generation.d.ts.map

View file

@ -28,7 +28,7 @@ If there is information from the codebase, documentation, IDE, or other tools th
## Apply generated code to your file
When the LLM replies with code, you can hover over the top right of the code block and select “Apply to current file” to update the existing code in the editor to this new version.
When the LLM replies with edits to a file, you can click the “Apply” button. This will update the existing code in the editor to reflect the suggested changes.
## Start a fresh session for a new task

View file

@ -6,7 +6,7 @@ keywords: [context, "@", provider, LLM]
Context Providers allow you to type '@' and see a dropdown of content that can all be fed to the LLM as context. Every context provider is a plugin, which means if you want to reference some source of information that you don't see here, you can request (or build!) a new context provider.
As an example, say you are working on solving a new GitHub Issue. You type '@Isse' and select the one you are working on. Continue can now see the issue title and contents. You also know that the issue is related to the files 'readme.md' and 'helloNested.py', so you type '@readme' and '@hello' to find and select them. Now these 3 "Context Items" are displayed inline with the rest of your input.
As an example, say you are working on solving a new GitHub Issue. You type '@Issue' and select the one you are working on. Continue can now see the issue title and contents. You also know that the issue is related to the files 'readme.md' and 'helloNested.py', so you type '@readme' and '@hello' to find and select them. Now these 3 "Context Items" are displayed inline with the rest of your input.
![Context Items](/img/context-provider-example.png)
@ -58,7 +58,7 @@ Reference all of the changes you've made to your current branch. This is useful
### `@Terminal`
Reference the contents of your IDE's terminal.
Reference the last command you ran in your IDE's terminal and its output.
```json title="config.json"
{
@ -200,7 +200,7 @@ For example, type "@Google python tutorial" if you want to search and discuss wa
Note: You can get an API key for free at [serper.dev](https://serper.dev).
### `@Isse`
### `@Issue`
Reference the conversation in a GitHub issue.
@ -410,7 +410,13 @@ Reference table schemas from Sqlite, Postgres, and MySQL databases.
}
```
Each connection should include a unique name, the connection_type (e.g., postgres, sqlite), and the necessary connection parameters specific to each database type.
Each connection should include a unique name, the `connection_type`, and the necessary connection parameters specific to each database type.
Available connection types:
- `postgres`
- `mysql`
- `sqlite`
### `@Locals`
@ -465,6 +471,51 @@ Reference the architecture and platform of your current operating system.
}
```
### `@HTTP`
The HttpContextProvider makes a POST request to the url passed in the configuration. The server must return 200 OK with a ContextItem object or an array of ContextItems.
```json title="config.json"
{
"contextProviders": [
{
"name": "http",
"params": {
"url": "https://api.example.com/v1/users"
}
}
]
}
```
The receiving URL should expect to receive the following parameters:
```json title="POST parameters"
{
query: string,
fullInput: string
}
```
The response 200 OK should be a JSON object with the following structure:
```json title="Response"
[
{
"name": "",
"description": "",
"content": ""
}
]
// OR
{
"name": "",
"description": "",
"content": ""
}
```
### Requesting Context Providers
Not seeing what you want? Create an issue [here](https://github.com/continuedev/continue/issues/new?assignees=TyDunn&labels=enhancement&projects=&template=feature-request-%F0%9F%92%AA.md&title=) to request a new Context Provider.

View file

@ -73,4 +73,4 @@ If you need to force a refresh of the index, reload the VS Code window with `cmd
## Repository map
Models in the Claude 3, Llama 3.1, Gemini 1.5, and GPT-4o families will automatically use a [repository map](../context-providers.md#repository-map) during codebsae retrieval, which allows the model to understand the structure of your codebase and use it to answer questions. Currently, the repository map only contains the filepaths in the codebase.
Models in the Claude 3, Llama 3.1, Gemini 1.5, and GPT-4o families will automatically use a [repository map](../context-providers.md#repository-map) during codebase retrieval, which allows the model to understand the structure of your codebase and use it to answer questions. Currently, the repository map only contains the filepaths in the codebase.

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