Merge pull request #2483 from continuedev/nate/merge-test

Nate/merge test
This commit is contained in:
Nate Sesti 2024-10-06 14:07:23 -07:00 • committed by GitHub
commit df2128cdaa
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
333 changed files with 12308 additions and 18607 deletions

View file

@ -0,0 +1,7 @@
## 0.0.69 - 2024-09-22
### Added
* Support for the "search" context provider
### Fixed
* Fixed bug where only first module would be recognized
* Improved concurrency handling to avoid freezes
* Made compatible with latest JetBrains versions

View file

@ -0,0 +1,15 @@
## 0.9.210 - 2024-09-15
### Added
- NVIDIA NIMs embeddings provider
- SambaNova LLM Provider
- Support for OpenAI's new o1-preview and o1-mini models
### Changed
- Use Chromium only as a fallback after asking user
### Fixed
- Increased default maxTokens, and autodetect for common models

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/intellij
kind: Changed
body: Updated tutorial file
time: 2024-09-23T16:02:51.918152-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: Continue for teams auth bug fix
time: 2024-09-19T21:11:12.997946-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/intellij
kind: Fixed
body: Fix ability to load config.ts in JetBrains IDEs
time: 2024-09-29T09:54:40.284968-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

@ -23,16 +23,15 @@ body:
description: |
Feel free to omit any info that is not relevant to your issue.
- **OS**: e.g. macOS 14.2.1
- **Continue**: e.g. v0.9.4
- **IDE**: e.g. VSCode 1.85.1
- Include also your LLM Model if it is relevant to your issue
- **Model**: e.g. Ollama v0.1.19
- The contents of your config.json file (e.g. `~/.continue/config.json` on macOS)
- **OS**: macOS
- **Continue version**: v0.9.4
- **IDE version**: VSCode 1.85.1
- Model: Claude Sonnet 3.5
- config.json: `{ "models": ... }`
value: |
- OS:
- Continue:
- IDE:
- Continue version:
- IDE version:
- Model:
- config.json:
```json

View file

@ -203,6 +203,7 @@ jobs:
ls
echo "---"
FILENAME=`ls continue-intellij-extension-*.zip`
echo "Filename=${FILENAME}"
unzip "$FILENAME" -d content
echo "filename=${FILENAME%.????}" >> $GITHUB_OUTPUT
@ -330,10 +331,10 @@ jobs:
- name: Upload logs
if: ${{ always() }}
uses: actions/upload-artifact@v2
uses: actions/upload-artifact@v4
with:
name: core-logs-${{ matrix.platform }}-${{ matrix.arch }}
path: binary/.continue/logs/core.log
path: ~/.continue/logs/core.log
# Run tests and upload a code coverage report
test:

2
.gitignore vendored
View file

@ -169,4 +169,4 @@ Icon?
.prompts/
.aider*
notes.md
notes.md

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")

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
@ -211,9 +217,9 @@ Continue has support for more than a dozen different LLM "providers", making it
- At least one of `_streamComplete` or `_streamChat` - This is the function that makes the request to the API and returns the streamed response. You only need to implement one because Continue can automatically convert between "chat" and "raw completion".
2. Add your provider to the `LLMs` array in [core/llm/llms/index.ts](./core/llm/llms/index.ts).
3. If your provider supports images, add it to the `PROVIDER_SUPPORTS_IMAGES` array in [core/llm/index.ts](./core/llm/index.ts).
3. If your provider supports images, add it to the `PROVIDER_SUPPORTS_IMAGES` array in [core/llm/autodetect.ts](./core/llm/autodetect.ts).
4. Add the necessary JSON Schema types to [`config_schema.json`](./extensions/vscode/config_schema.json). This makes sure that Intellisense shows users what options are available for your provider when they are editing `config.json`.
5. Add a documentation page for your provider in [`docs/docs/reference/Model Providers`](./docs/docs/reference/Model%20Providers). This should show an example of configuring your provider in `config.json` and explain what options are available.
5. Add a documentation page for your provider in [`docs/docs/customize/model-providers`](./docs/docs/customize/model-providers). This should show an example of configuring your provider in `config.json` and explain what options are available.
### Adding Models

View file

@ -48,7 +48,7 @@
"@aws-sdk/client-sagemaker-runtime": "^3.621.0",
"@aws-sdk/credential-providers": "^3.620.1",
"@continuedev/config-types": "^1.0.10",
"@continuedev/llm-info": "^1.0.1",
"@continuedev/llm-info": "^1.0.2",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.0.2",
"@typescript-eslint/eslint-plugin": "^7.8.0",
@ -60,7 +60,8 @@
"cheerio": "^1.0.0-rc.12",
"commander": "^12.0.0",
"comment-json": "^4.2.3",
"dbinfoz": "^0.1.4",
"dbinfoz": "^0.11.0",
"diff": "^7.0.0",
"dotenv": "^16.4.5",
"fastest-levenshtein": "^1.0.16",
"follow-redirects": "^1.15.5",
@ -104,6 +105,7 @@
"@babel/preset-env": "^7.24.7",
"@biomejs/biome": "1.6.4",
"@google/generative-ai": "^0.11.4",
"@types/diff": "^5.2.2",
"@types/follow-redirects": "^1.14.4",
"@types/jest": "^29.5.12",
"@types/jquery": "^3.5.29",

View file

@ -5,7 +5,11 @@ import FileSystemIde from "core/util/filesystem";
import { IMessenger } from "core/util/messenger";
import { ReverseMessageIde } from "core/util/reverseMessageIde";
import fs from "fs";
import { ChildProcessWithoutNullStreams, spawn } from "node:child_process";
import {
ChildProcessWithoutNullStreams,
execSync,
spawn,
} from "node:child_process";
import path from "path";
import {
CoreBinaryMessenger,
@ -59,21 +63,66 @@ describe("Test Suite", () => {
beforeAll(async () => {
const [platform, arch] = autodetectPlatformAndArch();
const binaryPath = path.join(
__dirname,
"..",
"bin",
`${platform}-${arch}`,
`continue-binary${platform === "win32" ? ".exe" : ""}`,
);
expect(fs.existsSync(binaryPath)).toBe(true);
const binaryDir = path.join(__dirname, "..", "bin", `${platform}-${arch}`);
const exe = platform === "win32" ? ".exe" : "";
const binaryPath = path.join(binaryDir, `continue-binary${exe}`);
const expectedItems = [
`continue-binary${exe}`,
`esbuild${exe}`,
"index.node",
"package.json",
"build/Release/node_sqlite3.node",
];
expectedItems.forEach((item) => {
expect(fs.existsSync(path.join(binaryDir, item))).toBe(true);
});
// Set execute permissions and remove quarantine attribute if on macOS
if (platform !== "win32") {
try {
fs.chmodSync(binaryPath, 0o755);
console.log("Execute permissions set for the binary");
if (platform === "darwin") {
const indexNodePath = path.join(binaryDir, "index.node");
const filesToUnquarantine = [binaryPath, indexNodePath];
for (const file of filesToUnquarantine) {
try {
execSync(`xattr -d com.apple.quarantine "${file}"`, {
stdio: "ignore",
});
console.log(
`Quarantine attribute removed from ${path.basename(file)}`,
);
} catch (error) {
console.warn(
`Failed to remove quarantine attribute from ${path.basename(file)}:`,
error,
);
}
}
}
} catch (error) {
console.error(
"Error setting permissions or removing quarantine:",
error,
);
}
}
if (USE_TCP) {
messenger = new CoreBinaryTcpMessenger<ToIdeProtocol, FromIdeProtocol>();
} else {
subprocess = spawn(binaryPath, {
env: { ...process.env, CONTINUE_GLOBAL_DIR },
});
try {
subprocess = spawn(binaryPath, {
env: { ...process.env, CONTINUE_GLOBAL_DIR },
});
console.log("Successfully spawned subprocess");
} catch (error) {
console.error("Error spawning subprocess:", error);
throw error;
}
messenger = new CoreBinaryMessenger<ToIdeProtocol, FromIdeProtocol>(
subprocess,
);
@ -123,13 +172,17 @@ describe("Test Suite", () => {
"package.json",
"logs/core.log",
"index/autocompleteCache.sqlite",
"out/config.js",
"types/core/index.d.ts",
];
for (const file of expectedFiles) {
const missingFiles = expectedFiles.filter((file) => {
const filePath = path.join(CONTINUE_GLOBAL_DIR, file);
expect(fs.existsSync(filePath)).toBe(true);
return !fs.existsSync(filePath);
});
expect(missingFiles).toEqual([]);
if (missingFiles.length > 0) {
console.log("Missing files:", missingFiles);
}
});

View file

@ -25,7 +25,7 @@ You can also set up tab-autocomplete with a local LM Studio instance by followin
Example:
```json title=~/.continue/config.json
```json title="config.json"
{
"tabAutocompleteModel": {
"title": "Starcoder2 3b",
@ -40,7 +40,7 @@ Example:
All of the configuration options available for chat models are available to use for tab-autocomplete. For example, if you wanted to use a remote vLLM instance you would edit your `config.json` like this (note that it is not inside the models array), filling in the correct model name and vLLM endpoint:
```json title=~/.continue/config.json
```json title="config.json"
{
"tabAutocompleteModel": {
"title": "Tab Autocomplete Model",
@ -54,7 +54,7 @@ All of the configuration options available for chat models are available to use
As another example, say you want to use a different model, `deepseek-coder:6.7b-base`, with Ollama:
```json title=~/.continue/config.json
```json title="config.json"
{
"tabAutocompleteModel": {
"title": "Tab Autocomplete Model",
@ -100,7 +100,7 @@ This object allows you to customize the behavior of tab-autocomplete. The availa
### Full example
```json title=~/.continue/config.json
```json title="config.json"
{
"tabAutocompleteModel": {
"title": "Tab Autocomplete Model",

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 { LineStream } from "../diff/util";
import { DiffLine } from "../";
import { DiffLine } from "../..";
import { LineStream } from "../../diff/util";
export type LineFilter = (args: {
lines: LineStream;
@ -238,9 +238,10 @@ export async function* stopAtSimilarLine(
export async function* stopAtLines(
stream: LineStream,
fullStop: () => void,
linesToStopAt: string[] = LINES_TO_STOP_AT,
): LineStream {
for await (const line of stream) {
if (LINES_TO_STOP_AT.some((stopAt) => line.trim().includes(stopAt))) {
if (linesToStopAt.some((stopAt) => line.trim().includes(stopAt))) {
fullStop();
break;
}
@ -382,6 +383,17 @@ export async function* filterEnglishLinesAtEnd(lines: LineStream) {
}
}
export async function* filterLeadingNewline(lines: LineStream): LineStream {
let firstLine = true;
for await (const line of lines) {
if (firstLine && line.trim() === "") {
firstLine = false;
continue;
}
yield line;
}
}
/**
* Removes leading indentation from the first line of a CodeLlama output.
* @param {LineStream} lines - The input stream of lines.
@ -482,3 +494,19 @@ export async function* stopAtRepeatingLines(
previousLine = line;
}
}
/**
* Pass-through, except logs the total output at the end
* @param lines a `LineStream`
*/
export async function* logLines(
lines: LineStream,
prefix: string = "STREAMED LINES",
): LineStream {
let linesToLog = [];
for await (const line of lines) {
yield line;
linesToLog.push(line);
}
console.log(`${prefix}:\n${linesToLog.join("\n")}\n\n`);
}

View file

@ -41,6 +41,25 @@ const stableCodeFimTemplate: AutocompleteTemplate = {
},
};
// https://github.com/QwenLM/Qwen2.5-Coder?tab=readme-ov-file#3-file-level-code-completion-fill-in-the-middle
const qwenCoderFimTemplate: AutocompleteTemplate = {
template:
"<|fim_prefix|>{{{prefix}}}<|fim_suffix|>{{{suffix}}}<|fim_middle|>",
completionOptions: {
stop: [
"<|endoftext|>",
"<|fim_prefix|>",
"<|fim_middle|>",
"<|fim_suffix|>",
"<|fim_pad|>",
"<|repo_name|>",
"<|file_sep|>",
"<|im_start|>",
"<|im_end|>",
],
},
};
const codestralFimTemplate: AutocompleteTemplate = {
template: "[SUFFIX]{{{suffix}}}[PREFIX]{{{prefix}}}",
completionOptions: {
@ -318,6 +337,10 @@ export function getTemplateForModel(model: string): AutocompleteTemplate {
// return starcoder2FimTemplate;
// }
if (lowerCaseModel.includes("qwen") && lowerCaseModel.includes("coder")) {
return qwenCoderFimTemplate;
}
if (
lowerCaseModel.includes("starcoder") ||
lowerCaseModel.includes("star-coder") ||

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

@ -1,7 +1,12 @@
import { ContinueProxyReranker } from "../../context/rerankers/ContinueProxyReranker.js";
import { ControlPlaneClient } from "../../control-plane/client.js";
import { ControlPlaneProxyInfo } from "../../control-plane/analytics/IAnalyticsProvider.js";
import {
ControlPlaneClient,
DEFAULT_CONTROL_PLANE_PROXY_URL,
} from "../../control-plane/client.js";
import { TeamAnalytics } from "../../control-plane/TeamAnalytics.js";
import {
ContinueConfig,
ContinueRcJson,
IDE,
IdeSettings,
@ -33,7 +38,7 @@ export default async function doLoadConfig(
const ideSettings = await ideSettingsPromise;
const workOsAccessToken = await controlPlaneClient.getAccessToken();
const newConfig = await loadFullConfigNode(
let newConfig = await loadFullConfigNode(
ide,
workspaceConfigs,
ideSettings,
@ -56,34 +61,59 @@ export default async function doLoadConfig(
// TODO: pass config to pre-load non-system TTS models
await TTS.setup();
// Set up control plane proxy if configured
let controlPlaneProxyUrl: string =
(newConfig as any).controlPlane?.proxyUrl ??
DEFAULT_CONTROL_PLANE_PROXY_URL;
if (!controlPlaneProxyUrl.endsWith("/")) {
controlPlaneProxyUrl += "/";
}
const controlPlaneProxyInfo = {
workspaceId,
controlPlaneProxyUrl,
workOsAccessToken,
};
if (newConfig.analytics) {
await TeamAnalytics.setup(
newConfig.analytics as any, // TODO: Need to get rid of index.d.ts once and for all
uniqueId,
ideInfo.extensionVersion,
controlPlaneClient,
workspaceId,
controlPlaneProxyInfo,
);
}
[...newConfig.models, ...(newConfig.tabAutocompleteModels ?? [])].forEach(
newConfig = await injectControlPlaneProxyInfo(
newConfig,
controlPlaneProxyInfo,
);
return newConfig;
}
// Pass ControlPlaneProxyInfo to objects that need it
async function injectControlPlaneProxyInfo(
config: ContinueConfig,
info: ControlPlaneProxyInfo,
): Promise<ContinueConfig> {
[...config.models, ...(config.tabAutocompleteModels ?? [])].forEach(
async (model) => {
if (model.providerName === "continue-proxy") {
(model as ContinueProxy).workOsAccessToken = workOsAccessToken;
(model as ContinueProxy).controlPlaneProxyInfo = info;
}
},
);
if (newConfig.embeddingsProvider?.providerName === "continue-proxy") {
if (config.embeddingsProvider?.providerName === "continue-proxy") {
(
newConfig.embeddingsProvider as ContinueProxyEmbeddingsProvider
).workOsAccessToken = workOsAccessToken;
config.embeddingsProvider as ContinueProxyEmbeddingsProvider
).controlPlaneProxyInfo = info;
}
if (newConfig.reranker?.name === "continue-proxy") {
(newConfig.reranker as ContinueProxyReranker).workOsAccessToken =
workOsAccessToken;
if (config.reranker?.name === "continue-proxy") {
(config.reranker as ContinueProxyReranker).controlPlaneProxyInfo = info;
}
return newConfig;
return config;
}

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"
@ -647,6 +648,8 @@ declare global {
| "deepseek-7b"
| "deepseek-33b"
| "neural-chat-7b"
| "gemma-7b-it"
| "gemma2-9b-it"
// Anthropic
| "claude-3-5-sonnet-20240620"
| "claude-3-opus-20240229"
@ -685,6 +688,11 @@ declare global {
clientCertificate?: ClientCertificateOptions;
}
export interface CacheBehavior {
cacheSystemMessage?: boolean;
cacheConversation?: boolean;
}
export interface ClientCertificateOptions {
cert: string;
key: string;
@ -747,6 +755,7 @@ declare global {
requestOptions?: RequestOptions;
promptTemplates?: { [key: string]: string };
capabilities?: ModelCapability;
cacheBehavior?: CacheBehavior;
}
export type EmbeddingsProviderName =

View file

@ -1,4 +1,10 @@
import { ContextProviderWithParams, ModelDescription } from "../";
import {
ContextProviderWithParams,
ContinueConfig,
ILLM,
ModelDescription,
ModelRoles,
} from "../";
import { editConfigJson } from "../util/paths";
function stringify(obj: any, indentation?: number): string {
@ -23,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;
@ -33,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;
});
}
@ -61,3 +79,20 @@ export function deleteModel(title: string) {
return config;
});
}
export function getModelByRole<T extends keyof ModelRoles>(
config: ContinueConfig,
role: T,
): ILLM | undefined {
const roleTitle = config.experimental?.modelRoles?.[role];
if (!roleTitle) {
return undefined;
}
const matchingModel = config.models.find(
(model) => model.title === roleTitle,
);
return matchingModel;
}

View file

@ -2,9 +2,9 @@ import {
ContextItem,
ContextProviderDescription,
ContextProviderExtras,
} from "../../index.js";
import { BaseContextProvider } from "../index.js";
import { retrieveContextItemsFromEmbeddings } from "../retrieval/retrieval.js";
} from "../../";
import { BaseContextProvider } from "../";
import { retrieveContextItemsFromEmbeddings } from "../retrieval/retrieval";
class CodebaseContextProvider extends BaseContextProvider {
static description: ContextProviderDescription = {

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

@ -6,7 +6,7 @@ import {
LoadSubmenuItemsArgs,
} from "../../index.js";
import { BaseContextProvider } from "../index.js";
import getDatabaseAdapter from "dbinfoz";
import { getDatabaseAdapter } from "dbinfoz";
class DatabaseContextProvider extends BaseContextProvider {
static description: ContextProviderDescription = {

View file

@ -1,3 +1,4 @@
import { INSTRUCTIONS_BASE_ITEM } from "./utils";
import { BaseContextProvider } from "../";
import {
Chunk,
@ -90,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. " +
@ -104,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"],
});
}
@ -146,11 +147,14 @@ class DocsContextProvider extends BaseContextProvider {
: chunk.otherMetadata?.title || chunk.filepath,
description: chunk.filepath,
content: chunk.content,
uri: {
type: "url" as const,
value: chunk.filepath,
},
}))
.reverse(),
{
name: "Instructions",
description: "Instructions",
...INSTRUCTIONS_BASE_ITEM,
content:
"Use the above documentation to answer the following question. You should not reference " +
"anything outside of what is shown, unless it is a commonly known concept. Reference URLs " +

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

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

@ -39,14 +39,15 @@ class HttpContextProvider extends BaseContextProvider {
}),
});
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();
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)];
}
}

View file

@ -23,8 +23,10 @@ class OSContextProvider extends BaseContextProvider {
return [
{
description: "Your operating system and CPU",
content: `I am running ${platform} on ${cpu}.`,
name: "os",
content: `I am running ${
platform === "win32" ? "Windows" : platform
} on ${cpu}.`,
name: "Operating System",
},
];
}

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

@ -3,15 +3,28 @@ import {
ContextItem,
ContextProviderDescription,
ContextProviderExtras,
ContextSubmenuItem,
LoadSubmenuItemsArgs,
} from "../../";
import generateRepoMap from "../../util/repoMap";
import {
groupByLastNPathParts,
getBasename,
getUniqueFilePath,
} from "../../util";
import generateRepoMap from "../../util/generateRepoMap";
const ENTIRE_PROJECT_ITEM: ContextSubmenuItem = {
id: "entire-codebase",
title: "Entire codebase",
description: "Search the entire codebase",
};
class RepoMapContextProvider extends BaseContextProvider {
static description: ContextProviderDescription = {
title: "repo-map",
displayTitle: "Repository Map",
description: "List of files and signatures",
type: "normal",
description: "Select a folder",
type: "submenu",
dependsOnIndexing: true,
};
@ -23,10 +36,28 @@ class RepoMapContextProvider extends BaseContextProvider {
{
name: "Repository Map",
description: "Overview of the repository structure",
content: await generateRepoMap(extras.llm, extras.ide),
content: await generateRepoMap(extras.llm, extras.ide, {
dirs: query === ENTIRE_PROJECT_ITEM.id ? undefined : [query],
}),
},
];
}
async loadSubmenuItems(
args: LoadSubmenuItemsArgs,
): Promise<ContextSubmenuItem[]> {
const folders = await args.ide.listFolders();
const folderGroups = groupByLastNPathParts(folders, 2);
return [
ENTIRE_PROJECT_ITEM,
...folders.map((folder) => ({
id: folder,
title: getBasename(folder),
description: getUniqueFilePath(folder, folderGroups),
})),
];
}
}
export default RepoMapContextProvider;

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

@ -1,4 +1,4 @@
import { ContextProviderName } from "../../";
import { ContextItem, ContextProviderName } from "../../";
import { BaseContextProvider } from "../";
import CodeContextProvider from "./CodeContextProvider";
import ContinueProxyContextProvider from "./ContinueProxyContextProvider";
@ -22,6 +22,7 @@ import SearchContextProvider from "./SearchContextProvider";
import TerminalContextProvider from "./TerminalContextProvider";
import URLContextProvider from "./URLContextProvider";
import RepoMapContextProvider from "./RepoMapContextProvider";
import GreptileContextProvider from "./GreptileContextProvider";
/**
* Note: We are currently omitting the following providers due to bugs:
@ -30,7 +31,7 @@ import RepoMapContextProvider from "./RepoMapContextProvider";
*
* See this issue for details: https://github.com/continuedev/continue/issues/1365
*/
const Providers: (typeof BaseContextProvider)[] = [
export const Providers: (typeof BaseContextProvider)[] = [
DiffContextProvider,
FileTreeContextProvider,
GitHubIssuesContextProvider,
@ -53,6 +54,7 @@ const Providers: (typeof BaseContextProvider)[] = [
URLContextProvider,
ContinueProxyContextProvider,
RepoMapContextProvider,
GreptileContextProvider,
];
export function contextProviderClassFromName(

View file

@ -0,0 +1,7 @@
import { ContextItem } from "../..";
export const INSTRUCTIONS_BASE_ITEM: ContextItem = {
name: "Instructions",
description: "Instructions",
content: "",
};

View file

@ -1,21 +1,15 @@
import fetch from "node-fetch";
import { CONTROL_PLANE_URL } from "../../control-plane/client.js";
import { ControlPlaneProxyInfo } from "../../control-plane/analytics/IAnalyticsProvider.js";
import { Chunk, Reranker } from "../../index.js";
export class ContinueProxyReranker implements Reranker {
name = "continue-proxy";
private _workOsAccessToken: string | undefined = undefined;
private _controlPlaneProxyInfo?: ControlPlaneProxyInfo;
get workOsAccessToken(): string | undefined {
return this._workOsAccessToken;
}
set workOsAccessToken(value: string | undefined) {
if (this._workOsAccessToken !== value) {
this._workOsAccessToken = value;
this.params.apiKey = value!;
}
set controlPlaneProxyInfo(value: ControlPlaneProxyInfo) {
this.params.apiKey = value.workOsAccessToken!;
this._controlPlaneProxyInfo = value;
}
constructor(
@ -26,7 +20,10 @@ export class ContinueProxyReranker implements Reranker {
) {}
async rerank(query: string, chunks: Chunk[]): Promise<number[]> {
const url = new URL("/model-proxy/v1/rerank", CONTROL_PLANE_URL);
const url = new URL(
"openai/v1/rerank",
this._controlPlaneProxyInfo?.controlPlaneProxyUrl,
);
const resp = await fetch(url, {
method: "POST",
headers: {

View file

@ -1,6 +1,33 @@
import { Chunk, ContinueConfig, IDE, ILLM } from "../..";
import { getModelByRole } from "../../config/util";
import { stripImages } from "../../llm/images";
import generateRepoMap from "../../util/repoMap";
import generateRepoMap from "../../util/generateRepoMap";
const SUPPORTED_MODEL_TITLE_FAMILIES = [
"claude-3",
"llama3.1",
"gemini-1.5",
"gpt-4",
];
function isSupportedModel(
config: ContinueConfig,
modelTitle?: string,
): boolean {
if (config.experimental?.modelRoles?.applyCodeBlock) {
return true;
}
if (!modelTitle) {
return false;
}
const lowercaseModelTitle = modelTitle.toLowerCase();
return SUPPORTED_MODEL_TITLE_FAMILIES.some((title) =>
lowercaseModelTitle.includes(title),
);
}
export async function requestFilesFromRepoMap(
defaultLlm: ILLM,
@ -9,20 +36,16 @@ export async function requestFilesFromRepoMap(
input: string,
filterDirectory?: string,
): Promise<Chunk[]> {
const llm =
config.models.find(
(model) =>
model.title === config.experimental?.modelRoles?.repoMapFileSelection,
) ?? defaultLlm;
const llm = getModelByRole(config, "repoMapFileSelection") ?? defaultLlm;
// Only supported for Claude models right now
if (!llm.model.toLowerCase().includes("claude")) {
if (!isSupportedModel(config, llm.title)) {
return [];
}
try {
const repoMap = await generateRepoMap(llm, ide, {
signatures: false,
includeSignatures: false,
dirs: filterDirectory ? [filterDirectory] : undefined,
});

View file

@ -1,14 +1,12 @@
import {
BranchAndDir,
ContextItem,
ContextProviderExtras,
} from "../../index.js";
import TransformersJsEmbeddingsProvider from "../../indexing/embeddings/TransformersJsEmbeddingsProvider.js";
import { resolveRelativePathInWorkspace } from "../../util/ideUtils.js";
import { getRelativePath } from "../../util/index.js";
import { RetrievalPipelineOptions } from "./pipelines/BaseRetrievalPipeline.js";
import NoRerankerRetrievalPipeline from "./pipelines/NoRerankerRetrievalPipeline.js";
import RerankerRetrievalPipeline from "./pipelines/RerankerRetrievalPipeline.js";
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";
import path from "path";
export async function retrieveContextItemsFromEmbeddings(
extras: ContextProviderExtras,
@ -97,22 +95,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\`\`\``,
};
}),
{
name: "Instructions",
description: "Instructions",
...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

@ -1,7 +1,10 @@
import { Analytics } from "@continuedev/config-types";
import os from "node:os";
import ContinueProxyAnalyticsProvider from "./analytics/ContinueProxyAnalyticsProvider.js";
import { IAnalyticsProvider } from "./analytics/IAnalyticsProvider.js";
import {
ControlPlaneProxyInfo,
IAnalyticsProvider,
} from "./analytics/IAnalyticsProvider.js";
import LogStashAnalyticsProvider from "./analytics/LogStashAnalyticsProvider.js";
import PostHogAnalyticsProvider from "./analytics/PostHogAnalyticsProvider.js";
import { ControlPlaneClient } from "./client.js";
@ -41,7 +44,7 @@ export class TeamAnalytics {
uniqueId: string,
extensionVersion: string,
controlPlaneClient: ControlPlaneClient,
workspaceId?: string,
controlPlaneProxyInfo: ControlPlaneProxyInfo,
) {
TeamAnalytics.uniqueId = uniqueId;
TeamAnalytics.os = os.platform();
@ -52,7 +55,11 @@ export class TeamAnalytics {
TeamAnalytics.provider = undefined;
} else {
TeamAnalytics.provider = createAnalyticsProvider(config);
await TeamAnalytics.provider?.setup(config, uniqueId, workspaceId);
await TeamAnalytics.provider?.setup(
config,
uniqueId,
controlPlaneProxyInfo,
);
if (config.provider === "continue-proxy") {
(

View file

@ -1,13 +1,16 @@
import { Analytics } from "@continuedev/config-types";
import fetch from "node-fetch";
import { CONTROL_PLANE_URL, ControlPlaneClient } from "../client.js";
import { IAnalyticsProvider } from "./IAnalyticsProvider.js";
import { ControlPlaneClient } from "../client.js";
import {
ControlPlaneProxyInfo,
IAnalyticsProvider,
} from "./IAnalyticsProvider.js";
export default class ContinueProxyAnalyticsProvider
implements IAnalyticsProvider
{
uniqueId?: string;
workspaceId?: string;
controlPlaneProxyInfo?: ControlPlaneProxyInfo;
controlPlaneClient?: ControlPlaneClient;
@ -16,8 +19,8 @@ export default class ContinueProxyAnalyticsProvider
properties: { [key: string]: any },
): Promise<void> {
const url = new URL(
`proxy/analytics/${this.workspaceId}/capture`,
CONTROL_PLANE_URL,
`proxy/analytics/${this.controlPlaneProxyInfo?.workspaceId}/capture`,
this.controlPlaneProxyInfo?.controlPlaneProxyUrl,
).toString();
fetch(url, {
method: "POST",
@ -35,10 +38,10 @@ export default class ContinueProxyAnalyticsProvider
async setup(
config: Analytics,
uniqueId: string,
workspaceId?: string,
controlPlaneProxyInfo?: ControlPlaneProxyInfo,
): Promise<void> {
this.uniqueId = uniqueId;
this.workspaceId = workspaceId;
this.controlPlaneProxyInfo = controlPlaneProxyInfo;
}
async shutdown(): Promise<void> {}

View file

@ -4,12 +4,18 @@ export interface AnalyticsMetadata {
extensionVersion: string;
}
export interface ControlPlaneProxyInfo {
workspaceId?: string;
controlPlaneProxyUrl: string;
workOsAccessToken?: string;
}
export interface IAnalyticsProvider {
capture(event: string, properties: { [key: string]: any }): Promise<void>;
setup(
config: Analytics,
uniqueId: string,
workspaceId?: string,
controlPlaneProxyInfo?: ControlPlaneProxyInfo,
): Promise<void>;
shutdown(): Promise<void>;
}

View file

@ -1,6 +1,9 @@
import { Analytics } from "@continuedev/config-types";
import net from "node:net";
import { IAnalyticsProvider } from "./IAnalyticsProvider.js";
import {
ControlPlaneProxyInfo,
IAnalyticsProvider,
} from "./IAnalyticsProvider.js";
export default class LogStashAnalyticsProvider implements IAnalyticsProvider {
private host?: string;
@ -31,7 +34,7 @@ export default class LogStashAnalyticsProvider implements IAnalyticsProvider {
async setup(
config: Analytics,
uniqueId: string,
workspaceId?: string,
controlPlaneProxyInfo?: ControlPlaneProxyInfo,
): Promise<void> {
if (!config.url) {
console.warn("LogStashAnalyticsProvider is missing a URL");

View file

@ -1,5 +1,8 @@
import { Analytics } from "@continuedev/config-types";
import { IAnalyticsProvider } from "./IAnalyticsProvider.js";
import {
ControlPlaneProxyInfo,
IAnalyticsProvider,
} from "./IAnalyticsProvider.js";
export default class PostHogAnalyticsProvider implements IAnalyticsProvider {
client?: any;
@ -19,7 +22,7 @@ export default class PostHogAnalyticsProvider implements IAnalyticsProvider {
async setup(
config: Analytics,
uniqueId: string,
workspaceId?: string,
controlPlaneProxyInfo?: ControlPlaneProxyInfo,
): Promise<void> {
if (!config || !config.clientKey || !config.url) {
this.client = undefined;

View file

@ -18,6 +18,11 @@ export interface ControlPlaneWorkspace {
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/";
export const CONTROL_PLANE_URL =
process.env.CONTROL_PLANE_ENV === "local"
? "http://localhost:3001/"

View file

@ -14,6 +14,7 @@ import { recentlyEditedFilesCache } from "./context/retrieval/recentlyEditedFile
import { ContinueServerClient } from "./continueServer/stubs/client";
import { getAuthUrlForTokenPage } from "./control-plane/auth/index";
import { ControlPlaneClient } from "./control-plane/client";
import { streamDiffLines } from "./edit/streamDiffLines";
import { CodebaseIndexer, PauseToken } from "./indexing/CodebaseIndexer";
import DocsService from "./indexing/docs/DocsService";
import Ollama from "./llm/llms/Ollama";
@ -27,7 +28,6 @@ import type { IMessenger, Message } from "./util/messenger";
import { editConfigJson } from "./util/paths";
import { Telemetry } from "./util/posthog";
import { TTS } from "./util/tts";
import { streamDiffLines } from "./util/verticalEdit";
export class Core {
// implements IMessenger<ToCoreProtocol, FromCoreProtocol>
@ -119,7 +119,7 @@ export class Core {
(resolve) => (continueServerClientResolve = resolve),
);
ideSettingsPromise.then((ideSettings) => {
void ideSettingsPromise.then((ideSettings) => {
const continueServerClient = new ContinueServerClient(
ideSettings.remoteConfigServerUrl,
ideSettings.userToken,
@ -136,18 +136,18 @@ export class Core {
);
// Index on initialization
this.ide.getWorkspaceDirs().then(async (dirs) => {
void this.ide.getWorkspaceDirs().then(async (dirs) => {
// Respect pauseCodebaseIndexOnStart user settings
if (ideSettings.pauseCodebaseIndexOnStart) {
await this.messenger.request("indexProgress", {
progress: 100,
progress: 1,
desc: "Initial Indexing Skipped",
status: "paused",
});
return;
}
this.refreshCodebaseIndex(dirs);
void this.refreshCodebaseIndex(dirs);
});
});
@ -172,11 +172,11 @@ export class Core {
this.messenger.onError((err) => {
console.error(err);
Telemetry.capture("core_messenger_error", {
void Telemetry.capture("core_messenger_error", {
message: err.message,
stack: err.stack,
});
this.ide.showToast("error", err.message);
void this.ide.showToast("error", err.message);
});
// New
@ -186,7 +186,7 @@ export class Core {
on("update/selectTabAutocompleteModel", async (msg) => {
this.globalContext.update("selectedTabAutocompleteModel", msg.data);
this.configHandler.reloadConfig();
void this.configHandler.reloadConfig();
});
// Special
@ -226,30 +226,30 @@ export class Core {
// Edit config
on("config/addModel", (msg) => {
const model = msg.data.model;
addModel(model);
this.configHandler.reloadConfig();
addModel(model, msg.data.role);
void this.configHandler.reloadConfig();
});
on("config/addOpenAiKey", (msg) => {
addOpenAIKey(msg.data);
this.configHandler.reloadConfig();
void this.configHandler.reloadConfig();
});
on("config/deleteModel", (msg) => {
deleteModel(msg.data.title);
this.configHandler.reloadConfig();
void this.configHandler.reloadConfig();
});
on("config/newPromptFile", async (msg) => {
createNewPromptFile(
void createNewPromptFile(
this.ide,
(await this.config()).experimental?.promptPath,
);
this.configHandler.reloadConfig();
void this.configHandler.reloadConfig();
});
on("config/reload", (msg) => {
this.configHandler.reloadConfig();
void this.configHandler.reloadConfig();
return this.configHandler.getSerializedConfig();
});
@ -272,9 +272,12 @@ export class Core {
}
if (hasFailed) {
this.ide.showToast("info", `Failed to index ${msg.data.startUrl}`);
void this.ide.showToast("info", `Failed to index ${msg.data.startUrl}`);
} else {
this.ide.showToast("info", `Successfully indexed ${msg.data.startUrl}`);
void this.ide.showToast(
"info",
`Successfully indexed ${msg.data.startUrl}`,
);
this.messenger.send("refreshSubmenuItems", undefined);
}
});
@ -331,7 +334,7 @@ export class Core {
fetchwithRequestOptions(url, init, config.requestOptions),
});
Telemetry.capture(
void Telemetry.capture(
"useContextProvider",
{
name: provider.description.title,
@ -344,7 +347,7 @@ export class Core {
id,
}));
} catch (e) {
this.ide.showToast(
void this.ide.showToast(
"error",
`Error getting context items from ${name}: ${e}`,
);
@ -368,7 +371,7 @@ export class Core {
// Stop TTS on new StreamChat
if (config.experimental?.readResponseTTS) {
TTS.kill();
void TTS.kill();
}
const model = await configHandler.llmFromTitle(msg.data.title);
@ -396,7 +399,7 @@ export class Core {
}
if (config.experimental?.readResponseTTS && "completion" in next.value) {
TTS.read(next.value?.completion);
void TTS.read(next.value?.completion);
}
return { done: true, content: next.value };
@ -477,7 +480,7 @@ export class Core {
TTS.messenger = this.messenger;
on("tts/kill", async () => {
TTS.kill();
void TTS.kill();
});
async function* runNodeJsSlashCommand(
@ -506,7 +509,7 @@ export class Core {
throw new Error(`Unknown slash command ${slashCommandName}`);
}
Telemetry.capture(
void Telemetry.capture(
"useSlashCommand",
{
name: slashCommandName,
@ -529,7 +532,7 @@ export class Core {
params,
ide,
addContextItem: (item) => {
messenger.request("addContextItem", {
void messenger.request("addContextItem", {
item,
historyIndex,
});
@ -568,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();
});
@ -636,7 +641,7 @@ export class Core {
editConfigJson(editConfigJsonCallback);
this.configHandler.reloadConfig();
void this.configHandler.reloadConfig();
});
on("addAutocompleteModel", (msg) => {
@ -646,7 +651,7 @@ export class Core {
tabAutocompleteModel: msg.data.model,
};
});
this.configHandler.reloadConfig();
void this.configHandler.reloadConfig();
});
on("stats/getTokensPerDay", async (msg) => {
@ -674,13 +679,13 @@ export class Core {
// Triggered when progress bar is initialized.
// If a non-default state has been stored, update the indexing display to that state
if (this.indexingState.status !== "loading") {
this.messenger.request("indexProgress", this.indexingState);
void this.messenger.request("indexProgress", this.indexingState);
}
});
on("didChangeSelectedProfile", (msg) => {
this.configHandler.setSelectedProfile(msg.data.id);
this.configHandler.reloadConfig();
void this.configHandler.setSelectedProfile(msg.data.id);
void this.configHandler.reloadConfig();
});
on("didChangeControlPlaneSessionInfo", async (msg) => {
this.configHandler.updateControlPlaneSessionInfo(msg.data.sessionInfo);
@ -713,7 +718,7 @@ export class Core {
updateToSend.progress = 1.0;
}
this.messenger.request("indexProgress", updateToSend);
void this.messenger.request("indexProgress", updateToSend);
this.indexingState = updateToSend;
if (update.status === "failed") {
@ -722,7 +727,7 @@ export class Core {
update.desc,
update.debugInfo,
);
Telemetry.capture(
void Telemetry.capture(
"indexing_error",
{
error: update.desc,

23
core/diff/myers.test.ts Normal file
View file

@ -0,0 +1,23 @@
import { dedent } from "../util";
import { myersDiff } from "./myers";
describe("Test myers diff function", () => {
test("should ...", () => {
const linesA = dedent`
A
B
C
D
E
`;
const linesB = dedent`
A
B
C'
D'
E
`;
const diffLines = myersDiff(linesA, linesB);
console.log(diffLines);
});
});

25
core/diff/myers.ts Normal file
View file

@ -0,0 +1,25 @@
import { diffLines, type Change } from "diff";
import { DiffLine } from "..";
export function convertMyersChangeToDiffLines(change: Change): DiffLine[] {
const type: DiffLine["type"] = change.added
? "new"
: change.removed
? "old"
: "same";
const lines = change.value.split("\n");
// `diff` package is always adding an extra new line at the end of the array
if (lines[lines.length - 1] === "") {
lines.pop();
}
return lines.map((line) => ({ type, line }));
}
export function myersDiff(oldContent: string, newContent: string): DiffLine[] {
const theirFormat = diffLines(oldContent, newContent);
const ourFormat = theirFormat.flatMap(convertMyersChangeToDiffLines);
return ourFormat;
}

View file

@ -4,6 +4,7 @@ import { DiffLine, DiffLineType } from "../index.js";
// @ts-ignore no typings available
import { changed, diff as myersDiff } from "myers-diff";
import path from "node:path";
import { generateLines } from "./util.js";
// "modification" is an extra type used to represent an "old" + "new" diff line
type MyersDiffTypes = Extract<DiffLineType, "new" | "old"> | "modification";
@ -14,12 +15,6 @@ const UNIFIED_DIFF_SYMBOLS = {
old: "-",
};
async function* generateLines(lines: string[]): AsyncGenerator<string> {
for (const line of lines) {
yield line;
}
}
async function collectDiffs(
oldLines: string[],
newLines: string[],
@ -224,18 +219,18 @@ describe("streamDiff(", () => {
});
test("tabs vs. spaces differences are ignored", async () => {
await expectDiff("fastapi-tabs-vs-spaces");
await expectDiff("fastapi-tabs-vs-spaces.py");
});
test("FastAPI example", async () => {
await expectDiff("fastapi");
await expectDiff("fastapi.py");
});
test("FastAPI comments", async () => {
await expectDiff("add-comments");
await expectDiff("add-comments.py");
});
test("Mock LLM example", async () => {
await expectDiff("mock-llm");
await expectDiff("mock-llm.ts");
});
});

View file

@ -93,19 +93,38 @@ export function matchLine(
*/
export async function* streamLines(
streamCompletion: AsyncGenerator<string | ChatMessage>,
log: boolean = false,
): LineStream {
let allLines = [];
let buffer = "";
for await (const update of streamCompletion) {
const chunk =
typeof update === "string" ? update : stripImages(update.content);
buffer += chunk;
const lines = buffer.split("\n");
buffer = lines.pop() ?? "";
for (const line of lines) {
yield line;
try {
for await (const update of streamCompletion) {
const chunk =
typeof update === "string" ? update : stripImages(update.content);
buffer += chunk;
const lines = buffer.split("\n");
buffer = lines.pop() ?? "";
for (const line of lines) {
yield line;
allLines.push(line);
}
}
if (buffer.length > 0) {
yield buffer;
allLines.push(buffer);
}
} finally {
if (log) {
console.log("Streamed lines: ", allLines.join("\n"));
}
}
if (buffer.length > 0) {
yield buffer;
}
export async function* generateLines<T>(lines: T[]): AsyncGenerator<T> {
for (const line of lines) {
yield line;
// await new Promise((resolve, reject) => setTimeout(() => resolve(null), 50));
}
}

View file

@ -0,0 +1,35 @@
import path from "path";
import { DiffLine, ILLM } from "../..";
import { generateLines } from "../../diff/util";
import { supportedLanguages } from "../../util/treeSitter";
import { deterministicApplyLazyEdit } from "./deterministic";
import { streamLazyApply } from "./streamLazyApply";
function canUseInstantApply(filename: string) {
const fileExtension = path.extname(filename).toLowerCase().slice(1);
return supportedLanguages[fileExtension] !== undefined;
}
export async function applyCodeBlock(
oldFile: string,
newFile: string,
filename: string,
llm: ILLM,
fastLlm: ILLM,
): Promise<[boolean, AsyncGenerator<DiffLine>]> {
if (canUseInstantApply(filename)) {
const diffLines = await deterministicApplyLazyEdit(
oldFile,
newFile,
filename,
);
// Fall back to LLM method if we couldn't apply deterministically
if (diffLines !== undefined) {
const diffGenerator = generateLines(diffLines!);
return [true, diffGenerator];
}
}
return [false, streamLazyApply(oldFile, filename, newFile, llm, fastLlm)];
}

View file

@ -0,0 +1,161 @@
import fs from "node:fs";
// @ts-ignore no typings available
import { diff as myersDiff } from "myers-diff";
import path from "node:path";
import { DiffLine } from "../..";
import { myersDiff as continueMyersDiff } from "../../diff/myers";
import { dedent } from "../../util";
import { deterministicApplyLazyEdit } from "./deterministic";
const UNIFIED_DIFF_SYMBOLS = {
same: "",
new: "+",
old: "-",
};
async function collectDiffs(
oldFile: string,
newFile: string,
filename: string,
): Promise<{ ourDiffs: DiffLine[]; myersDiffs: any }> {
const ourDiffs: DiffLine[] = [];
for (const diffLine of (await deterministicApplyLazyEdit(
oldFile,
newFile,
filename,
)) ?? []) {
ourDiffs.push(diffLine);
}
const myersDiffs = myersDiff(oldFile, newFile);
return { ourDiffs, myersDiffs };
}
function displayDiff(diff: DiffLine[]) {
return diff
.map(({ type, line }) =>
type === "same" ? line : `${UNIFIED_DIFF_SYMBOLS[type]} ${line}`,
)
.join("\n");
}
function normalizeDisplayedDiff(d: string): string {
return d
.split("\n")
.map((line) => (line.trim() === "" ? "" : line))
.join("\n");
}
async function expectDiff(file: string) {
const testFilePath = path.join(
__dirname,
"edit",
"lazy",
"test-examples",
file + ".diff",
);
const testFileContents = fs.readFileSync(testFilePath, "utf-8");
const [oldFile, newFile, expectedDiff] = testFileContents
.split("\n---\n")
.map((s) => s.replace(/^\n+/, "").trimEnd());
const { ourDiffs: streamDiffs } = await collectDiffs(oldFile, newFile, file);
const displayedDiff = displayDiff(streamDiffs);
if (!expectedDiff || expectedDiff.trim() === "") {
console.log(
"Expected diff was empty. Writing computed diff to the test file",
);
fs.writeFileSync(
testFilePath,
`${oldFile}\n\n---\n\n${newFile}\n\n---\n\n${displayDiff(
continueMyersDiff(oldFile, newFile),
)}`,
);
throw new Error("Expected diff is empty");
}
expect(normalizeDisplayedDiff(displayedDiff)).toEqual(
normalizeDisplayedDiff(expectedDiff),
);
}
describe("deterministicApplyLazyEdit(", () => {
test("no changes", async () => {
const file = dedent`
function test() {
return 1;
}
function test2(a) {
return a * 2;
}
`;
const { ourDiffs: streamDiffs, myersDiffs } = await collectDiffs(
file,
file,
"test.js",
);
expect(streamDiffs).toEqual(
file.split("\n").map((line) => ({
line,
type: "same",
})),
);
expect(myersDiffs).toEqual([]);
});
test("fastapi", async () => {
await expectDiff("fastapi.py");
});
test("calculator exp", async () => {
await expectDiff("calculator-exp.js");
});
test("calculator exp2", async () => {
await expectDiff("calculator-exp2.js");
});
test("calculator comments", async () => {
await expectDiff("calculator-comments.js");
});
test("calculator docstrings", async () => {
await expectDiff("calculator-docstrings.js");
});
test("calculator stateless", async () => {
await expectDiff("calculator-stateless.js");
});
test("top level same blocks", async () => {
await expectDiff("top-level-same.js");
});
test.skip("gui add toggle", async () => {
await expectDiff("gui.js");
});
test("rust calculator", async () => {
await expectDiff("rust-calc-exp.rs");
});
test("no lazy blocks", async () => {
await expectDiff("no-lazy.js");
});
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

@ -0,0 +1,323 @@
import { distance } from "fastest-levenshtein";
import path from "path";
import Parser from "web-tree-sitter";
import { DiffLine } from "../..";
import { LANGUAGES } from "../../autocomplete/languages";
import { myersDiff } from "../../diff/myers";
import { getParserForFile } from "../../util/treeSitter";
import { findInAst } from "./findInAst";
type AstReplacements = Array<{
nodeToReplace: Parser.SyntaxNode;
replacementNodes: Parser.SyntaxNode[];
}>;
function reconstructNewFile(
oldFile: string,
newFile: string,
lazyBlockReplacements: AstReplacements,
): string {
// Sort acc by reverse line number
lazyBlockReplacements
.sort((a, b) => a.nodeToReplace.startIndex - b.nodeToReplace.startIndex)
.reverse();
// Reconstruct entire file by replacing lazy blocks with the replacement nodes
const oldFileLines = oldFile.split("\n");
const newFileChars = newFile.split("");
for (const {
nodeToReplace: lazyBlockNode,
replacementNodes,
} of lazyBlockReplacements) {
// Get the full string from the replacement nodes
let replacementText = "";
if (replacementNodes.length > 0) {
const startPosition = replacementNodes[0].startPosition;
const endPosition =
replacementNodes[replacementNodes.length - 1].endPosition;
const replacementLines = oldFileLines.slice(
startPosition.row,
endPosition.row + 1,
);
replacementLines[0] = replacementLines[0].slice(startPosition.column);
replacementLines[replacementLines.length - 1] = replacementLines[
replacementLines.length - 1
].slice(0, endPosition.column);
replacementText = replacementLines.join("\n");
// Replace the lazy block
newFileChars.splice(
lazyBlockNode.startIndex,
lazyBlockNode.text.length,
replacementText,
);
} else {
// If there are no replacements, then we want to strip the surrounding whitespace
// The example in calculator-exp.js.diff is a test where this is necessary
const lazyBlockStart = lazyBlockNode.startIndex;
const lazyBlockEnd = lazyBlockNode.endIndex - 1;
// Remove leading whitespace up to two new lines
let startIndex = lazyBlockStart;
let newLinesFound = 0;
while (
startIndex > 0 &&
newFileChars[startIndex - 1]?.trim() === "" &&
newLinesFound < 2
) {
startIndex--;
if (newFileChars[startIndex - 1] === "\n") {
newLinesFound++;
}
}
// Remove trailing whitespace up to two new lines
const charAfter = newFileChars[lazyBlockEnd + 1];
const secondCharAfter = newFileChars[lazyBlockEnd + 2];
let endIndex = lazyBlockEnd;
if (charAfter === "\n") {
endIndex++;
if (secondCharAfter === "\n") {
endIndex++;
}
}
// Remove the lazy block
newFileChars.splice(startIndex, endIndex - startIndex + 1);
}
}
return newFileChars.join("");
}
const REMOVAL_PERCENTAGE_THRESHOLD = 0.3;
function shouldRejectDiff(diff: DiffLine[]): boolean {
const numRemovals = diff.filter((line) => line.type === "old").length;
if (numRemovals / diff.length > REMOVAL_PERCENTAGE_THRESHOLD) {
return true;
}
return false;
}
// TODO: If we don't have high confidence, return undefined to fall back to slower methods
export async function deterministicApplyLazyEdit(
oldFile: string,
newLazyFile: string,
filename: string,
): Promise<DiffLine[] | undefined> {
const parser = await getParserForFile(filename);
if (!parser) {
return undefined;
}
const oldTree = parser.parse(oldFile);
let newTree = parser.parse(newLazyFile);
// If there is no lazy block anywhere, we add our own to the outsides
// so that large chunks of the file don't get removed
if (!findInAst(newTree.rootNode, isLazyBlock)) {
// First, we need to check whether there are matching (similar) nodes at the root level
const firstSimilarNode = findInAst(oldTree.rootNode, (node) =>
nodesAreSimilar(node, newTree.rootNode.children[0]),
);
if (firstSimilarNode?.parent?.equals(oldTree.rootNode)) {
// If so, we tack lazy blocks to start and end, and run the usual algorithm
const ext = path.extname(filename).slice(1);
const language = LANGUAGES[ext];
if (language) {
newLazyFile = `${language.singleLineComment} ... existing code ...\n\n${newLazyFile}\n\n${language.singleLineComment} ... existing code...`;
newTree = parser.parse(newLazyFile);
}
} else {
// If not, we need to recursively search for the nodes that are being rewritten,
// and we apply a slightly different algorithm
return undefined; // TODO
}
}
const replacements: AstReplacements = [];
findLazyBlockReplacements(oldTree.rootNode, newTree.rootNode, replacements);
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
if (shouldRejectDiff(diff)) {
return undefined;
}
return diff;
}
const LAZY_COMMENT_REGEX = /\.{3}\s*(.+?)\s*\.{3}/;
export function isLazyLine(text: string): boolean {
return LAZY_COMMENT_REGEX.test(text);
}
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
* @param b
* @returns
*/
function nodesAreSimilar(a: Parser.SyntaxNode, b: Parser.SyntaxNode): boolean {
if (a.type !== b.type) {
return false;
}
// Check if they have the same name
if (
a.childForFieldName("name") !== null &&
a.childForFieldName("name")?.text === b.childForFieldName("name")?.text
) {
return true;
}
if (
a.namedChildren[0]?.text === b.namedChildren[0]?.text &&
a.children[1]?.text === b.children[1]?.text
) {
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];
return stringsWithinLevDistThreshold(lineOneA, lineOneB, 0.2);
}
function nodesAreExact(a: Parser.SyntaxNode, b: Parser.SyntaxNode): boolean {
return a.text === b.text;
}
/**
* Should be like Myers diff, but lazy blocks consume all nodes until the next match
* @param newNode
* @param oldNode
* @returns
*/
function findLazyBlockReplacements(
oldNode: Parser.SyntaxNode,
newNode: Parser.SyntaxNode,
replacements: AstReplacements,
): void {
// Base case
if (nodesAreExact(oldNode, newNode)) {
return;
}
// Other base case: no lazy blocks => use line-by-line diff
if (!findInAst(newNode, isLazyBlock)) {
return;
}
const leftChildren = oldNode.namedChildren;
const rightChildren = newNode.namedChildren;
let isLazy = false;
let currentLazyBlockNode: Parser.SyntaxNode | undefined = undefined;
const currentLazyBlockReplacementNodes = [];
while (leftChildren.length > 0 && rightChildren.length > 0) {
const L = leftChildren[0];
const R = rightChildren[0];
// Consume lazy block
if (isLazyBlock(R)) {
// Enter "lazy mode"
isLazy = true;
currentLazyBlockNode = R;
rightChildren.shift();
continue;
}
// Look for the first match of L
const index = rightChildren.findIndex((node) => nodesAreSimilar(L, node));
if (index === -1) {
// No match
if (isLazy) {
// Add to replacements if in lazy mode
currentLazyBlockReplacementNodes.push(L);
}
// Consume
leftChildren.shift();
} else {
// Match found, insert all right nodes before the match
for (let i = 0; i < index; i++) {
rightChildren.shift();
}
// then recurse at the match
findLazyBlockReplacements(L, rightChildren[0], replacements);
// then consume L and R
leftChildren.shift();
rightChildren.shift();
// Exit "lazy mode"
if (isLazy) {
// Record the replacement lines
replacements.push({
nodeToReplace: currentLazyBlockNode!,
replacementNodes: [...currentLazyBlockReplacementNodes],
});
isLazy = false;
currentLazyBlockReplacementNodes.length = 0;
currentLazyBlockNode = undefined;
}
}
}
if (isLazy) {
replacements.push({
nodeToReplace: currentLazyBlockNode!,
replacementNodes: [...currentLazyBlockReplacementNodes, ...leftChildren],
});
}
// Cut out any extraneous lazy blocks
for (const R of rightChildren) {
if (isLazyBlock(R)) {
replacements.push({
nodeToReplace: R,
replacementNodes: [],
});
}
}
}

View file

@ -0,0 +1,16 @@
import Parser from "web-tree-sitter";
export function findInAst(
node: Parser.SyntaxNode,
criterion: (node: Parser.SyntaxNode) => boolean,
): Parser.SyntaxNode | null {
const stack = [node];
while (stack.length > 0) {
let node = stack.pop()!;
if (criterion(node)) {
return node;
}
stack.push(...node.children);
}
return null;
}

62
core/edit/lazy/prompts.ts Normal file
View file

@ -0,0 +1,62 @@
import { ChatMessage, ModelProvider } from "../..";
import { dedent } from "../../util";
export const UNCHANGED_CODE = "UNCHANGED CODE";
type LazyApplyPrompt = (
oldCode: string,
filename: string,
newCode: string,
) => ChatMessage[];
const RULES = [
"Your response should be a code block containing a rewritten version of the file.",
`Whenever any part of the code is the same as before, you may simply indicate this with a comment that says "${UNCHANGED_CODE}" instead of rewriting.`,
"You must keep at least one line above and below from the original code, so that we can identify what the previous code was.",
`Do not place miscellaneous "${UNCHANGED_CODE}" comments at the top or bottom of the file when there is nothing to replace them.`,
// `You should write "${UNCHANGED_CODE}" at least for each function that is unchanged, rather than grouping them into a single comment.`,
// `You should lean toward using a smaller number of these comments rather than rewriting it for every function if all of them are unchanged.`,
// `You may do this for imports as well if needed.`,
// `Do not explain your changes either before or after the code block.`,
"The code should always be syntactically valid, even with the comments.",
];
function claude35SonnetLazyApplyPrompt(
...args: Parameters<LazyApplyPrompt>
): ReturnType<LazyApplyPrompt> {
const userContent = dedent`
ORIGINAL CODE:
\`\`\`${args[1]}
${args[0]}
\`\`\`
NEW CODE:
\`\`\`
${args[2]}
\`\`\`
Above is a code block containing the original version of a file (ORIGINAL CODE) and below it is a code snippet (NEW CODE) that was suggested as modification to the original file. Your task is to apply the NEW CODE to the ORIGINAL CODE and show what the entire file would look like after it is applied.
- ${RULES.join("\n- ")}
`;
const assistantContent = dedent`
Sure! Here's the modified version of the file after applying the new code:
\`\`\`${args[1]}
`;
return [
{ role: "user", content: userContent },
{ role: "assistant", content: assistantContent },
];
}
export function lazyApplyPromptForModel(
model: string,
provider: ModelProvider,
): LazyApplyPrompt | undefined {
if (model.includes("sonnet")) {
return claude35SonnetLazyApplyPrompt;
}
return undefined;
}

98
core/edit/lazy/replace.ts Normal file
View file

@ -0,0 +1,98 @@
import { ILLM } from "../..";
import {
filterLeadingNewline,
stopAtLines,
} from "../../autocomplete/streamTransforms/lineStream";
import { streamLines } from "../../diff/util";
import { dedent } from "../../util";
export const BUFFER_LINES_BELOW = 3;
const MATCH_LINES_ABOVE = 1;
export function getReplacementByMatching(
oldCode: string,
linesBefore: string[],
linesAfter: string[],
): string | undefined {
const oldLines = oldCode.split("\n");
const linesToMatchAbove = MATCH_LINES_ABOVE;
const linesToMatchBelow = Math.min(BUFFER_LINES_BELOW, linesAfter.length);
// Get surrounding lines around the gap
const beforeContext = linesBefore.slice(-linesToMatchAbove).join("\n");
const afterContext = linesAfter.slice(0, linesToMatchBelow).join("\n");
// Find the start index in the old code
const startIndex = oldLines.findIndex((line, index) => {
const chunk = oldLines.slice(index, index + linesToMatchAbove).join("\n");
return chunk === beforeContext;
});
if (startIndex === -1) {
return undefined; // Couldn't find matching start
}
// Find the end index in the old code
const endIndex = oldLines.findIndex((line, index) => {
if (index <= startIndex + linesToMatchBelow) {
return false;
}
const chunk = oldLines.slice(index, index + linesToMatchBelow).join("\n");
return chunk === afterContext;
});
if (endIndex === -1) {
return undefined; // Couldn't find matching end
}
// Extract the replacement code
const replacement = oldLines
.slice(startIndex + linesToMatchAbove, endIndex)
.join("\n");
return replacement;
}
const REPLACE_HERE = "// REPLACE HERE //";
export async function* getReplacementWithLlm(
oldCode: string,
linesBefore: string[],
linesAfter: string[],
llm: ILLM,
): AsyncGenerator<string> {
const userPrompt = dedent`
ORIGINAL CODE:
\`\`\`
${oldCode}
\`\`\`
UPDATED CODE:
\`\`\`
${linesBefore.join("\n")}
${REPLACE_HERE}
${linesAfter.join("\n")}
\`\`\`
Above is an original version of a file, followed by a newer version that is in the process of being written. The new version contains a section which is exactly the same as in the original code, and has been marked with "${REPLACE_HERE}". Your task is to give the exact snippet of code from the original code that should replace "${REPLACE_HERE}" in the new version.
Your output should be a single code block. We will paste the contents of that code block directly into the new version, so make sure that it has correct indentation.
`;
const assistantPrompt = dedent`
Here is the snippet of code that will replace "${REPLACE_HERE}" in the new version:
\`\`\`
`;
const completion = await llm.streamChat([
{ role: "user", content: userPrompt },
{ role: "assistant", content: assistantPrompt },
]);
let lines = streamLines(completion);
lines = filterLeadingNewline(lines);
lines = stopAtLines(lines, () => {}, ["```"]);
for await (const line of lines) {
yield line;
}
}

View file

@ -0,0 +1,130 @@
import {
filterLeadingAndTrailingNewLineInsertion,
filterLeadingNewline,
stopAtLines,
} from "../../autocomplete/streamTransforms/lineStream";
import { streamDiff } from "../../diff/streamDiff.js";
import { LineStream, streamLines } from "../../diff/util.js";
import { DiffLine, ILLM } from "../../index.js";
import { lazyApplyPromptForModel, UNCHANGED_CODE } from "./prompts.js";
import { BUFFER_LINES_BELOW, getReplacementWithLlm } from "./replace.js";
export async function* streamLazyApply(
oldCode: string,
filename: string,
newCode: string,
llm: ILLM,
fastLlm: ILLM,
): AsyncGenerator<DiffLine> {
const promptFactory = lazyApplyPromptForModel(llm.model, llm.providerName);
if (!promptFactory) {
throw new Error(`Lazy apply not supported for model ${llm.model}`);
}
const promptMessages = promptFactory(oldCode, filename, newCode);
const lazyCompletion = llm.streamChat(promptMessages);
// Do find and replace over the lazy edit response
async function* replacementFunction(
oldCode: string,
linesBefore: string[],
linesAfter: string[],
): AsyncGenerator<string> {
for await (const line of getReplacementWithLlm(
oldCode,
linesBefore,
linesAfter,
fastLlm,
)) {
yield line;
}
}
let lazyCompletionLines = streamLines(lazyCompletion, true);
// Process line output
// lazyCompletionLines = filterEnglishLinesAtStart(lazyCompletionLines);
lazyCompletionLines = stopAtLines(lazyCompletionLines, () => {}, ["```"]);
lazyCompletionLines = filterLeadingNewline(lazyCompletionLines);
// Fill in unchanged code
let lines = streamFillUnchangedCode(
lazyCompletionLines,
oldCode,
replacementFunction,
);
// Convert output to diff
const oldLines = oldCode.split(/\r?\n/);
let diffLines = streamDiff(oldLines, lines);
diffLines = filterLeadingAndTrailingNewLineInsertion(diffLines);
for await (const diffLine of diffLines) {
yield diffLine;
}
}
async function* streamFillUnchangedCode(
lines: LineStream,
oldCode: string,
replacementFunction: (
oldCode: string,
linesBefore: string[],
linesAfter: string[],
) => AsyncGenerator<string>,
): LineStream {
const newLines = [];
let buffer = [];
let waitingForBuffer = false;
for await (const line of lines) {
if (waitingForBuffer) {
buffer.push(line);
if (buffer.length >= BUFFER_LINES_BELOW) {
// Find the replacement and continue streaming once we have it
const replacementLines = replacementFunction(oldCode, newLines, buffer);
let replacement = "";
for await (const replacementLine of replacementLines) {
yield replacementLine;
newLines.push(replacementLine);
replacement += replacementLine + "\n";
}
// Yield the buffered lines
for (const bufferedLine of buffer) {
yield bufferedLine;
newLines.push(bufferedLine);
}
waitingForBuffer = false;
buffer = [];
continue;
} else {
continue;
}
}
if (line.includes(UNCHANGED_CODE)) {
// Buffer so we can give the context of BUFFER_LINES_BELOW lines below
waitingForBuffer = true;
// TODO: If the UNCHANGED CODE is at the very top of the file we need to handle a bit differently
} else {
yield line;
newLines.push(line);
}
}
if (waitingForBuffer) {
// If we're still waiting for a buffer, we've reached the end of the stream
// and we should just look for the replacement with what we have
const replacementLines = replacementFunction(oldCode, newLines, buffer);
for await (const replacementLine of replacementLines) {
yield replacementLine;
newLines.push(replacementLine);
}
// Yield the buffered lines
for (const bufferedLine of buffer) {
yield bufferedLine;
newLines.push(bufferedLine);
}
}
}

View file

@ -0,0 +1,129 @@
class Calculator {
constructor() {
this.result = 0;
}
add(number) {
this.result += number;
return this;
}
subtract(number) {
this.result -= number;
return this;
}
multiply(number) {
this.result *= number;
return this;
}
divide(number) {
if (number === 0) {
throw new Error("Cannot divide by zero");
}
this.result /= number;
return this;
}
getResult() {
return this.result;
}
reset() {
this.result = 0;
return this;
}
}
---
class Calculator {
// ... existing code ...
// Adds the given number to the result
add(number) {
this.result += number;
return this;
}
// Subtracts the given number from the result
subtract(number) {
this.result -= number;
return this;
}
// Multiplies the result by the given number
multiply(number) {
this.result *= number;
return this;
}
// Divides the result by the given number
// Throws an error if attempting to divide by zero
divide(number) {
if (number === 0) {
throw new Error("Cannot divide by zero");
}
this.result /= number;
return this;
}
// Returns the current result
getResult() {
return this.result;
}
// Resets the result to zero
reset() {
this.result = 0;
return this;
}
}
---
class Calculator {
constructor() {
this.result = 0;
}
+ // Adds the given number to the result
add(number) {
this.result += number;
return this;
}
+ // Subtracts the given number from the result
subtract(number) {
this.result -= number;
return this;
}
+ // Multiplies the result by the given number
multiply(number) {
this.result *= number;
return this;
}
+ // Divides the result by the given number
+ // Throws an error if attempting to divide by zero
divide(number) {
if (number === 0) {
throw new Error("Cannot divide by zero");
}
this.result /= number;
return this;
}
+ // Returns the current result
getResult() {
return this.result;
}
+ // Resets the result to zero
reset() {
this.result = 0;
return this;
}
}

View file

@ -0,0 +1,189 @@
class Calculator {
constructor() {
this.result = 0;
}
add(number) {
this.result += number;
return this;
}
subtract(number) {
this.result -= number;
return this;
}
multiply(number) {
this.result *= number;
return this;
}
divide(number) {
if (number === 0) {
throw new Error("Cannot divide by zero");
}
this.result /= number;
return this;
}
getResult() {
return this.result;
}
reset() {
this.result = 0;
return this;
}
}
---
/**
* Calculator class for performing basic arithmetic operations.
*/
class Calculator {
/**
* Creates a new Calculator instance.
* Initializes the result to 0.
*/
constructor() {
this.result = 0;
}
/**
* Adds a number to the current result.
* @param {number} number - The number to add.
* @returns {Calculator} The Calculator instance for method chaining.
*/
add(number) {
this.result += number;
return this;
}
/**
* Subtracts a number from the current result.
* @param {number} number - The number to subtract.
* @returns {Calculator} The Calculator instance for method chaining.
*/
subtract(number) {
this.result -= number;
return this;
}
/**
* Multiplies the current result by a number.
* @param {number} number - The number to multiply by.
* @returns {Calculator} The Calculator instance for method chaining.
*/
multiply(number) {
this.result *= number;
return this;
}
/**
* Divides the current result by a number.
* @param {number} number - The number to divide by.
* @returns {Calculator} The Calculator instance for method chaining.
* @throws {Error} If attempting to divide by zero.
*/
divide(number) {
if (number === 0) {
throw new Error("Cannot divide by zero");
}
this.result /= number;
return this;
}
/**
* Returns the current result.
* @returns {number} The current result.
*/
getResult() {
return this.result;
}
/**
* Resets the calculator's result to 0.
* @returns {Calculator} The Calculator instance for method chaining.
*/
reset() {
this.result = 0;
return this;
}
}
---
+ /**
+ * Calculator class for performing basic arithmetic operations.
+ */
class Calculator {
+ /**
+ * Creates a new Calculator instance.
+ * Initializes the result to 0.
+ */
constructor() {
this.result = 0;
}
+ /**
+ * Adds a number to the current result.
+ * @param {number} number - The number to add.
+ * @returns {Calculator} The Calculator instance for method chaining.
+ */
add(number) {
this.result += number;
return this;
}
+ /**
+ * Subtracts a number from the current result.
+ * @param {number} number - The number to subtract.
+ * @returns {Calculator} The Calculator instance for method chaining.
+ */
subtract(number) {
this.result -= number;
return this;
}
+ /**
+ * Multiplies the current result by a number.
+ * @param {number} number - The number to multiply by.
+ * @returns {Calculator} The Calculator instance for method chaining.
+ */
multiply(number) {
this.result *= number;
return this;
}
+ /**
+ * Divides the current result by a number.
+ * @param {number} number - The number to divide by.
+ * @returns {Calculator} The Calculator instance for method chaining.
+ * @throws {Error} If attempting to divide by zero.
+ */
divide(number) {
if (number === 0) {
throw new Error("Cannot divide by zero");
}
this.result /= number;
return this;
}
+ /**
+ * Returns the current result.
+ * @returns {number} The current result.
+ */
getResult() {
return this.result;
}
+ /**
+ * Resets the calculator's result to 0.
+ * @returns {Calculator} The Calculator instance for method chaining.
+ */
reset() {
this.result = 0;
return this;
}
}

View file

@ -0,0 +1,99 @@
class Calculator {
constructor() {
this.result = 0;
}
add(number) {
this.result += number;
return this;
}
subtract(number) {
this.result -= number;
return this;
}
multiply(number) {
this.result *= number;
return this;
}
divide(number) {
if (number === 0) {
throw new Error("Cannot divide by zero");
}
this.result /= number;
return this;
}
getResult() {
return this.result;
}
reset() {
this.result = 0;
return this;
}
}
---
class Calculator {
constructor() {
this.result = 0;
}
// ... same ...
exp(a) {
this.result = Math.pow(this.result, a);
return this;
}
// ... same ...
}
---
class Calculator {
constructor() {
this.result = 0;
}
add(number) {
this.result += number;
return this;
}
subtract(number) {
this.result -= number;
return this;
}
multiply(number) {
this.result *= number;
return this;
}
divide(number) {
if (number === 0) {
throw new Error("Cannot divide by zero");
}
this.result /= number;
return this;
}
getResult() {
return this.result;
}
reset() {
this.result = 0;
return this;
}
+
+ exp(a) {
+ this.result = Math.pow(this.result, a);
+ return this;
+ }
}

View file

@ -0,0 +1,93 @@
class Calculator {
constructor() {
this.result = 0;
}
add(number) {
this.result += number;
return this;
}
subtract(number) {
this.result -= number;
return this;
}
multiply(number) {
this.result *= number;
return this;
}
divide(number) {
if (number === 0) {
throw new Error("Cannot divide by zero");
}
this.result /= number;
return this;
}
getResult() {
return this.result;
}
reset() {
this.result = 0;
return this;
}
}
---
class Calculator {
// ... existing code ...
exp(number) {
this.result = Math.pow(this.result, number);
return this;
}
}
---
class Calculator {
constructor() {
this.result = 0;
}
add(number) {
this.result += number;
return this;
}
subtract(number) {
this.result -= number;
return this;
}
multiply(number) {
this.result *= number;
return this;
}
divide(number) {
if (number === 0) {
throw new Error("Cannot divide by zero");
}
this.result /= number;
return this;
}
getResult() {
return this.result;
}
reset() {
this.result = 0;
return this;
}
+
+ exp(number) {
+ this.result = Math.pow(this.result, number);
+ return this;
+ }
}

View file

@ -0,0 +1,111 @@
class Calculator {
constructor() {
this.result = 0;
}
add(number) {
this.result += number;
return this;
}
subtract(number) {
this.result -= number;
return this;
}
multiply(number) {
this.result *= number;
return this;
}
divide(number) {
if (number === 0) {
throw new Error("Cannot divide by zero");
}
this.result /= number;
return this;
}
getResult() {
return this.result;
}
reset() {
this.result = 0;
return this;
}
}
---
class Calculator {
// ... existing code ...
static add(a, b) {
return a + b;
}
static subtract(a, b) {
return a - b;
}
static multiply(a, b) {
return a * b;
}
static divide(a, b) {
if (b === 0) {
throw new Error("Cannot divide by zero");
}
return a / b;
}
}
---
class Calculator {
constructor() {
this.result = 0;
}
- add(number) {
- this.result += number;
- return this;
+ static add(a, b) {
+ return a + b;
}
- subtract(number) {
- this.result -= number;
- return this;
+ static subtract(a, b) {
+ return a - b;
}
- multiply(number) {
- this.result *= number;
- return this;
+ static multiply(a, b) {
+ return a * b;
}
- divide(number) {
- if (number === 0) {
+ static divide(a, b) {
+ if (b === 0) {
throw new Error("Cannot divide by zero");
}
- this.result /= number;
- return this;
+ return a / b;
}
-
- getResult() {
- return this.result;
- }
-
- reset() {
- this.result = 0;
- return this;
- }
}

View file

@ -0,0 +1,37 @@
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.get("/landing")
def read_landing_page():
return {"message": "Welcome to the landing page"}
---
from fastapi import FastAPI, HTTPException
# ... same ...
@app.get("/landing")
def read_landing_page():
raise HTTPException(status_code=404, detail="Page not found")
---
- from fastapi import FastAPI
+ from fastapi import FastAPI, HTTPException
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.get("/landing")
def read_landing_page():
- return {"message": "Welcome to the landing page"}
+ raise HTTPException(status_code=404, detail="Page not found")

File diff suppressed because it is too large Load diff

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

@ -0,0 +1,30 @@
class Calculator {
constructor() {
this.result = 0;
}
reset() {
this.result = 0;
return this;
}
}
---
reset() {
this.result = 1;
return this;
}
---
class Calculator {
constructor() {
this.result = 0;
}
reset() {
- this.result = 0;
+ this.result = 1;
return this;
}
}

View file

@ -0,0 +1,34 @@
class Hello {
hello() {
return "Hello World";
}
}
class Goodbye {
goodbye() {
return "Goodbye World";
}
}
---
class Goodbye {
goodbye() {
return "Au revoir le monde";
}
}
---
class Hello {
hello() {
return "Hello World";
}
}
class Goodbye {
goodbye() {
- return "Goodbye World";
+ return "Au revoir le monde";
}
}

View file

@ -0,0 +1,126 @@
use std::io;
fn main() {
println!("Welcome to the Calculator!");
loop {
println!("Please enter an operator (+, -, *, /) or 'q' to quit:");
let operator = read_input();
if operator == "q" {
break;
}
println!("Please enter the first number:");
let num1 = read_input().parse::<f64>().unwrap();
println!("Please enter the second number:");
let num2 = read_input().parse::<f64>().unwrap();
let result = match operator.as_str() {
"+" => num1 + num2,
"-" => num1 - num2,
"*" => num1 * num2,
"/" => num1 / num2,
_ => {
println!("Invalid operator. Please try again.");
continue;
}
};
println!("Result: {}", result);
}
}
fn read_input() -> String {
let mut input = String::new();
io::stdin()
.read_line(&mut input)
.expect("Failed to read input");
input.trim().to_string()
}
---
use std::io;
fn main() {
println!("Welcome to the Calculator!");
loop {
println!("Please enter an operator (+, -, *, /, ^) or 'q' to quit:");
let operator = read_input();
if operator == "q" {
break;
}
println!("Please enter the first number:");
let num1 = read_input().parse::<f64>().unwrap();
println!("Please enter the second number:");
let num2 = read_input().parse::<f64>().unwrap();
let result = match operator.as_str() {
"+" => num1 + num2,
"-" => num1 - num2,
"*" => num1 * num2,
"/" => num1 / num2,
"^" => num1.powf(num2),
_ => {
println!("Invalid operator. Please try again.");
continue;
}
};
println!("Result: {}", result);
}
}
// ... existing code ...
---
use std::io;
fn main() {
println!("Welcome to the Calculator!");
loop {
- println!("Please enter an operator (+, -, *, /) or 'q' to quit:");
+ println!("Please enter an operator (+, -, *, /, ^) or 'q' to quit:");
let operator = read_input();
if operator == "q" {
break;
}
println!("Please enter the first number:");
let num1 = read_input().parse::<f64>().unwrap();
println!("Please enter the second number:");
let num2 = read_input().parse::<f64>().unwrap();
let result = match operator.as_str() {
"+" => num1 + num2,
"-" => num1 - num2,
"*" => num1 * num2,
"/" => num1 / num2,
+ "^" => num1.powf(num2),
_ => {
println!("Invalid operator. Please try again.");
continue;
}
};
println!("Result: {}", result);
}
}
fn read_input() -> String {
let mut input = String::new();
io::stdin()
.read_line(&mut input)
.expect("Failed to read input");
input.trim().to_string()
}

View file

@ -0,0 +1,64 @@
class Calculator {
constructor() {
this.result = 0;
}
}
class Subtract extends Calculator {
sub(num1, num2) {
this.result = num1 - num2;
return this.result;
}
}
class Add extends Calculator {
add(num1, num2) {
this.result = num1 + num2;
return this.result;
}
}
---
// ... existing code ...
class Subtract extends Calculator {
sub(num1, num2) {
this.result = num1 - num2;
if (this.result < 0) {
throw new Error("Result cannot be negative");
}
return this.result;
}
}
// ... existing code ...
---
class Calculator {
constructor() {
this.result = 0;
}
}
class Subtract extends Calculator {
sub(num1, num2) {
this.result = num1 - num2;
+
+ if (this.result < 0) {
+ throw new Error("Result cannot be negative");
+ }
+
return this.result;
}
}
class Add extends Calculator {
add(num1, num2) {
this.result = num1 + num2;
return this.result;
}
}

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 {
@ -15,7 +15,7 @@ import {
LLMFullCompletionOptions,
} from "../index.js";
import { gptEditPrompt } from "../llm/templates/edit.js";
import { Telemetry } from "./posthog.js";
import { Telemetry } from "../util/posthog.js";
function constructPrompt(
prefix: string,

30
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,
@ -578,6 +580,7 @@ type ContextProviderName =
| "gitlab-mr"
| "os"
| "currentFile"
| "greptile"
| "outline"
| "continue-proxy"
| "highlights"
@ -691,6 +694,8 @@ export type ModelName =
| "deepseek-7b"
| "deepseek-33b"
| "neural-chat-7b"
| "gemma-7b-it"
| "gemma2-9b-it"
// Anthropic
| "claude-3-5-sonnet-20240620"
| "claude-3-opus-20240229"
@ -725,6 +730,11 @@ export interface RequestOptions {
clientCertificate?: ClientCertificateOptions;
}
export interface CacheBehavior {
cacheSystemMessage?: boolean;
cacheConversation?: boolean;
}
export interface ClientCertificateOptions {
cert: string;
key: string;
@ -787,6 +797,7 @@ export interface ModelDescription {
requestOptions?: RequestOptions;
promptTemplates?: { [key: string]: string };
capabilities?: ModelCapability;
cacheBehavior?: CacheBehavior;
}
export type EmbeddingsProviderName =
@ -871,6 +882,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,
},
};
}
@ -383,20 +387,18 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex {
const placeholders = likePatterns.map(() => "?").join(" OR path LIKE ");
const query = `
SELECT path, signature
FROM code_snippets
WHERE path LIKE ${placeholders}
ORDER BY path
LIMIT ? OFFSET ?
`;
SELECT DISTINCT path, signature
FROM code_snippets
WHERE path LIKE ${placeholders}
ORDER BY path, signature
LIMIT ? OFFSET ?
`;
const rows = await db.all(query, [...likePatterns, batchSize, offset]);
const validRows = rows.filter((row) => row.path && row.signature !== null);
const groupedByPath: { [path: string]: string[] } = {};
for (const { path, signature } of validRows) {
for (const { path, signature } of rows) {
if (!groupedByPath[path]) {
groupedByPath[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

@ -411,7 +411,7 @@ class ChromiumCrawler {
for (const link of linkGroup) {
enqueuedLinkCount++;
console.log({ enqueuedLinkCount, url: this.startUrl });
console.log({ enqueuedLinkCount, url: this.startUrl.toString() });
if (enqueuedLinkCount <= this.maxRequestsPerCrawl) {
yield* this.crawlSitePages(page, new URL(link), visitedLinks);
}

View file

@ -1,8 +1,6 @@
import { open, type Database } from "sqlite";
import sqlite3 from "sqlite3";
import lancedb, { Connection } from "vectordb";
import { ConfigHandler } from "../../config/ConfigHandler";
import DocsContextProvider from "../../context/providers/DocsContextProvider";
import {
Chunk,
ContinueConfig,
@ -11,6 +9,9 @@ import {
IndexingProgressUpdate,
SiteIndexingConfig,
} from "../..";
import { ConfigHandler } from "../../config/ConfigHandler";
import { addContextProvider } from "../../config/util";
import DocsContextProvider from "../../context/providers/DocsContextProvider";
import { FromCoreProtocol, ToCoreProtocol } from "../../protocol";
import { GlobalContext } from "../../util/GlobalContext";
import { IMessenger } from "../../util/messenger";
@ -31,7 +32,7 @@ import {
SiteIndexingResults,
} from "./preIndexed";
import preIndexedDocs from "./preIndexedDocs";
import { addContextProvider } from "../../config/util";
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,6 +254,10 @@ export default class DocsService {
}
}
void Telemetry.capture("docs_pages_crawled", {
count: processedPages,
});
const chunks: Chunk[] = [];
const embeddings: number[][] = [];
@ -317,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,
@ -456,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);
}
@ -691,7 +699,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,
@ -704,30 +717,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

@ -78,7 +78,8 @@ class BedrockEmbeddingsProvider extends BaseEmbeddingsProvider {
try {
return await
fromIni({
profile: this.profile
profile: this.profile,
ignoreCache: true
})();
} catch (e) {
console.warn(

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