Merge branch 'dev' into pe/onboarding-refactor

This commit is contained in:
Test 2024-09-12 11:07:04 -07:00
commit 68b76fda47
79 changed files with 1658 additions and 525 deletions

View file

@ -0,0 +1,4 @@
project: extensions/vscode
kind: Changed
body: Use Chromium only as a fallback after asking user
time: 2024-09-05T13:08:13.018136-07:00

View file

@ -161,7 +161,7 @@ jobs:
run: cd extensions/vscode && npx vsce package --no-dependencies --target ${{ env.target }}
# 6. Upload the .vsix as an artifact
- uses: actions/upload-artifact@v2
- uses: actions/upload-artifact@v4
with:
name: ${{ env.target }}
path: "extensions/vscode/*.vsix"

View file

@ -156,7 +156,7 @@ jobs:
run: cd extensions/vscode && npx vsce package --pre-release --no-dependencies --target ${{ env.target }}
# 6. Upload the .vsix as an artifact
- uses: actions/upload-artifact@v2
- uses: actions/upload-artifact@v4
with:
name: ${{ env.target }}
path: "extensions/vscode/*.vsix"

View file

@ -18,5 +18,8 @@
"binary/": false,
"**/core/vendor/**": true,
"**/gui/dist": true
}
},
"eslint.workingDirectories": [
"./core"
]
}

View file

@ -238,7 +238,7 @@ Continue consists of 2 parts that are split so that it can be extended to work i
1. **Continue GUI** - The Continue GUI is a React application that gives the user control over Continue. It displays the current chat history, allows the user to ask questions, invoke slash commands, and use context providers. The GUI also handles most state and holds as much of the logic as possible so that it can be reused between IDEs.
2. **Continue Extension** - The Continue Extension is a plugin for the IDE which implements the [IDE Interface](./core/index.d.ts#L229). This allows the GUI to request information from or actions to be taken within the IDE. This same interface is used regardless of IDE. The first Continue extensions we have built are for VS Code and JetBrains, but we plan to build clients for other IDEs in the future. The IDE Client must 1. implement IDE Interface, as is done [here](./extensions/vscode/src/ideProtocol.ts) for VS Code and 2. display the Continue GUI in a sidebar, like [here](./extensions/vscode/src/debugPanel.ts).
2. **Continue Extension** - The Continue Extension is a plugin for the IDE which implements the [IDE Interface](./core/index.d.ts#L229). This allows the GUI to request information from or actions to be taken within the IDE. This same interface is used regardless of IDE. The first Continue extensions we have built are for VS Code and JetBrains, but we plan to build clients for other IDEs in the future. The IDE Client must 1. implement IDE Interface, as is done [here](./extensions/vscode/src/ideProtocol.ts) for VS Code and 2. display the Continue GUI in a sidebar, like [here](./extensions/vscode/src/ContinueGUIWebviewViewProvider.ts).
### Continue VS Code Extension

View file

@ -1,44 +0,0 @@
on:
defaults:
run:
working-directory: ./server
jobs:
lint:
runs-on: ubuntu-latest
name: ${{ matrix.name }}
strategy:
fail-fast: false
matrix:
include:
- name: ruff
command: ruff check --output-format=github .
deps: --only lint-ruff
- name: mypy
command: mypy
deps: --with lint-typing
steps:
- uses: actions/checkout@v4
- name: Install Python
uses: actions/setup-python@v4
with:
python-version: "3.11"
- uses: snok/install-poetry@v1
- name: Install dependencies
run: poetry install ${{ matrix.deps }}
- run: poetry run ${{ matrix.command }}
# test:
# runs-on: ubuntu-latest
# steps:
# - uses: actions/checkout@v4
# - name: Install Python
# uses: actions/setup-python@v4
# with:
# python-version: "3.12"
# - uses: snok/install-poetry@v1
# - run: poetry run python -m pip install --upgrade pip setuptools
# - name: Install dependencies
# run: poetry install
# - run: poetry run pytest

View file

@ -1,65 +0,0 @@
on:
name: Rust Continuous integration
defaults:
run:
working-directory: ./server
jobs:
# test:
# name: test
# runs-on: ${{ matrix.os }}
# strategy:
# matrix:
# os: [ubuntu-latest, macos-latest, windows-latest]
# toolchain: [stable]
# include:
# - os: ubuntu-latest
# toolchain: nightly
# steps:
# - uses: actions/checkout@v4
# - uses: dtolnay/rust-toolchain@master
# with:
# toolchain: ${{ matrix.toolchain }}
# - run: cargo test --all-features
fmt:
name: format
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@nightly
with:
components: rustfmt
- run: cargo fmt --all --check
clippy:
name: lint
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@master
with:
toolchain: nightly-2023-12-10
components: clippy
- uses: actions-rs-plus/clippy-check@v2
with:
working-directory: server/
args: --all-features --all-targets
docs:
name: docs
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
- run: cargo doc --no-deps
cargo-deny:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: EmbarkStudios/cargo-deny-action@v1
with:
arguments: --manifest-path server/Cargo.toml

View file

@ -57,6 +57,7 @@
"adf-to-md": "^1.1.0",
"async-mutex": "^0.5.0",
"axios": "^1.6.7",
"cheerio": "^1.0.0-rc.12",
"commander": "^12.0.0",
"comment-json": "^4.2.3",
"dbinfoz": "^0.1.4",

View file

@ -20,6 +20,8 @@ export class AutocompleteLruCache {
driver: sqlite3.Database,
});
await db.exec("PRAGMA busy_timeout = 3000;");
await db.run(`
CREATE TABLE IF NOT EXISTS cache (
key TEXT PRIMARY KEY,

View file

@ -600,6 +600,7 @@ declare global {
| "msty"
| "watsonx"
| "openrouter"
| "sambanova"
| "nvidia";
export type ModelName =

View file

@ -1,5 +1,5 @@
import { ModelDescription } from "../index.js";
import { editConfigJson } from "../util/paths.js";
import { ContextProviderWithParams, ModelDescription } from "../";
import { editConfigJson } from "../util/paths";
function stringify(obj: any, indentation?: number): string {
return JSON.stringify(
@ -11,6 +11,18 @@ function stringify(obj: any, indentation?: number): string {
);
}
export function addContextProvider(provider: ContextProviderWithParams) {
editConfigJson((config) => {
if (!config.contextProviders) {
config.contextProviders = [provider];
} else {
config.contextProviders.push(provider);
}
return config;
});
}
export function addModel(model: ModelDescription) {
editConfigJson((config) => {
if (config.models?.some((m: any) => stringify(m) === stringify(model))) {

View file

@ -5,7 +5,7 @@ import type {
CustomContextProvider,
IContextProvider,
LoadSubmenuItemsArgs,
} from "../../index.js";
} from "../../";
class CustomContextProviderClass implements IContextProvider {
custom: CustomContextProvider;

View file

@ -21,9 +21,11 @@ class GitHubIssuesContextProvider extends BaseContextProvider {
): Promise<ContextItem[]> {
const issueId = query;
const { Octokit } = await import("@octokit/rest");
const domain = this.options?.domain ?? "github.com";
const octokit = new Octokit({
auth: this.options?.githubToken,
baseUrl: `https://${domain}/api/v3`,
request: {
fetch: extras.fetch,
},

View file

@ -1,11 +1,19 @@
import fs from "node:fs";
import { streamDiff } from "../diff/streamDiff.js";
import { DiffLine, DiffLineType } from "../index.js";
// @ts-ignore no typings available
import { changed, diff as myersDiff } from "myers-diff";
import path from "node:path";
// "modification" is an extra type used to represent an "old" + "new" diff line
type MyersDiffTypes = Extract<DiffLineType, "new" | "old"> | "modification";
const UNIFIED_DIFF_SYMBOLS = {
same: "",
new: "+",
old: "-",
};
async function* generateLines(lines: string[]): AsyncGenerator<string> {
for (const line of lines) {
yield line;
@ -43,6 +51,43 @@ function getMyersDiffType(diff: any): MyersDiffTypes | undefined {
return undefined;
}
function displayDiff(diff: DiffLine[]) {
return diff
.map(({ type, line }) => `${UNIFIED_DIFF_SYMBOLS[type]} ${line}`)
.join("\n");
}
async function expectDiff(file: string) {
const testFilePath = path.join(
__dirname,
"diff",
"test-examples",
file + ".diff",
);
const testFileContents = fs.readFileSync(testFilePath, "utf-8");
const [oldText, newText, expectedDiff] = testFileContents
.split("\n---\n")
.map((s) => s.replace(/^\n+/, "").trimEnd());
const oldLines = oldText.split("\n");
const newLines = newText.split("\n");
const { streamDiffs, myersDiffs } = await collectDiffs(oldLines, newLines);
const displayedDiff = displayDiff(streamDiffs);
if (!expectedDiff || expectedDiff.trim() === "") {
console.log(
"Expected diff was empty. Writing computed diff to the test file",
);
fs.writeFileSync(
testFilePath,
`${oldText}\n\n---\n\n${newText}\n\n---\n\n${displayedDiff}`,
);
throw new Error("Expected diff is empty");
}
expect(displayedDiff).toEqual(expectedDiff);
}
// We use a longer `)` string here to not get
// caught by the fuzzy matcher
describe("streamDiff(", () => {
@ -177,4 +222,20 @@ describe("streamDiff(", () => {
expect(myersDiffs[0].lhs.del).toEqual(2);
expect(getMyersDiffType(myersDiffs[0])).toBe("old");
});
test("tabs vs. spaces differences are ignored", async () => {
await expectDiff("fastapi-tabs-vs-spaces");
});
test("FastAPI example", async () => {
await expectDiff("fastapi");
});
test("FastAPI comments", async () => {
await expectDiff("add-comments");
});
test("Mock LLM example", async () => {
await expectDiff("mock-llm");
});
});

View file

@ -0,0 +1,23 @@
# Diff algorithm tests
Tests are specified as
```
<CODE BEFORE>
---
<CODE AFTER>
---
<EXPECTED DIFF>
```
`---` is the delimeter, and surrounding whitespace will be trimmed.
The expected diff can be generated with the `displayDiff` function.
We make this explicit instead of comparing to the output of `myersDiff` in case the output from that is either unattainable or not exactly what we want.
In order to generate the expected diff, you can first leave it empty and then run the test. The test will catch this and write the _computed_ diff to the test file. It is up to you to correct this to the expected diff.

View file

@ -0,0 +1,53 @@
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"}
---
# Import the FastAPI class from the fastapi module
from fastapi import FastAPI
# Create an instance of the FastAPI application
app = FastAPI()
# Define a route for the root endpoint ("/")
@app.get("/")
def read_root():
# Return a simple JSON response
return {"Hello": "World"} // This is an example comment
# Define a route for the landing page endpoint ("/landing")
@app.get("/landing")
def read_landing_page():
# Return a JSON response with a welcome message
return {"message": "Welcome to the landing page"}
---
+ # Import the FastAPI class from the fastapi module
from fastapi import FastAPI
+ # Create an instance of the FastAPI application
app = FastAPI()
+ # Define a route for the root endpoint ("/")
@app.get("/")
def read_root():
+ # Return a simple JSON response
+ return {"Hello": "World"} // This is an example comment
+
+ # Define a route for the landing page endpoint ("/landing")
- return {"Hello": "World"}
-
@app.get("/landing")
def read_landing_page():
+ # Return a JSON response with a welcome message
return {"message": "Welcome to the landing page"}

View file

@ -0,0 +1,42 @@
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
\treturn {"Hello": "World"}
@app.get("/landing")
def read_landing_page():
\treturn {"message": "Welcome to the landing page"}
---
from fastapi import FastAPI, HTTPException
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
@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():
- \treturn {"Hello": "World"}
+ return {"Hello": "World"}
@app.get("/landing")
def read_landing_page():
+ raise HTTPException(status_code=404, detail="Page not found")
- \treturn {"message": "Welcome to the landing page"}

View file

@ -0,0 +1,41 @@
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
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
@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():
+ raise HTTPException(status_code=404, detail="Page not found")
- return {"message": "Welcome to the landing page"}

View file

@ -0,0 +1,103 @@
import { ChatMessage, CompletionOptions, ModelProvider } from "../../index.js";
import { BaseLLM } from "../index.js";
class Mock extends BaseLLM {
static Completion = "Test Completion";
static providerName: ModelProvider = "mock";
protected async *_streamComplete(
prompt: string,
options: CompletionOptions,
): AsyncGenerator<string> {
yield Mock.Completion;
}
protected async *_streamChat(
messages: ChatMessage[],
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
yield {
role: "assistant",
content: Mock.Completion,
};
}
}
export default Mock;
---
import { ChatMessage, CompletionOptions, ModelProvider } from "../../index.js";
import { BaseLLM } from "../index.js";
class Mock extends BaseLLM {
private static _completion: string = "Test Completion";
static providerName: ModelProvider = "mock";
static get completion(): string {
return Mock._completion;
}
static set completion(value: string) {
Mock._completion = value;
}
protected async *_streamComplete(
prompt: string,
options: CompletionOptions,
): AsyncGenerator<string> {
yield Mock.completion;
}
protected async *_streamChat(
messages: ChatMessage[],
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
yield {
role: "assistant",
content: Mock.completion,
};
}
}
export default Mock;
---
import { ChatMessage, CompletionOptions, ModelProvider } from "../../index.js";
import { BaseLLM } from "../index.js";
class Mock extends BaseLLM {
- static Completion = "Test Completion";
+ private static _completion: string = "Test Completion";
static providerName: ModelProvider = "mock";
+ static get completion(): string {
+ return Mock._completion;
+ }
+
+ static set completion(value: string) {
+ Mock._completion = value;
+ }
+
protected async *_streamComplete(
prompt: string,
options: CompletionOptions,
): AsyncGenerator<string> {
- yield Mock.Completion;
+ yield Mock.completion;
}
protected async *_streamChat(
messages: ChatMessage[],
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
yield {
role: "assistant",
- content: Mock.Completion,
+ content: Mock.completion,
};
}
}
export default Mock;

View file

@ -31,7 +31,8 @@ function linesMatch(lineA: string, lineB: string, linesBetween = 0): boolean {
return (
// Should be more unlikely for lines to fuzzy match if they are further away
(d / Math.max(lineA.length, lineB.length) < 0.5 - linesBetween * 0.05 ||
(d / Math.max(lineA.length, lineB.length) <=
Math.max(0, 0.48 - linesBetween * 0.06) ||
lineA.trim() === lineB.trim()) &&
lineA.trim() !== ""
);

22
core/index.d.ts vendored
View file

@ -121,7 +121,7 @@ export interface ILLM extends LLMOptions {
export type ContextProviderType = "normal" | "query" | "submenu";
export interface ContextProviderDescription {
title: string;
title: ContextProviderName;
displayTitle: string;
description: string;
renderInlineAs?: string;
@ -366,6 +366,7 @@ export interface LLMOptions {
watsonxProjectId?: string;
watsonxStopToken?: string;
watsonxApiVersion?: string;
watsonxFullUrl?: string;
cacheSystemMessage?: boolean;
}
@ -574,7 +575,15 @@ type ContextProviderName =
| "docs"
| "gitlab-mr"
| "os"
| "currentFile";
| "currentFile"
| "outline"
| "continue-proxy"
| "highlights"
| "file"
| "issue"
| "repo-map"
| "url"
| string;
type TemplateType =
| "llama2"
@ -627,6 +636,7 @@ type ModelProvider =
| "msty"
| "watsonx"
| "openrouter"
| "sambanova"
| "nvidia"
| "vllm"
| "mock";
@ -788,6 +798,7 @@ export type EmbeddingsProviderName =
| "gemini"
| "continue-proxy"
| "deepinfra"
| "nvidia"
| "voyage";
export interface EmbedOptions {
@ -924,6 +935,13 @@ interface ExperimentalConfig {
* Automatically read LLM chat responses aloud using system TTS models
*/
readResponseTTS?: boolean;
/**
* If set to true, we will attempt to pull down and install an instance of Chromium
* that is compatible with the current version of Puppeteer.
* This is needed to crawl a large number of documentation sites that are dynamically rendered.
*/
useChromiumForDocsCrawling?: boolean;
}
interface AnalyticsConfig {

View file

@ -0,0 +1,138 @@
import DocsCrawler, { ChromiumInstaller, type PageData } from "./DocsCrawler";
import preIndexedDocs from "./preIndexedDocs";
import { jest } from "@jest/globals";
import FileSystemIde from "../../util/filesystem";
import { testConfigHandler } from "../../test/util/fixtures";
import os from "os";
import { ContinueConfig } from "../..";
// Temporary workaround until we have better caching of Chromium
// download between test runs
const TIMEOUT_MS = 1_000_000_000;
// Overwrite the Chromium download path to `os.tmpdir()`
// so that we don't delete the Chromium install between tests
ChromiumInstaller.PCR_CONFIG = { downloadPath: os.tmpdir() };
// Skipped until we have a better way to cache Chromium installs
// between tests and in CI
describe.skip("DocsCrawler", () => {
const NUM_PAGES_TO_CRAWL = 5;
let config: ContinueConfig;
let mockIde: FileSystemIde;
let chromiumInstaller;
let docsCrawler: DocsCrawler;
beforeAll(async () => {
config = await testConfigHandler.loadConfig();
mockIde = new FileSystemIde(process.cwd());
chromiumInstaller = new ChromiumInstaller(mockIde, config);
docsCrawler = new DocsCrawler(mockIde, config);
// Make sure we have Chromium pulled down before beginning tests
await chromiumInstaller.install();
}, TIMEOUT_MS);
function crawlTest(
urls: string[],
numPagesToCrawl: number = NUM_PAGES_TO_CRAWL,
) {
const numUrlsToTest = 5;
const randomUrls = urls
.sort(() => 0.5 - Math.random())
.slice(0, numUrlsToTest);
randomUrls.forEach((url) => {
it(
`Crawl test for ${url}`,
async () => {
const crawlResults: PageData[] = [];
for await (const page of docsCrawler.crawl(
new URL(url),
NUM_PAGES_TO_CRAWL,
)) {
crawlResults.push(page);
}
expect(crawlResults.length).toBeGreaterThanOrEqual(numPagesToCrawl);
},
TIMEOUT_MS,
);
});
}
describe("GitHub Crawler", () => {
const repoUrl =
"https://github.com/Patrick-Erichsen/test-github-repo-for-crawling";
let crawlResults: PageData[];
beforeAll(async () => {
crawlResults = [];
for await (const page of docsCrawler.crawl(new URL(repoUrl))) {
crawlResults.push(page);
}
}, TIMEOUT_MS);
test("finds expected markdown files", async () => {
expect(crawlResults.some((page) => page.path.endsWith("README.md"))).toBe(
true,
);
expect(
crawlResults.some((page) => page.path.endsWith("docs-depth-1.md")),
).toBe(true);
});
test("html includes the correct content", async () => {
const doc = crawlResults.find((page) =>
page.path.endsWith("docs-depth-1.md"),
);
expect(doc?.content.includes("Test body")).toBe(true);
expect(doc?.content.includes("Test H2 Header")).toBe(true);
});
test("ignores non-markdown files, e.g. `test.js` at the root", async () => {
expect(crawlResults.some((page) => page.path.endsWith("test.js"))).toBe(
false,
);
});
});
describe("Chromium Crawler", () => {
let shouldUseChromiumSpy: any;
beforeAll(() => {
shouldUseChromiumSpy = jest
.spyOn(docsCrawler as any, "shouldUseChromium")
.mockReturnValue(true);
});
afterAll(() => {
shouldUseChromiumSpy.mockRestore();
});
describe("Pre-indexed Docs", () => {
crawlTest(Object.keys(preIndexedDocs));
});
describe("Running list of common sites", () => {
crawlTest([
"https://docs.nestjs.com/",
"https://go.dev/doc/",
"https://clickhouse.com/docs",
"https://www.tensorflow.org/api_docs",
// "https://www.rust-lang.org/learn", TODO: This is failing
"https://docs.anthropic.com/en/docs",
]);
});
});
describe("Cheerio Crawler", () => {
crawlTest(["https://amplified.dev/"], 1);
});
});

View file

@ -1,172 +0,0 @@
import { SpiedFunction } from "jest-mock";
import DocsCrawler, { ChromiumCrawler, type PageData } from "./DocsCrawler";
import preIndexedDocs from "./preIndexedDocs";
import { jest } from "@jest/globals";
// Temporary workaround until we have better caching of Chromium
// download between test runs
const TIMEOUT_MS = 1_000_000_000;
// Skipped until we have a better way to cache Chromium installs
// between tests and in CI
describe.skip("crawl", () => {
beforeAll(async () => {
// Make sure we have Chromium pulled down before beginning tests
await ChromiumCrawler.verifyOrInstallChromium();
}, TIMEOUT_MS);
describe("GitHub Crawler", () => {
const repoUrl =
"https://github.com/Patrick-Erichsen/test-github-repo-for-crawling";
let crawlResults: PageData[];
beforeAll(async () => {
const docsCrawler = new DocsCrawler();
crawlResults = [];
for await (const page of docsCrawler.crawl(new URL(repoUrl))) {
crawlResults.push(page);
}
}, TIMEOUT_MS);
test("finds expected markdown files", async () => {
expect(crawlResults.some((page) => page.path.endsWith("README.md"))).toBe(
true,
);
expect(
crawlResults.some((page) => page.path.endsWith("docs-depth-1.md")),
).toBe(true);
});
test("html includes the correct content", async () => {
const doc = crawlResults.find((page) =>
page.path.endsWith("docs-depth-1.md"),
);
expect(doc?.content.includes("Test body")).toBe(true);
expect(doc?.content.includes("Test H2 Header")).toBe(true);
});
test("ignores non-markdown files, e.g. `test.js` at the root", async () => {
expect(crawlResults.some((page) => page.path.endsWith("test.js"))).toBe(
false,
);
});
});
describe("Chromium Crawler", () => {
it("Pre-indexed Docs", () => {
const results: { [url: string]: boolean } = {};
let totalTests = 0;
let passedTests = 0;
Object.keys(preIndexedDocs).forEach((url) => {
it(
`Crawl test for ${url}`,
async () => {
totalTests++;
let pageFound = false;
try {
const docsCrawler = new DocsCrawler();
for await (const page of docsCrawler.crawl(new URL(url), 1)) {
if (page.url === url) {
pageFound = true;
break;
}
}
} catch (error) {
console.error(`Error crawling ${url}:`, error);
}
results[url] = pageFound;
if (pageFound) {
passedTests++;
console.log(`✅ ${url}`);
} else {
console.log(`❌ ${url}`);
}
expect(pageFound).toBe(true);
},
TIMEOUT_MS,
);
});
});
it(
"succeeds in crawling a list of common sites",
async () => {
const TEST_SITES = [
"https://docs.nestjs.com/",
"https://docs.nestjs.com/",
"https://go.dev/doc/",
"https://clickhouse.com/docs",
"https://www.tensorflow.org/api_docs",
"https://www.rust-lang.org/learn",
"https://docs.anthropic.com/en/docs",
];
const NUM_PAGES_TO_CRAWL = 10;
for (const site of TEST_SITES) {
const crawlResults: PageData[] = [];
const docsCrawler = new DocsCrawler();
for await (const page of docsCrawler.crawl(
new URL(site),
NUM_PAGES_TO_CRAWL,
)) {
crawlResults.push(page);
}
// `toBeGreaterThanOrEqual` because Crawlee doesn't guarantee
// an exact number of pages to crawl since it runs in parallel
expect(crawlResults.length).toBeGreaterThanOrEqual(
NUM_PAGES_TO_CRAWL,
);
}
},
TIMEOUT_MS,
);
});
describe("Cheerio Crawler", () => {
let mockVerifyOrInstallChromium: SpiedFunction<() => Promise<boolean>>;
beforeAll(() => {
mockVerifyOrInstallChromium = jest
.spyOn(ChromiumCrawler, "verifyOrInstallChromium")
.mockResolvedValue(false);
});
afterAll(() => {
mockVerifyOrInstallChromium.mockRestore();
});
it(
"succeeds in crawling a basic site",
async () => {
const NUM_PAGES_TO_CRAWL = 1;
const site = "https://amplified.dev/";
const crawlResults: PageData[] = [];
const docsCrawler = new DocsCrawler();
for await (const page of docsCrawler.crawl(
new URL(site),
NUM_PAGES_TO_CRAWL,
)) {
crawlResults.push(page);
}
expect(crawlResults.length).toBeGreaterThanOrEqual(NUM_PAGES_TO_CRAWL);
},
TIMEOUT_MS,
);
});
});

View file

@ -1,18 +1,18 @@
import { Octokit } from "@octokit/rest";
import * as cheerio from "cheerio";
import * as fs from "fs";
import fetch from "node-fetch";
import { URL } from "node:url";
import { Page } from "puppeteer";
import { Handler, HTTPResponse, Page } from "puppeteer";
import {
editConfigJson,
getChromiumPath,
getContinueUtilsPath,
editConfigJson,
} from "../../util/paths";
// @ts-ignore
// @prettier-ignore
import PCR from "puppeteer-chromium-resolver";
import * as cheerio from "cheerio";
import fetch from "node-fetch";
import { GlobalContext } from "../../util/GlobalContext";
import { ContinueConfig, IDE } from "../..";
export type PageData = {
url: string;
@ -23,10 +23,20 @@ export type PageData = {
class DocsCrawler {
private readonly MAX_REQUESTS_PER_CRAWL = 1000;
private readonly GITHUB_HOST = "github.com";
private useChromiumPromise: Promise<boolean> | undefined = undefined;
private readonly chromiumInstaller: ChromiumInstaller;
constructor() {
this.useChromiumPromise = ChromiumCrawler.verifyOrInstallChromium();
constructor(
private readonly ide: IDE,
private readonly config: ContinueConfig,
) {
this.chromiumInstaller = new ChromiumInstaller(this.ide, this.config);
}
private shouldUseChromium() {
return (
this.config.experimental?.useChromiumForDocsCrawling &&
this.chromiumInstaller.isInstalled()
);
}
async *crawl(
@ -35,11 +45,39 @@ class DocsCrawler {
): AsyncGenerator<PageData> {
if (startUrl.host === this.GITHUB_HOST) {
yield* new GitHubCrawler(startUrl).crawl();
} else if (this.shouldUseChromium()) {
yield* new ChromiumCrawler(startUrl, maxRequestsPerCrawl).crawl();
} else {
if (await this.useChromiumPromise) {
yield* new ChromiumCrawler(startUrl, maxRequestsPerCrawl).crawl();
} else {
yield* new CheerioCrawler(startUrl, maxRequestsPerCrawl).crawl();
let didCrawlSinglePage = false;
for await (const pageData of new CheerioCrawler(
startUrl,
maxRequestsPerCrawl,
).crawl()) {
yield pageData;
didCrawlSinglePage = true;
}
// We assume that if we failed to crawl a single page,
// it was due to an error that using Chromium can resolve
const shouldProposeUseChromium =
!didCrawlSinglePage &&
this.chromiumInstaller.shouldProposeUseChromiumOnCrawlFailure();
if (shouldProposeUseChromium) {
const didInstall =
await this.chromiumInstaller.proposeAndAttemptInstall(
startUrl.toString(),
);
if (didInstall) {
await this.ide.showToast(
"info",
`Successfully installed Chromium! Retrying crawl of: ${startUrl.toString()}`,
);
yield* new ChromiumCrawler(startUrl, maxRequestsPerCrawl).crawl();
}
}
}
}
@ -152,12 +190,15 @@ class CheerioCrawler {
(this.constructor as any).name
}] Starting crawl from: ${url} - Max Depth: ${maxDepth}`,
);
const { baseUrl, basePath } = this.splitUrl(url);
let paths: { path: string; depth: number }[] = [
{ path: basePath, depth: 0 },
];
let index = 0;
while (index < paths.length) {
const batch = paths.slice(index, index + 50);
@ -189,15 +230,12 @@ class CheerioCrawler {
}
}
} catch (e) {
if (e instanceof TypeError) {
console.warn("Error while crawling page: ", e);
} else {
console.error("Error while crawling page: ", e);
}
console.debug("Error while crawling page: ", e);
}
index += batch.length;
}
console.log("Crawl completed");
}
@ -235,7 +273,9 @@ class CheerioCrawler {
$("a").each((_: any, element: any) => {
const href = $(element).attr("href");
if (!href) return;
if (!href) {
return;
}
const parsedUrl = new URL(href, url);
if (parsedUrl.hostname === baseUrl.hostname) {
@ -264,20 +304,29 @@ class CheerioCrawler {
class ChromiumCrawler {
private readonly LINK_GROUP_SIZE = 2;
private static PCR_CONFIG = { downloadPath: getContinueUtilsPath() };
private curCrawlCount = 0;
constructor(
private readonly startUrl: URL,
private readonly maxRequestsPerCrawl: number,
) {}
static setUseChromiumForDocsCrawling(useChromiumForDocsCrawling: boolean) {
editConfigJson((config) => ({
...config,
experimental: {
...config.experimental,
useChromiumForDocsCrawling,
},
}));
}
async *crawl(): AsyncGenerator<PageData> {
console.debug(
`[${(this.constructor as any).name}] Crawling site repo: ${
this.startUrl
}`,
`[${(this.constructor as any).name}] Crawling site: ${this.startUrl}`,
);
const stats = await PCR(ChromiumCrawler.PCR_CONFIG);
const stats = await PCR(ChromiumInstaller.PCR_CONFIG);
const browser = await stats.puppeteer.launch({
args: [
"--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36",
@ -290,56 +339,82 @@ class ChromiumCrawler {
yield* this.crawlSitePages(page, this.startUrl);
} catch (e) {
console.debug("Error getting links: ", e);
console.debug(
"Setting 'useChromiumForDocsCrawling' to 'false' in config.json",
);
ChromiumCrawler.setUseChromiumForDocsCrawling(false);
} finally {
await browser.close();
}
}
/**
* We need to handle redirects manually, otherwise there are race conditions.
*
* https://github.com/puppeteer/puppeteer/issues/3323#issuecomment-2332333573
*/
private async gotoPageAndHandleRedirects(page: Page, url: string) {
const MAX_PAGE_WAIT_MS = 5000;
await page.goto(url, {
timeout: 0,
waitUntil: "networkidle2",
});
let responseEventOccurred = false;
const responseHandler: Handler<HTTPResponse> = (event) =>
(responseEventOccurred = true);
const responseWatcher = new Promise<void>(function (resolve, reject) {
setTimeout(() => {
if (!responseEventOccurred) {
resolve();
} else {
setTimeout(() => resolve(), MAX_PAGE_WAIT_MS);
}
}, 500);
});
page.on("response", responseHandler);
await Promise.race([responseWatcher, page.waitForNavigation()]);
}
private async *crawlSitePages(
page: Page,
curUrl: URL,
visitedLinks: Set<string> = new Set(),
curRequestCount: number = 0,
): AsyncGenerator<PageData> {
if (curRequestCount >= this.maxRequestsPerCrawl) {
console.warn(
`[${
(this.constructor as any).name
}] Max requests per crawl reached. Stopping crawler.`,
);
const urlStr = curUrl.toString();
if (visitedLinks.has(urlStr)) {
return;
}
if (visitedLinks.has(curUrl.toString())) {
return;
}
console.debug(
`[${(this.constructor as any).name}] Crawling page: ${curUrl.toString()}`,
);
await page.goto(curUrl.toString());
await this.gotoPageAndHandleRedirects(page, urlStr);
const htmlContent = await page.content();
const linkGroups = await this.getLinkGroupsFromPage(page, curUrl);
const requestCount = curRequestCount + 1;
this.curCrawlCount++;
visitedLinks.add(curUrl.toString());
visitedLinks.add(urlStr);
yield {
path: curUrl.pathname,
url: curUrl.toString(),
url: urlStr,
content: htmlContent,
};
for (const linkGroup of linkGroups) {
let enqueuedLinkCount = this.curCrawlCount;
for (const link of linkGroup) {
yield* this.crawlSitePages(
page,
new URL(link),
visitedLinks,
requestCount,
);
enqueuedLinkCount++;
console.log({ enqueuedLinkCount, url: this.startUrl });
if (enqueuedLinkCount <= this.maxRequestsPerCrawl) {
yield* this.crawlSitePages(page, new URL(link), visitedLinks);
}
}
}
}
@ -395,34 +470,89 @@ class ChromiumCrawler {
return groups;
}
}
static async verifyOrInstallChromium() {
const globalContext = new GlobalContext();
class ChromiumInstaller {
static PCR_CONFIG = { downloadPath: getContinueUtilsPath() };
// If we previously failed to install Chromium, don't try again
if (globalContext.get("didPrevChromiumInstallFail")) {
return false;
constructor(
private readonly ide: IDE,
private readonly config: ContinueConfig,
) {
if (this.shouldInstallOnStartup()) {
console.log("Installing Chromium");
void this.install();
}
}
if (fs.existsSync(getChromiumPath())) {
return true;
isInstalled() {
return fs.existsSync(getChromiumPath());
}
shouldInstallOnStartup() {
return (
!this.isInstalled() &&
this.config.experimental?.useChromiumForDocsCrawling
);
}
shouldProposeUseChromiumOnCrawlFailure() {
const { experimental } = this.config;
return (
experimental?.useChromiumForDocsCrawling === undefined ||
experimental.useChromiumForDocsCrawling
);
}
async proposeAndAttemptInstall(site: string) {
const userAcceptedInstall = await this.proposeInstall(site);
if (userAcceptedInstall) {
const didInstall = await this.install();
return didInstall;
}
}
async install() {
try {
await PCR(ChromiumCrawler.PCR_CONFIG);
await PCR(ChromiumInstaller.PCR_CONFIG);
ChromiumCrawler.setUseChromiumForDocsCrawling(true);
return true;
} catch (error) {
console.debug("Error installing Chromium : ", error);
console.debug(
`Setting 'didPrevChromiumInstallFail' to 'true' in ${globalContext.constructor.name}`,
"Setting 'useChromiumForDocsCrawling' to 'false' in config.json",
);
globalContext.update("didPrevChromiumInstallFail", true);
ChromiumCrawler.setUseChromiumForDocsCrawling(false);
await this.ide.showToast("error", "Failed to install Chromium");
return false;
}
}
private async proposeInstall(site: string) {
const msg =
`Unable to crawl documentation site: ${site}\n` +
"We recommend installing Chromium. " +
"Download progress can be viewed in the developer console.";
const actionMsg = "Install Chromium";
const res = await this.ide.showToast("warning", msg, actionMsg);
return res === actionMsg;
}
}
export default DocsCrawler;
export { CheerioCrawler, ChromiumCrawler, GitHubCrawler };
export {
CheerioCrawler,
ChromiumCrawler,
ChromiumInstaller as ChromiumInstaller,
GitHubCrawler,
};

View file

@ -31,6 +31,7 @@ import {
SiteIndexingResults,
} from "./preIndexed";
import preIndexedDocs from "./preIndexedDocs";
import { addContextProvider } from "../../config/util";
// Purposefully lowercase because lancedb converts
export interface LanceDbDocsRow {
@ -139,13 +140,34 @@ export default class DocsService {
return !!title;
}
async showAddDocsContextProviderToast() {
const actionMsg = "Add 'docs' context provider";
const res = await this.ide.showToast(
"info",
"Starting docs indexing",
actionMsg,
);
if (res === actionMsg) {
addContextProvider({
name: DocsContextProvider.description.title,
params: {},
});
this.ide.showToast("info", "Successfuly added docs context provider");
}
return res === actionMsg;
}
async indexAllDocs(reIndex: boolean = false) {
if (!this.hasDocsContextProvider()) {
this.ide.showToast(
"info",
"No 'docs' provider configured under 'contextProviders' in config.json",
);
return;
const didAddDocsContextProvider =
await this.showAddDocsContextProviderToast();
if (!didAddDocsContextProvider) {
return;
}
}
const docs = await this.list();
@ -384,7 +406,7 @@ export default class DocsService {
private async init(configHandler: ConfigHandler) {
this.config = await configHandler.loadConfig();
this.docsCrawler = new DocsCrawler();
this.docsCrawler = new DocsCrawler(this.ide, this.config);
const embeddingsProvider = await this.getEmbeddingsProvider();
@ -462,6 +484,8 @@ export default class DocsService {
driver: sqlite3.Database,
});
await db.exec("PRAGMA busy_timeout = 3000;");
await runSqliteMigrations(db);
await db.exec(`CREATE TABLE IF NOT EXISTS ${DocsService.sqlitebTableName} (

View file

@ -49,7 +49,7 @@ class BedrockEmbeddingsProvider extends BaseEmbeddingsProvider {
if (response.body) {
const responseBody = JSON.parse(new TextDecoder().decode(response.body));
return responseBody.embedding;
return [responseBody.embedding];
}
}),
)
@ -62,7 +62,7 @@ class BedrockEmbeddingsProvider extends BaseEmbeddingsProvider {
): any {
const payload = {
"inputText": prompt,
"dimensions": 1024,
"dimensions": 512,
"normalize": true
};

View file

@ -0,0 +1,80 @@
import { Response } from "node-fetch";
import { EmbeddingsProviderName, EmbedOptions } from "../../index.js";
import { withExponentialBackoff } from "../../util/withExponentialBackoff.js";
import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js";
class NvidiaEmbeddingsProvider extends BaseEmbeddingsProvider {
static maxBatchSize = 96;
static providerName: EmbeddingsProviderName = "nvidia";
static defaultOptions: Partial<EmbedOptions> | undefined = {
apiBase: "https://integrate.api.nvidia.com/v1/",
model: "nvidia/nv-embedqa-mistral-7b-v2",
};
async embed(chunks: string[]) {
if (!this.options.apiBase?.endsWith("/")) {
this.options.apiBase += "/";
}
const batchedChunks = [];
for (
let i = 0;
i < chunks.length;
i += NvidiaEmbeddingsProvider.maxBatchSize
) {
batchedChunks.push(
chunks.slice(i, i + NvidiaEmbeddingsProvider.maxBatchSize),
);
}
return (
await Promise.all(
batchedChunks.map(async (batch) => {
if (batch.length === 0) {
return [];
}
// Input list must be non empty and all elements must be non empty, therefore, for all empty elements replace it with a token
const emptyToken = '[EMPTY]';
for (let i = 0; i < batch.length; i++) {
if (batch[i].trim() === '') {
batch[i] = emptyToken;
}
}
const fetchWithBackoff = () =>
withExponentialBackoff<Response>(() =>
this.fetch(new URL("embeddings", this.options.apiBase), {
method: "POST",
body: JSON.stringify({
input: batch,
model: this.options.model,
input_type: 'passage',
truncate: "END",
}),
headers: {
Authorization: `Bearer ${this.options.apiKey}`,
"Content-Type": "application/json",
},
}),
);
const resp = await fetchWithBackoff();
if (!resp.ok) {
throw new Error(await resp.text());
}
const data = (await resp.json()) as any;
return data.data.map(
(result: { embedding: number[] }) => result.embedding,
);
}),
)
).flat();
}
}
export default NvidiaEmbeddingsProvider;

View file

@ -28,6 +28,7 @@ async function embedOne(
}),
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${options.apiKey}`,
},
});

View file

@ -10,6 +10,7 @@ import HuggingFaceTEIEmbeddingsProvider from "./HuggingFaceTEIEmbeddingsProvider
import OllamaEmbeddingsProvider from "./OllamaEmbeddingsProvider.js";
import OpenAIEmbeddingsProvider from "./OpenAIEmbeddingsProvider.js";
import TransformersJsEmbeddingsProvider from "./TransformersJsEmbeddingsProvider.js";
import NvidiaEmbeddingsProvider from "./NvidiaEmbeddingsProvider.js";
import VoyageEmbeddingsProvider from "./VoyageEmbeddingsProvider.js";
type EmbeddingsProviderConstructor = new (
@ -30,5 +31,6 @@ export const allEmbeddingsProviders: Record<
gemini: GeminiEmbeddingsProvider,
"continue-proxy": ContinueProxyEmbeddingsProvider,
deepinfra: DeepInfraEmbeddingsProvider,
nvidia: NvidiaEmbeddingsProvider,
voyage: VoyageEmbeddingsProvider,
};

View file

@ -67,6 +67,7 @@ export const DEFAULT_IGNORE_FILETYPES = [
"*.csv",
"*.uasset",
"*.pdb",
"*.bin",
// "*.prompt", // can be incredibly confusing for the LLM to have another set of instructions injected into the prompt
];
@ -84,6 +85,7 @@ export const DEFAULT_IGNORE_DIRS = [
"node_modules/",
"dist/",
"build/",
"Build/",
"target/",
"out/",
"bin/",

View file

@ -92,6 +92,8 @@ export class SqliteDb {
driver: sqlite3.Database,
});
await SqliteDb.db.exec("PRAGMA busy_timeout = 3000;");
await SqliteDb.createTables(SqliteDb.db);
return SqliteDb.db;

View file

@ -45,6 +45,7 @@ const PROVIDER_HANDLES_TEMPLATING: ModelProvider[] = [
"sagemaker",
"continue-proxy",
"mistral",
"sambanova",
];
const PROVIDER_SUPPORTS_IMAGES: ModelProvider[] = [
@ -108,6 +109,7 @@ const PARALLEL_PROVIDERS: ModelProvider[] = [
"free-trial",
"replicate",
"together",
"sambanova",
];
function llmCanGenerateInParallel(

View file

@ -63,7 +63,7 @@ export abstract class BaseLLM implements ILLM {
}
supportsCompletions(): boolean {
if (this.providerName === "openai") {
if (["openai", "azure"].includes(this.providerName)) {
if (
this.apiBase?.includes("api.groq.com") ||
this.apiBase?.includes("api.mistral.ai") ||
@ -76,7 +76,7 @@ export abstract class BaseLLM implements ILLM {
return false;
}
}
if (["groq", "mistral"].includes(this.providerName)) {
if (["groq", "mistral", "deepseek"].includes(this.providerName)) {
return false;
}
return true;
@ -118,6 +118,7 @@ export abstract class BaseLLM implements ILLM {
watsonxProjectId?: string;
watsonxStopToken?: string;
watsonxApiVersion?: string;
watsonxFullUrl?: string;
cacheSystemMessage?: boolean;
@ -180,6 +181,7 @@ export abstract class BaseLLM implements ILLM {
this.watsonxProjectId = options.watsonxProjectId;
this.watsonxStopToken = options.watsonxStopToken;
this.watsonxApiVersion = options.watsonxApiVersion;
this.watsonxFullUrl = options.watsonxFullUrl;
this.cacheSystemMessage = options.cacheSystemMessage;

View file

@ -18,7 +18,7 @@ class Bedrock extends BaseLLM {
static defaultOptions: Partial<LLMOptions> = {
region: "us-east-1",
model: "anthropic.claude-3-sonnet-20240229-v1:0",
contextLength: 200_000
contextLength: 200_000,
};
profile?: string | undefined;
@ -49,8 +49,10 @@ class Bedrock extends BaseLLM {
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
const credentials = await this._getCredentials();
const client = new BedrockRuntimeClient({
region: this.region,
endpoint: this.apiBase,
credentials: {
accessKeyId: credentials.accessKeyId,
secretAccessKey: credentials.secretAccessKey,
@ -58,6 +60,27 @@ class Bedrock extends BaseLLM {
},
});
let config_headers =
this.requestOptions && this.requestOptions.headers
? this.requestOptions.headers
: {};
// AWS SigV4 requires strict canonicalization of headers.
// DO NOT USE "_" in your header name. It will return an error like below.
// "The request signature we calculated does not match the signature you provided."
client.middlewareStack.add(
(next) => async (args: any) => {
args.request.headers = {
...args.request.headers,
...config_headers,
};
return next(args);
},
{
step: "build",
},
);
const input = this._generateConverseInput(messages, options);
const command = new ConverseStreamCommand(input);
const response = await client.send(command);

View file

@ -55,12 +55,24 @@ class SageMaker extends BaseLLM {
let position;
while ((position = buffer.indexOf("\n")) >= 0) {
const line = buffer.slice(0, position);
const data = JSON.parse(line.replace(/^data:/, ""));
if ("choices" in data) {
yield data.choices[0].delta.content;
}
else if ("token" in data) {
yield data.token.text;
try {
const data = JSON.parse(line.replace(/^data:/, ''));
let text = undefined;
if ("choices" in data) {
if ("delta" in data.choices[0]){
text = data.choices[0].delta.content;
}
else{
text = data.choices[0].text;
}
}
else if ("token" in data) {
text = data.token.text;
}
if (text !== undefined) {
yield text;
}
} catch (e) {
}
buffer = buffer.slice(position + 1);
}
@ -94,12 +106,24 @@ class SageMaker extends BaseLLM {
let position;
while ((position = buffer.indexOf("\n")) >= 0) {
const line = buffer.slice(0, position);
const data = JSON.parse(line.replace(/^data:/, ""));
if ("choices" in data) {
yield { role: "assistant", content: data.choices[0].delta.content };
}
else if ("token" in data) {
yield { role: "assistant", content: data.token.text };
try {
const data = JSON.parse(line.replace(/^data:/, ''));
let text = undefined;
if ("choices" in data) {
if ("delta" in data.choices[0]){
text = data.choices[0].delta.content;
}
else{
text = data.choices[0].text;
}
}
else if ("token" in data) {
text = data.token.text;
}
if (text !== undefined) {
yield { role: "assistant", content: text };
}
} catch (e) {
}
buffer = buffer.slice(position + 1);
}
@ -189,6 +213,7 @@ class CompletionAPIToolkit implements SageMakerModelToolkit {
): InvokeEndpointWithResponseStreamCommand {
const payload = {
inputs: prompt,
prompt: prompt,
parameters: this.sagemaker.completionOptions,
stream: true,
};

View file

@ -0,0 +1,22 @@
import type { LLMOptions, ModelProvider } from "../../index.js";
import OpenAI from "./OpenAI.js";
class SambaNova extends OpenAI {
static providerName: ModelProvider = "sambanova";
static defaultOptions: Partial<LLMOptions> = {
apiBase: "https://api.sambanova.ai/v1/",
};
private static MODEL_IDS: { [name: string]: string } = {
"llama3.1-8b": "Meta-Llama-3.1-8B-Instruct",
"llama3.1-70b": "Meta-Llama-3.1-70B-Instruct",
"llama3.1-405b": "Meta-Llama-3.1-405B-Instruct",
};
protected _convertModelName(model: string) {
return SambaNova.MODEL_IDS[model] || this.model;
}
}
export default SambaNova;

View file

@ -84,6 +84,10 @@ class WatsonX extends BaseLLM {
}
}
getWatsonxEndpoint(): string {
return this.watsonxFullUrl ?? `${this.watsonxUrl}/ml/v1/text/generation_stream?version=${this.watsonxApiVersion}`;
}
static providerName: ModelProvider = "watsonx";
protected _convertMessage(message: ChatMessage) {
@ -186,8 +190,9 @@ class WatsonX extends BaseLLM {
const stopToken =
this.watsonxStopToken ??
(options.model?.includes("granite") ? "<|im_end|>" : undefined);
const url = this.getWatsonxEndpoint();
var response = await this.fetch(
`${this.watsonxUrl}/ml/v1/text/generation_stream?version=${this.watsonxApiVersion}`,
url,
{
method: "POST",
headers: {

View file

@ -36,6 +36,7 @@ import OpenAI from "./OpenAI";
import OpenRouter from "./OpenRouter";
import Replicate from "./Replicate";
import SageMaker from "./SageMaker";
import SambaNova from "./SambaNova";
import TextGenWebUI from "./TextGenWebUI";
import Together from "./Together";
import Vllm from "./Vllm";
@ -75,6 +76,7 @@ const LLMs = [
OpenRouter,
Nvidia,
Vllm,
SambaNova,
Mock,
];

View file

@ -5,7 +5,6 @@ import { EmbeddingsProvider } from "../index.js";
export type GlobalContextType = {
indexingPaused: boolean;
selectedTabAutocompleteModel: string;
didPrevChromiumInstallFail: boolean;
lastSelectedProfileForWorkspace: { [workspaceIdentifier: string]: string };
/**
* This is needed to handle the case where a JetBrains user has created

138
core/util/dedent.test.ts Normal file
View file

@ -0,0 +1,138 @@
import { dedent } from "./index";
describe("dedent function", () => {
it("should remove common leading whitespace from all lines", () => {
const result = dedent`
Hello
World
!
`;
expect(result).toBe("Hello\n World\n !");
});
it("should handle strings with no indentation", () => {
const result = dedent`Hello
World
!`;
expect(result).toBe("Hello\nWorld\n!");
});
it("should handle strings with mixed indentation", () => {
const result = dedent`
Hello
World
!
`;
expect(result).toBe(" Hello\nWorld\n !");
});
it("should remove leading and trailing empty lines", () => {
const result = dedent`
Hello
World
`;
expect(result).toBe("Hello\nWorld");
});
it("should handle empty strings", () => {
const result = dedent``;
expect(result).toBe("");
});
it("should handle strings with only whitespace", () => {
const result = dedent`
`;
expect(result).toBe("");
});
it.skip("should handle strings with tabs", () => {
const result = dedent`
\tHello
\t\tWorld
\t\t\t!
`;
expect(result).toBe("\tHello\n\t\tWorld\n\t\t\t!");
});
it("should handle interpolated values", () => {
const world = "World";
const result = dedent`
Hello ${world}
How are you?
`;
expect(result).toBe("Hello World\n How are you?");
});
it("should handle multiple interpolated values", () => {
const greeting = "Hello";
const name = "Alice";
const question = "How are you?";
const result = dedent`
${greeting} ${name}
${question}
`;
expect(result).toBe("Hello Alice\n How are you?");
});
it("should handle interpolated values with different indentation", () => {
const value1 = "foo";
const value2 = "bar";
const result = dedent`
${value1}
${value2}
`;
expect(result).toBe("foo\n bar");
});
it("should handle a single line with indentation", () => {
const result = dedent` Hello World!`;
expect(result).toBe("Hello World!");
});
it("should handle a string with only one non-empty line", () => {
const result = dedent`
Hello World!
`;
expect(result).toBe("Hello World!");
});
it("should handle a string with Unicode characters", () => {
const result = dedent`
こんにちは
世界
`;
expect(result).toBe("こんにちは\n 世界");
});
it("should handle a string with emoji", () => {
const result = dedent`
🌍
🌎
🌏
`;
expect(result).toBe("🌍\n 🌎\n 🌏");
});
it.skip("should handle a string with CRLF line endings", () => {
const result = dedent`
Hello\r
World\r
`;
expect(result).toBe("Hello\r\n World");
});
it("should not count empty lines in the minimum indentation", () => {
const result = dedent`
Hello
World
`;
expect(result).toBe("Hello\n\nWorld");
});
});

View file

@ -79,6 +79,8 @@ export class DevDataSqliteDb {
driver: sqlite3.Database,
});
await DevDataSqliteDb.db.exec("PRAGMA busy_timeout = 3000;");
await DevDataSqliteDb.createTables(DevDataSqliteDb.db!);
return DevDataSqliteDb.db;

View file

@ -48,7 +48,10 @@ class HistoryManager {
(session) => session.sessionId !== sessionId,
);
fs.writeFileSync(sessionsListFile, JSON.stringify(sessionsList));
fs.writeFileSync(
sessionsListFile,
JSON.stringify(sessionsList, undefined, 2),
);
}
load(sessionId: string): PersistedSessionInfo {
@ -77,7 +80,7 @@ class HistoryManager {
// Save the main session json file
fs.writeFileSync(
getSessionFilePath(session.sessionId),
JSON.stringify(session),
JSON.stringify(session, undefined, 2),
);
// Read and update the sessions list
@ -117,7 +120,10 @@ class HistoryManager {
sessionsList.push(sessionInfo);
}
fs.writeFileSync(sessionsListFilePath, JSON.stringify(sessionsList));
fs.writeFileSync(
sessionsListFilePath,
JSON.stringify(sessionsList, undefined, 2),
);
} catch (error) {
if (error instanceof SyntaxError) {
throw new Error(

View file

@ -2,19 +2,19 @@ export function removeQuotesAndEscapes(output: string): string {
output = output.trim();
// Replace smart quotes
output = output.replace("“", "\"");
output = output.replace("”", "\"");
output = output.replace("“", '"');
output = output.replace("”", '"');
output = output.replace("‘", "'");
output = output.replace("’", "'");
// Remove escapes
output = output.replace("\\\"", "\"");
output = output.replace('\\"', '"');
output = output.replace("\\'", "'");
output = output.replace("\\n", "\n");
output = output.replace("\\t", "\t");
output = output.replace("\\\\", "\\");
while (
(output.startsWith("\"") && output.endsWith("\"")) ||
(output.startsWith('"') && output.endsWith('"')) ||
(output.startsWith("'") && output.endsWith("'"))
) {
output = output.slice(1, -1);
@ -120,7 +120,9 @@ export function getUniqueFilePath(
}
export function shortestRelativePaths(paths: string[]): string[] {
if (paths.length === 0) {return [];}
if (paths.length === 0) {
return [];
}
const partsLengths = paths.map((x) => x.split(SEP_REGEX).length);
const currentRelativePaths = paths.map(getBasename);
@ -135,7 +137,9 @@ export function shortestRelativePaths(paths: string[]): string[] {
const firstDuplicatedPath = currentRelativePaths.find(
(x, i) => isDuplicated[i],
);
if (!firstDuplicatedPath) {break;}
if (!firstDuplicatedPath) {
break;
}
currentRelativePaths.forEach((x, i) => {
if (x === firstDuplicatedPath) {
@ -270,3 +274,33 @@ export function deduplicateArray<T>(
}
export type TODO = any;
export function dedent(strings: TemplateStringsArray, ...values: any[]) {
let result = strings.reduce(
(acc, str, i) => acc + str + (values[i] || ""),
"",
);
result = result.replace(/^\n/, "").replace(/\n\s*$/, "");
let lines = result.split("\n");
// Remove leading white-space-only lines
while (lines.length > 0 && lines[0].trim() === "") {
lines.shift();
}
// Remove trailing white-space-only lines
while (lines.length > 0 && lines[lines.length - 1].trim() === "") {
lines.pop();
}
const minIndent = lines.reduce((min, line) => {
if (line.trim() === "") {
// Don't consider empty lines when calculating indentation
return min;
}
const match = line.match(/^\s*/);
return Math.min(min, match ? match[0].length : Infinity);
}, Infinity);
return lines.map((line) => line.slice(minIndent)).join("\n");
}

View file

@ -81,6 +81,9 @@ export async function* streamDiffLines(
oldLines = [];
}
// Trim end of oldLines, otherwise we have trailing \r on every line for CRLF files
oldLines = oldLines.map((line) => line.trimEnd());
const prompt = constructPrompt(
prefix,
highlighted,

View file

@ -138,6 +138,26 @@ Type '@issue' to reference the conversation in a GitHub issue. Make sure to incl
}
```
#### Using Github Enterprise Server
When using with Github Enterprise Server, you can set the `domain` parameter to your server's hostname. By default this is set to `github.com`.
```json
{
"name": "issue",
"params": {
"repos": [
{
"owner": "continuedev",
"repo": "continue"
}
],
"githubToken": "ghp_xxx",
"domain": "github.acme-inc.com"
}
}
```
### GitLab Merge Request
Type `@gitlab-mr` to reference an open MR for this branch on GitLab.

View file

@ -68,6 +68,21 @@ Whether to use re-ranking, which will allow initial selection of `nRetrieve` res
We also support other methods of generating embeddings, which can be configured with the `"embeddingsProvider"` property in `config.json`. We currently have built-in support for the following providers:
### NVIDIA
NVIDIA provides text embedding models as NIMs (NVIDIA Inference Models) that generate semantically meaningful vector representations of text.
Sample configuration for the `nvidia/nv-embedqa-mistral-7b-v2` model. This is the default model for the nvidia provider.
```json title="~/.continue/config.json"
{
"embeddingsProvider": {
"provider": "nvidia",
"model": "nvidia/nv-embedqa-mistral-7b-v2",
"apiKey": "YOUR_API_KEY"
}
}
```
Some of the other key NVIDIA embedding NIMs are: `nvidia/nv-embedqa-e5-v5` and `baai/bge-m3`. See Nvidia's [catalog](https://build.nvidia.com/search?term=embeddings) for more available models.
### Transformers.js (currently VS Code only)
[Transformers.js](https://huggingface.co/docs/transformers.js/index) is a JavaScript port of the popular [Transformers](https://huggingface.co/transformers/) library. It allows embeddings to be calculated locally in the browser (or in this case inside of the sidebar of your IDE). The model used is `all-MiniLM-L6-v2`, which is shipped alongside the Continue extension and generates embeddings of size 384.

View file

@ -24,10 +24,6 @@ To enable the `@docs` context provider, you need to add it to the list of contex
The `@docs` context provider works by crawling specified documentation sites, generating embeddings, and storing them locally for you. This process allows for quick and efficient access to your documentation content.
:::info
Note that we download and install a headless browser, Chromium, to crawl documentation sites. This is required to execute JavaScript on the page and ensure that we can crawl all the content.
:::
1. We crawl the specified documentation site
2. Generate embeddings for the content
3. Store the embeddings locally on your machine
@ -71,6 +67,18 @@ The configuration schema is as follows:
- `rootUrl`: The base URL of the documentation site, used to determine which pages to index.
- `faviconUrl`: The URL of the site's favicon, used for visual identification in the UI.
## Crawling dynamically generated sites with `useChromiumForDocsCrawling`
By default, we use a lighter weight tool to crawl documentation sites that cannot render sites that are dynamically generated using JavaScript.
If you want to crawl a site that is dynamically generated, or you get an error while attempting to crawl a site, you can enable the experimental `useChromiumForDocsCrawling` feature in your `config.json`. This will download and install Chromium to `~/.continue/.utils`.
```json title=config.json
"experimental": {
"useChromiumForDocsCrawling": true
}
```
## FAQ
### How often is the indexed content updated?

View file

@ -0,0 +1,18 @@
# SambaNova Cloud
The SambaNova Cloud is a cloud platform for running large AI models with the world record Llama 3.1 70B/405B performance. You can sign up [here](https://cloud.sambanova.ai/), copy your API key on the initial welcome screen, and then hit the play button on any model from the [model list](https://community.sambanova.ai/t/quick-start-guide/104). Change `~/.continue/config.json` to look like this:
```json title="~/.continue/config.json"
{
"models": [
{
"title": "SambaNova Llama 3.1 405B",
"provider": "sambanova",
"model": "llama3.1-405b",
"apiKey": "YOUR_API_KEY"
}
]
}
```
[View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/SambaNova.ts)

Binary file not shown.

After

Width:  |  Height:  |  Size: 858 KiB

View file

@ -20,16 +20,16 @@ You can configure Azure OpenAI service through the UI, or you can configure it m
"apiBase": "<YOUR_DEPLOYMENT_BASE>",
"engine": "<YOUR_ENGINE>",
"apiVersion": "<YOUR_API_VERSION>",
"apiType": "openai",
"apiType": "azure",
"apiKey": "<MY_API_KEY>"
}]
```
To find out the information from _Azure AI Studio_, select the model that you would like to connect. Under the _Endpoint_ section and capture the Target URI.
For example, Target URI of https://just-an-example.openai.azure.com/openai/deployments/gpt-4o/chat/completions?api-version=2023-13-15-preview
For example, Target URI of https://just-an-example.openai.azure.com/openai/deployments/gpt-4o-deployment-name/chat/completions?api-version=2023-13-15-preview
Maps to:
- model = gpt-4o
- engine = gpt-4o
- engine = gpt-4o-deployment-name
- apiVersion = 2023-13-15-preview
- apiBase = just-an-example.openai.azure.com
- apiBase = https://just-an-example.openai.azure.com/

View file

@ -34,5 +34,47 @@ To authenticate to your watsonx.ai Software instance with Continue, you can use
- Set **watsonx Project ID** to your watsonx project ID.
- Set **watsonx API Key** to your watsonx Username and Password using `username:password` as format.
## Configuration
Add the following configuration to your `config.json` file to use the watsonx provider. Fill in the `watsonxCreds` with the authentication details you obtained in the setup step.
```json title="~/.continue/config.json"
{
"models": [
{
"model": "model ID",
"title": "watsonx - Model Name",
"watsonxUrl": "watsonx endpoint e.g. https://us-south.ml.cloud.ibm.com",
"watsonxProjectId": "PROJECT_ID",
"watsonxCreds": "API_KEY/ZENAPI_KEY/USERNAME:PASSWORD",
"watsonxApiVersion": "2023-05-29",
"provider": "watsonx"
},
]
}
```
`watsonxAPIVersion` is optional and defaults to the latest version.
### Configuration Options
Add the full watsonx URL to `watsonxFullUrl` if you are using a custom endpoint. When `watsonxFullUrl` is set, `watsonxUrl` and `watsonxApiVersion` are ignored.
```json title="~/.continue/config.json"
{
"models": [
{
"model": "model ID",
"title": "watsonx - Model Name",
"watsonxUrl": "watsonx endpoint e.g. https://us-south.ml.cloud.ibm.com",
"watsonxProjectId": "PROJECT_ID",
"watsonxCreds": "API_KEY",
"watsonxApiVersion": "2023-05-29",
"provider": "watsonx",
"watsonxFullUrl": "https://us-south.ml.cloud.ibm.com/m1/v1/text/generation"
},
]
}
```
## Usage
![usage-gif](../Model%20Providers/assets/watsonx1.gif)
![usage-gif](../Model%20Providers/assets/watsonx2.gif)

View file

@ -80,6 +80,7 @@ You can run open-source LLMs with cloud services like:
- [Replicate](../reference/Model%20Providers/replicatellm.md)
- [Deepinfra](../reference/Model%20Providers/deepinfra.md)
- [Groq](../reference/Model%20Providers/openai.md) (OpenAI compatible API)
- [SambaNova](../reference/Model%20Providers/sambanova.md)
### Commercial models
@ -87,7 +88,7 @@ You can use commercial LLMs via APIs using:
- [Anthrophic API](../reference/Model%20Providers/anthropicllm.md)
- [OpenAI API](../reference/Model%20Providers/openai.md)
- [Azure OpenAI Service](../reference/Model%20Providers/openai.md)
- [Azure OpenAI Service](../reference/Model%20Providers/azure.md)
- [Amazon Bedrock](../reference/Model%20Providers/bedrock.md)
- [Google Gemini API](../reference/Model%20Providers/geminiapi.md)
- [Mistral API](../reference/Model%20Providers/mistral.md)

View file

@ -92,3 +92,24 @@ Replicate makes it easy to host and run open-source AI with an API.
]
}
```
## SambaNova
SambaNova Cloud provides world record Llama3.1 70B/405B serving.
1. Create an account [here](https://cloud.sambanova.ai/)
2. Copy your API key
3. Update your Continue config file like this:
```json title="~/.continue/config.json"
{
"models": [
{
"title": "SambaNova Llama 3.1 405B",
"provider": "sambanova",
"model": "llama3.1-405b",
"apiKey": "YOUR_API_KEY"
}
]
}
```

View file

@ -192,6 +192,7 @@
"msty",
"watsonx",
"openrouter",
"sambanova",
"nvidia",
"vllm"
],
@ -243,10 +244,10 @@
"type": "string"
},
"region": {
"title": "Region",
"description": "The region where the model is hosted",
"type": "string"
},
"title": "Region",
"description": "The region where the model is hosted",
"type": "string"
},
"profile": {
"title": "Profile",
"description": "The AWS security profile to use",
@ -398,7 +399,8 @@
"huggingface-inference-api",
"replicate",
"together",
"cloudflare"
"cloudflare",
"sambanova"
]
}
},
@ -412,9 +414,7 @@
"if": {
"properties": {
"provider": {
"enum": [
"bedrockimport"
]
"enum": ["bedrockimport"]
}
},
"required": ["provider"]
@ -1285,6 +1285,9 @@
"watsonxStopToken": {
"type": "string"
},
"watsonxFullUrl": {
"type": "string"
},
"model": {
"enum": [
"ibm/granite-13b-chat-v2",
@ -1297,6 +1300,31 @@
},
"required": ["watsonxUrl", "watsonxProjectId"]
}
},
{
"if": {
"properties": {
"provider": {
"enum": ["sambanova"]
}
},
"required": ["provider"]
},
"then": {
"properties": {
"model": {
"anyOf": [
{
"enum": ["llama3.1-8b", "llama3.1-70b", "llama3.1-405b"]
},
{
"type": "string"
}
],
"markdownDescription": "Select a pre-defined option."
}
}
}
}
]
},
@ -2060,8 +2088,7 @@
"cohere",
"free-trial",
"gemini",
"voyage",
"bedrock"
"voyage"
]
},
"model": {
@ -2102,20 +2129,7 @@
"if": {
"properties": {
"provider": {
"enum": ["cohere", "voyage"]
}
},
"required": ["provider"]
},
"then": {
"required": ["apiKey"]
}
},
{
"if": {
"properties": {
"provider": {
"enum": ["gemini"]
"enum": ["cohere", "voyage", "nvidia", "gemini"]
}
},
"required": ["provider"]

View file

@ -11,6 +11,7 @@ plugins {
alias(libs.plugins.changelog) // Gradle Changelog Plugin
alias(libs.plugins.qodana) // Gradle Qodana Plugin
alias(libs.plugins.kover) // Gradle Kover Plugin
kotlin("plugin.serialization") version "1.8.0"
}
group = properties("pluginGroup").get()
@ -38,6 +39,7 @@ dependencies {
exclude(group = "org.slf4j", module = "slf4j-api")
}
implementation("com.posthog.java:posthog:1.+")
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.5.0")
}
@ -84,6 +86,9 @@ tasks {
from("../../binary/bin") {
into("${intellij.pluginName.get()}/core/")
}
from("../vscode/node_modules/@vscode/ripgrep") {
into("${intellij.pluginName.get()}/ripgrep/")
}
}
wrapper {
@ -144,7 +149,7 @@ tasks {
// Specify pre-release label to publish the plugin in a custom Release Channel automatically. Read more:
// https://plugins.jetbrains.com/docs/intellij/deployment.html#specifying-a-release-channel
channels.set(listOf(environment("RELEASE_CHANNEL").getOrElse("eap")))
// We always hide the stable releases until a few days of EAP have proven them stable
// hidden = environment("RELEASE_CHANNEL").map { it == "stable" }.getOrElse(false)
}

View file

@ -4,7 +4,7 @@ pluginGroup = com.github.continuedev.continueintellijextension
pluginName = continue-intellij-extension
pluginRepositoryUrl = https://github.com/continuedev/continue
# SemVer format -> https://semver.org
pluginVersion = 0.0.67
pluginVersion = 0.0.68
# Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html
pluginSinceBuild = 223

View file

@ -68,20 +68,20 @@ class ContinuePluginStartupActivity : StartupActivity, Disposable, DumbAware {
removeShortcutFromAction(getPlatformSpecificKeyStroke("J"))
removeShortcutFromAction(getPlatformSpecificKeyStroke("shift J"))
project.messageBus.connect().subscribe(
ToolWindowManagerListener.TOPIC,
object : ToolWindowManagerListener {
override fun stateChanged(toolWindowManager: ToolWindowManager) {
if (toolWindowManager.activeToolWindowId == TerminalToolWindowFactory.TOOL_WINDOW_ID
|| TerminalView.getInstance(project).isNotAvailable()
) {
project.service<TerminalActivityTrackingService>().update(
TerminalView.getInstance(project).widgets
)
}
}
}
)
// project.messageBus.connect().subscribe(
// ToolWindowManagerListener.TOPIC,
// object : ToolWindowManagerListener {
// override fun stateChanged(toolWindowManager: ToolWindowManager) {
// if (toolWindowManager.activeToolWindowId == TerminalToolWindowFactory.TOOL_WINDOW_ID
// || TerminalView.getInstance(project).isNotAvailable()
// ) {
// project.service<TerminalActivityTrackingService>().update(
// TerminalView.getInstance(project).widgets
// )
// }
// }
// }
// )
ApplicationManager.getApplication().executeOnPooledThread {
initializePlugin(project)
@ -134,6 +134,8 @@ class ContinuePluginStartupActivity : StartupActivity, Disposable, DumbAware {
showTutorial(project)
}
settings.addRemoteSyncJob()
val ideProtocolClient = IdeProtocolClient(
continuePluginService,
defaultStrategy,

View file

@ -81,17 +81,32 @@ fun getContinueGlobalPath(): String {
return continuePath.toString()
}
fun getConfigJsonPath(): String {
val path = Paths.get(getContinueGlobalPath(), "config.json")
fun getContinueRemoteConfigPath(remoteHostname: String): String {
val path = Paths.get(getContinueGlobalPath(), ".configs")
if (Files.notExists(path)) {
Files.createDirectories(path)
}
return Paths.get(path.toString(), remoteHostname).toString()
}
fun getConfigJsonPath(remoteHostname: String? = null): String {
val path = Paths.get(
if (remoteHostname != null) getContinueRemoteConfigPath(remoteHostname) else getContinueGlobalPath(),
"config.json"
)
if (Files.notExists(path)) {
Files.createFile(path)
Files.writeString(path, DEFAULT_CONFIG);
Files.writeString(path, if (remoteHostname == null) DEFAULT_CONFIG else "{}")
}
return path.toString()
}
fun getConfigJsPath(): String {
val path = Paths.get(getContinueGlobalPath(), "config.js")
fun getConfigJsPath(remoteHostname: String? = null): String {
val path = Paths.get(
if (remoteHostname != null) getContinueRemoteConfigPath(remoteHostname) else getContinueGlobalPath(),
"config.js"
)
if (Files.notExists(path)) {
Files.createFile(path)
Files.writeString(path, DEFAULT_CONFIG_JS);

View file

@ -14,6 +14,9 @@ import com.google.gson.reflect.TypeToken
import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer
import com.intellij.codeInsight.daemon.impl.DaemonCodeAnalyzerImpl
import com.intellij.codeInsight.daemon.impl.HighlightInfo
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.util.ExecUtil
import com.intellij.ide.plugins.PluginManager
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.lang.annotation.HighlightSeverity
import com.intellij.openapi.Disposable
@ -52,6 +55,7 @@ import java.awt.datatransfer.StringSelection
import java.io.*
import java.net.NetworkInterface
import java.nio.charset.Charset
import java.nio.file.Paths
import java.util.*
@ -197,6 +201,7 @@ class IdeProtocolClient (
private val project: Project
): DumbAware {
val diffManager = DiffManager(project)
private val ripgrep: String
init {
initIdeProtocol()
@ -205,6 +210,20 @@ class IdeProtocolClient (
VirtualFileManager.getInstance().addAsyncFileListener(AsyncFileSaveListener(this), object : Disposable {
override fun dispose() {}
})
val myPluginId = "com.github.continuedev.continueintellijextension"
val pluginDescriptor = PluginManager.getPlugin(PluginId.getId(myPluginId)) ?: throw Exception("Plugin not found")
val pluginPath = pluginDescriptor.pluginPath
val osName = System.getProperty("os.name").toLowerCase()
val os = when {
osName.contains("mac") || osName.contains("darwin") -> "darwin"
osName.contains("win") -> "win32"
osName.contains("nix") || osName.contains("nux") || osName.contains("aix") -> "linux"
else -> "linux"
}
ripgrep = Paths.get(pluginPath.toString(), "ripgrep", "bin", "rg" + (if (os == "win32") ".exe" else "")).toString()
}
private fun send(messageType: String, data: Any?, messageId: String? = null) {
@ -592,7 +611,8 @@ class IdeProtocolClient (
}
"getSearchResults" -> {
respond("")
val query = (data as Map<String, Any>)["query"] as String
respond(search(query))
}
// Other
@ -1018,6 +1038,12 @@ class IdeProtocolClient (
return contents
}
private fun search(query: String): String {
val command = GeneralCommandLine(ripgrep, "-i", "-C", "2", "--", query, ".")
command.setWorkDirectory(project.basePath)
return ExecUtil.execAndGetOutput(command).stdout ?: ""
}
}
interface TextSelectionStrategy {

View file

@ -1,12 +1,24 @@
package com.github.continuedev.continueintellijextension.services
import com.github.continuedev.continueintellijextension.constants.getConfigJsPath
import com.github.continuedev.continueintellijextension.constants.getConfigJsonPath
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.*
import com.intellij.openapi.options.Configurable
import com.intellij.openapi.project.DumbAware
import com.intellij.util.concurrency.AppExecutorUtil
import com.intellij.util.messages.Topic
import kotlinx.serialization.Serializable
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
import okhttp3.OkHttpClient
import okhttp3.Request
import java.awt.GridBagConstraints
import java.awt.GridBagLayout
import java.io.File
import java.io.IOException
import java.util.concurrent.ScheduledFuture
import java.util.concurrent.TimeUnit
import javax.swing.*
class ContinueSettingsComponent: DumbAware {
@ -53,6 +65,12 @@ class ContinueSettingsComponent: DumbAware {
}
}
@Serializable
class ContinueRemoteConfigSyncResponse {
var configJson: String? = null
var configJs: String? = null
}
@State(
name = "com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings",
storages = [Storage("ContinueExtensionSettings.xml")]
@ -73,6 +91,8 @@ open class ContinueExtensionSettings : PersistentStateComponent<ContinueExtensio
var continueState: ContinueState = ContinueState()
private var remoteSyncFuture: ScheduledFuture<*>? = null
override fun getState(): ContinueState {
return continueState
}
@ -85,6 +105,72 @@ open class ContinueExtensionSettings : PersistentStateComponent<ContinueExtensio
val instance: ContinueExtensionSettings
get() = ServiceManager.getService(ContinueExtensionSettings::class.java)
}
// Sync remote config from server
private fun syncRemoteConfig() {
val state = instance.continueState
if (state.remoteConfigServerUrl != null) {
// download remote config as json file
val client = OkHttpClient()
val baseUrl = state.remoteConfigServerUrl?.removeSuffix("/")
val requestBuilder = Request.Builder().url("${baseUrl}/sync")
if (state.userToken != null) {
requestBuilder.addHeader("Authorization", "Bearer ${state.userToken}")
}
val request = requestBuilder.build()
var configResponse: ContinueRemoteConfigSyncResponse? = null
try {
client.newCall(request).execute().use { response ->
if (!response.isSuccessful) throw IOException("Unexpected code $response")
response.body?.string()?.let { responseBody ->
try {
configResponse =
Json.decodeFromString<ContinueRemoteConfigSyncResponse>(responseBody)
} catch (e: Exception) {
e.printStackTrace()
return
}
}
}
} catch (e: IOException) {
e.printStackTrace()
return
}
if (configResponse?.configJson?.isNotEmpty()!!) {
val file = File(getConfigJsonPath(request.url.host))
file.writeText(configResponse!!.configJson!!)
}
if (configResponse?.configJs?.isNotEmpty()!!) {
val file = File(getConfigJsPath(request.url.host))
file.writeText(configResponse!!.configJs!!)
}
}
}
// Create a scheduled task to sync remote config every `remoteConfigSyncPeriod` minutes
fun addRemoteSyncJob() {
if (remoteSyncFuture != null) {
remoteSyncFuture?.cancel(false)
}
instance.remoteSyncFuture = AppExecutorUtil.getAppScheduledExecutorService()
.scheduleWithFixedDelay(
{ syncRemoteConfig() },
0,
continueState.remoteConfigSyncPeriod.toLong(),
TimeUnit.MINUTES
)
}
}
interface SettingsListener {
@ -124,6 +210,7 @@ class ContinueExtensionConfigurable : Configurable {
settings.continueState.displayEditorTooltip = mySettingsComponent?.displayEditorTooltip?.isSelected ?: true
ApplicationManager.getApplication().messageBus.syncPublisher(SettingsListener.TOPIC).settingsUpdated(settings.continueState)
ContinueExtensionSettings.instance.addRemoteSyncJob()
}
override fun reset() {
@ -134,6 +221,8 @@ class ContinueExtensionConfigurable : Configurable {
mySettingsComponent?.enableTabAutocomplete?.isSelected = settings.continueState.enableTabAutocomplete
mySettingsComponent?.enableContinueTeamsBeta?.isSelected = settings.continueState.enableContinueTeamsBeta
mySettingsComponent?.displayEditorTooltip?.isSelected = settings.continueState.displayEditorTooltip
ContinueExtensionSettings.instance.addRemoteSyncJob()
}
override fun disposeUIResources() {

View file

@ -57,7 +57,8 @@ class MessageTypes {
"getDefaultModelTitle",
"indexProgress",
"refreshSubmenuItems",
"didChangeAvailableProfiles"
"didChangeAvailableProfiles",
"addContextItem"
)
}
}

View file

@ -192,6 +192,7 @@
"msty",
"watsonx",
"openrouter",
"sambanova",
"nvidia",
"vllm"
],
@ -398,7 +399,8 @@
"huggingface-inference-api",
"replicate",
"together",
"cloudflare"
"cloudflare",
"sambanova"
]
}
},
@ -1285,6 +1287,9 @@
"watsonxStopToken": {
"type": "string"
},
"watsonxFullUrl": {
"type": "string"
},
"model": {
"enum": [
"ibm/granite-13b-chat-v2",
@ -1297,6 +1302,35 @@
},
"required": ["watsonxUrl", "watsonxProjectId"]
}
},
{
"if": {
"properties": {
"provider": {
"enum": ["sambanova"]
}
},
"required": ["provider"]
},
"then": {
"properties": {
"model": {
"anyOf": [
{
"enum": [
"llama3.1-8b",
"llama3.1-70b",
"llama3.1-405b"
]
},
{
"type": "string"
}
],
"markdownDescription": "Select a pre-defined option."
}
}
}
}
]
},
@ -2061,6 +2095,7 @@
"free-trial",
"gemini",
"voyage",
"nvidia",
"bedrock"
]
},
@ -2102,20 +2137,7 @@
"if": {
"properties": {
"provider": {
"enum": ["cohere", "voyage"]
}
},
"required": ["provider"]
},
"then": {
"required": ["apiKey"]
}
},
{
"if": {
"properties": {
"provider": {
"enum": ["gemini"]
"enum": ["cohere", "voyage", "gemini", "nvidia"]
}
},
"required": ["provider"]

View file

@ -0,0 +1,3 @@
<svg width="13" height="13" viewBox="0 0 13 13" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M10.4742 1.6668L9.77141 2.88516L11.5477 5.95951C11.5607 5.98283 11.5685 6.01135 11.5685 6.03728C11.5685 6.0632 11.5607 6.09172 11.5477 6.11505L9.77141 9.19199L10.4742 10.4104L13 6.03728L10.4742 1.66421V1.6668ZM9.4991 2.72702L10.2019 1.50867H8.79634L8.09357 2.72702H9.5017H9.4991ZM8.09097 3.0433L9.73249 5.88173H11.138L9.4991 3.0433H8.09097ZM9.4991 9.03645L11.138 6.19542H9.73249L8.09097 9.03645H9.4991ZM8.09097 9.35273L8.79374 10.5659H10.1993L9.4965 9.35273H8.08837H8.09097ZM3.32716 10.8666C3.29864 10.8666 3.27271 10.8588 3.24939 10.8458C3.22599 10.8329 3.20527 10.8122 3.19227 10.7889L1.41332 7.71183H0.00777705L2.53362 12.0824H7.58267L6.87991 10.8666H3.32976H3.32716ZM7.15222 10.7085L7.85498 11.9242L8.55775 10.7059L7.85498 9.48755L7.15222 10.7059V10.7085ZM7.58267 9.33201H4.30484L3.60207 10.5503H6.87991L7.58267 9.33201ZM4.02992 9.17647L2.38841 6.33536L1.68562 7.55376L3.32716 10.3948L4.02992 9.17647ZM0.00518489 7.39562H1.41073L2.1135 6.17729H0.71055L0.00518489 7.39562ZM3.18454 1.29611C3.19746 1.27278 3.21826 1.25205 3.24159 1.23908C3.26491 1.22612 3.29344 1.21834 3.31936 1.21834H6.87471L7.57747 0H2.52582L0 4.37305H1.40555L3.17934 1.29871L3.18454 1.29611ZM2.1135 5.90506L1.41073 4.68673H0.00518489L0.707957 5.90506H2.1135ZM3.32196 1.69013L1.68303 4.52859L2.38581 5.74699L4.02472 2.90848L3.32196 1.69013ZM6.87731 1.532H3.59427L4.29704 2.75034H7.58007L6.87731 1.532ZM7.85498 2.5922L8.55515 1.37647L7.85498 0.158126L7.15222 1.37388L7.85498 2.5922Z" fill="#6C707E"/>
</svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

View file

@ -5,6 +5,10 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html),
and is generated by [Changie](https://github.com/miniscruff/changie).
Pre-release Changes
### Changed
* Use Chromium only as a fallback after asking user
## 0.8.50 - 2024-09-02
### Fixed
* Hotfix for ability to use more than one inline context provider

View file

@ -192,6 +192,7 @@
"msty",
"watsonx",
"openrouter",
"sambanova",
"nvidia",
"vllm"
],
@ -398,7 +399,8 @@
"huggingface-inference-api",
"replicate",
"together",
"cloudflare"
"cloudflare",
"sambanova"
]
}
},
@ -1285,6 +1287,9 @@
"watsonxStopToken": {
"type": "string"
},
"watsonxFullUrl": {
"type": "string"
},
"model": {
"enum": [
"ibm/granite-13b-chat-v2",
@ -1297,6 +1302,35 @@
},
"required": ["watsonxUrl", "watsonxProjectId"]
}
},
{
"if": {
"properties": {
"provider": {
"enum": ["sambanova"]
}
},
"required": ["provider"]
},
"then": {
"properties": {
"model": {
"anyOf": [
{
"enum": [
"llama3.1-8b",
"llama3.1-70b",
"llama3.1-405b"
]
},
{
"type": "string"
}
],
"markdownDescription": "Select a pre-defined option."
}
}
}
}
]
},
@ -2061,6 +2095,7 @@
"free-trial",
"gemini",
"voyage",
"nvidia",
"bedrock"
]
},
@ -2102,20 +2137,7 @@
"if": {
"properties": {
"provider": {
"enum": ["cohere", "voyage"]
}
},
"required": ["provider"]
},
"then": {
"required": ["apiKey"]
}
},
{
"if": {
"properties": {
"provider": {
"enum": ["gemini"]
"enum": ["cohere", "voyage", "nvidia", "gemini"]
}
},
"required": ["provider"]

View file

@ -195,6 +195,7 @@
"msty",
"watsonx",
"openrouter",
"sambanova",
"nvidia",
"vllm"
],
@ -410,7 +411,8 @@
"huggingface-inference-api",
"replicate",
"together",
"cloudflare"
"cloudflare",
"sambanova"
]
}
},
@ -1424,6 +1426,9 @@
"watsonxStopToken": {
"type": "string"
},
"watsonxFullUrl": {
"type": "string"
},
"model": {
"enum": [
"ibm/granite-13b-chat-v2",
@ -1439,6 +1444,39 @@
"watsonxProjectId"
]
}
},
{
"if": {
"properties": {
"provider": {
"enum": [
"sambanova"
]
}
},
"required": [
"provider"
]
},
"then": {
"properties": {
"model": {
"anyOf": [
{
"enum": [
"llama3.1-8b",
"llama3.1-70b",
"llama3.1-405b"
]
},
{
"type": "string"
}
],
"markdownDescription": "Select a pre-defined option."
}
}
}
}
]
},
@ -2291,8 +2329,7 @@
"cohere",
"free-trial",
"gemini",
"voyage",
"bedrock"
"voyage"
]
},
"model": {
@ -2337,26 +2374,9 @@
"provider": {
"enum": [
"cohere",
"voyage"
]
}
},
"required": [
"provider"
]
},
"then": {
"required": [
"apiKey"
]
}
},
{
"if": {
"properties": {
"provider": {
"enum": [
"gemini"
"voyage",
"gemini",
"nvidia"
]
}
},

View file

@ -1,12 +1,12 @@
{
"name": "continue",
"version": "0.9.206",
"version": "0.9.208",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "continue",
"version": "0.9.206",
"version": "0.9.208",
"license": "Apache-2.0",
"dependencies": {
"@electron/rebuild": "^3.2.10",

View file

@ -2,7 +2,7 @@
"name": "continue",
"icon": "media/icon.png",
"author": "Continue Dev, Inc",
"version": "0.9.206",
"version": "0.9.209",
"repository": {
"type": "git",
"url": "https://github.com/continuedev/continue"

View file

@ -15,10 +15,8 @@ import {
} from "../autocomplete/statusBar";
import { registerAllCommands } from "../commands";
import { ContinueGUIWebviewViewProvider } from "../ContinueGUIWebviewViewProvider";
import { registerDebugTracker } from "../debug/debug";
import { DiffManager } from "../diff/horizontal";
import { VerticalPerLineDiffManager } from "../diff/verticalPerLine/manager";
import { VsCodeIde } from "../VsCodeIde";
import { registerAllCodeLensProviders } from "../lang-server/codeLens";
import { QuickEdit } from "../quickEdit/QuickEditQuickPick";
import { setupRemoteConfigSync } from "../stubs/activation";
@ -28,6 +26,7 @@ import {
} from "../stubs/WorkOsAuthProvider";
import { Battery } from "../util/battery";
import { TabAutocompleteModel } from "../util/loadAutocompleteModel";
import { VsCodeIde } from "../VsCodeIde";
import type { VsCodeWebviewProtocol } from "../webviewProtocol";
import { VsCodeMessenger } from "./VsCodeMessenger";
@ -210,7 +209,8 @@ export class VsCodeExtension {
this.core,
);
registerDebugTracker(this.sidebar.webviewProtocol, this.ide);
// Disabled due to performance issues
// registerDebugTracker(this.sidebar.webviewProtocol, this.ide);
// Listen for file saving - use global file watcher so that changes
// from outside the window are also caught

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

View file

@ -212,7 +212,7 @@ const IndexingProgressBar = ({
margin: 0,
}}
>
{Math.trunc(indexingState.progress)}%
{Math.trunc(Math.min(100, 100 * indexingState.progress))}%
</p>
</div>
@ -259,20 +259,22 @@ const IndexingProgressBar = ({
>
Retry
</StyledButton>
) : indexingState.status === "indexing" ? (
<StyledButton
onClick={() => {
if (indexingState.progress < 1 && indexingState.progress >= 0) {
setPaused((prev) => !prev);
} else {
ideMessenger.post("index/forceReIndex", undefined);
}
}}
>
Pause
</StyledButton>
) : indexingState.status === "loading" ? null : indexingState.status ===
"paused" ? (
) : indexingState.status === "indexing" ||
indexingState.status === "loading" ? (
<div>
<StyledButton
onClick={() => {
if (indexingState.progress < 1 && indexingState.progress >= 0) {
setPaused((prev) => !prev);
} else {
ideMessenger.post("index/forceReIndex", undefined);
}
}}
>
Pause
</StyledButton>
</div>
) : indexingState.status === "paused" ? (
<StyledButton
onClick={() => {
if (indexingState.progress < 1 && indexingState.progress >= 0) {
@ -286,11 +288,16 @@ const IndexingProgressBar = ({
</StyledButton>
) : null}
{indexingState.status === "failed" && (
<p style={{ color: "red", fontSize: getFontSize() - 2 }}>
{getIndexingErrMsg(indexingState.desc)}
</p>
)}
<div style={{ height: "40px", overflow: "hidden" }}>
{indexingState.status === "failed" && (
<p style={{ color: "red", fontSize: getFontSize() - 2 }}>
{getIndexingErrMsg(indexingState.desc)}
</p>
)}
{indexingState.status === "indexing" && (
<p style={{ color: lightGray }}>{indexingState.desc}</p>
)}
</div>
</div>
);
};

View file

@ -33,7 +33,6 @@ const StyledDiv = styled.div<{ isHidden: boolean }>`
gap: 1px;
background-color: ${vscInputBackground};
align-items: center;
z-index: 50;
font-size: ${getFontSize() - 2}px;
cursor: ${(props) => (props.isHidden ? "default" : "text")};
opacity: ${(props) => (props.isHidden ? 0 : 1)};

View file

@ -72,7 +72,6 @@ const InputBoxDiv = styled.div<{ disabled?: boolean }>`
width: calc(100% - 24px);
background-color: ${vscInputBackground};
color: ${vscForeground};
z-index: 1;
border: 0.5px solid ${vscInputBorder};
outline: none;
font-size: ${getFontSize()}px;
@ -99,7 +98,6 @@ const HoverDiv = styled.div`
opacity: 0.5;
background-color: ${vscBadgeBackground};
color: ${vscForeground};
z-index: 100;
display: flex;
align-items: center;
justify-content: center;
@ -112,7 +110,6 @@ const HoverTextDiv = styled.div`
top: 0;
left: 0;
color: ${vscForeground};
z-index: 100;
display: flex;
align-items: center;
justify-content: center;

View file

@ -67,6 +67,7 @@ export const models: { [key: string]: ModelPackage } = {
"together",
"llama.cpp",
"replicate",
"sambanova",
],
isOpenSource: true,
},

View file

@ -513,6 +513,13 @@ To get started, [register](https://dataplatform.cloud.ibm.com/registration/stepo
placeholder: "Enter the API Version",
defaultValue: "2023-05-29",
},
{
inputType: "text",
key: "watsonxFullUrl",
label: "Full watsonx URL",
placeholder: "http://us-south.dataplatform.cloud.ibm.com/m1/v1/text/generation_stream?version=2023-05-29",
required: false
},
// {
// inputType: "text",
// key: "title",
@ -573,4 +580,34 @@ To get started, [register](https://dataplatform.cloud.ibm.com/registration/stepo
],
collectInputFor: [...completionParamsInputsConfigs],
},
sambanova: {
title: "SambaNova Cloud",
provider: "sambanova",
refPage: "sambanova",
description:
"Use SambaNova Cloud for Llama3.1 fast inference performance",
icon: "sambanova.png",
longDescription: `The SambaNova Cloud is a cloud platform for running large AI models with the world record Llama 3.1 70B/405B performance. You can sign up [here](https://cloud.sambanova.ai/)`,
tags: [ModelProviderTags.RequiresApiKey, ModelProviderTags.OpenSource],
params: {
apiKey: "",
},
collectInputFor: [
{
inputType: "text",
key: "apiKey",
label: "API Key",
placeholder: "Enter your SambaNova Cloud API key",
required: true,
},
...completionParamsInputsConfigs,
],
packages: [
models.llama31Chat,
].map((p) => {
p.params.contextLength = 4096;
return p;
}),
apiKeyUrl: "https://cloud.sambanova.ai/apis",
},
};

View file

@ -404,6 +404,11 @@ function History() {
This Month
</SectionHeader>
)}
{date < lastMonth && prevDate > lastMonth && (
<SectionHeader style={{ top: `${headerHeight - 1}px` }}>
Older
</SectionHeader>
)}
<Tr key={index}>
<TableRow

View file

@ -88,7 +88,7 @@ function MorePage() {
<h3 className="my-3 mx-auto text-center">Codebase Indexing</h3>
<div
className="p-6 flex flex-col gap-6"
className="p-6 pb-0 flex flex-col gap-6"
style={{
borderTop: `0.5px solid ${lightGray}`,
}}

View file

@ -68,6 +68,11 @@ export function constructLlmApi(config: LlmApiConfig): BaseLlmApi {
...config,
apiBase: "https://api.together.xyz/v1/",
});
case "sambanova":
return new OpenAIApi({
...config,
apiBase: "https://api.sambanova.ai/v1/",
});
default:
throw new Error(`Unsupported LLM API format: ${config.provider}`);
}

View file

@ -204,6 +204,12 @@ const COMPLETION_TESTS: ({ chatOnly?: boolean } & LlmApiConfig)[] = [
apiKey: process.env.TOGETHER_API_KEY!,
chatOnly: true,
},
{
provider: "sambanova",
model: "Meta-Llama-3.1-8B-Instruct",
apiKey: process.env.SAMBANOVA_API_KEY!,
chatOnly: true,
},
];
const FIM_TESTS: LlmApiConfig[] = [