merge dev

This commit is contained in:
Test 2024-09-14 11:55:53 -07:00
commit 17c96acbac
179 changed files with 4860 additions and 3354 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,9 +161,9 @@ 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 }}
name: ${{ env.target }}-vsix
path: "extensions/vscode/*.vsix"
release:
@ -182,21 +182,18 @@ jobs:
git config --local user.name "GitHub Action"
# Download the .vsix artifacts
- uses: actions/download-artifact@v3
- uses: actions/download-artifact@v4
with:
pattern: "*-vsix"
path: vsix-artifacts
merge-multiple: true
- name: Release
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ github.ref_name }}
files: |
alpine-x64/*.vsix
darwin-arm64/*.vsix
darwin-x64/*.vsix
linux-arm64/*.vsix
linux-armhf/*.vsix
linux-x64/*.vsix
win32-x64/*.vsix
win32-arm64/*.vsix
vsix-artifacts/*.vsix
token: ${{ secrets.CI_GITHUB_TOKEN }}
repository: continuedev/continue
@ -220,13 +217,17 @@ jobs:
run: git pull origin main
# 1. Download the artifacts
- uses: actions/download-artifact@v3
- uses: actions/download-artifact@v4
with:
pattern: "*-vsix"
path: vsix-artifacts
merge-multiple: true
# 2. Publish the extension to VS Code Marketplace
- name: Publish to VS Code Marketplace
run: |
cd extensions/vscode
npx vsce publish --packagePath ../../alpine-x64/*.vsix ../../darwin-arm64/*.vsix ../../darwin-x64/*.vsix ../../linux-arm64/*.vsix ../../linux-armhf/*.vsix ../../linux-x64/*.vsix ../../win32-x64/*.vsix ../../win32-arm64/*.vsix
npx vsce publish --packagePath ../../vsix-artifacts/*.vsix
env:
VSCE_PAT: ${{ secrets.VSCE_TOKEN }}
@ -235,7 +236,7 @@ jobs:
continue-on-error: true
run: |
cd extensions/vscode
npx ovsx publish -p ${{ secrets.VSX_REGISTRY_TOKEN }} --packagePath ../../alpine-x64/*.vsix ../../darwin-arm64/*.vsix ../../darwin-x64/*.vsix ../../linux-arm64/*.vsix ../../linux-armhf/*.vsix ../../linux-x64/*.vsix ../../win32-x64/*.vsix ../../win32-arm64/*.vsix
npx ovsx publish -p ${{ secrets.VSX_REGISTRY_TOKEN }} --packagePath ../../vsix-artifacts/*.vsix
# 4. Update the package.json version and push changes
# - name: Update version in package.json

View file

@ -156,9 +156,9 @@ 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 }}
name: ${{ env.target }}-vsix
path: "extensions/vscode/*.vsix"
release:
@ -177,21 +177,18 @@ jobs:
git config --local user.name "GitHub Action"
# Download the .vsix artifacts
- uses: actions/download-artifact@v3
- uses: actions/download-artifact@v4
with:
pattern: "*-vsix"
path: vsix-artifacts
merge-multiple: true
- name: Release
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ github.ref_name }}
files: |
alpine-x64/*.vsix
darwin-arm64/*.vsix
darwin-x64/*.vsix
linux-arm64/*.vsix
linux-armhf/*.vsix
linux-x64/*.vsix
win32-x64/*.vsix
win32-arm64/*.vsix
vsix-artifacts/*.vsix
token: ${{ secrets.CI_GITHUB_TOKEN }}
repository: continuedev/continue
prerelease: true
@ -216,13 +213,17 @@ jobs:
run: git pull origin dev
# 1. Download the artifacts
- uses: actions/download-artifact@v3
- uses: actions/download-artifact@v4
with:
pattern: "*-vsix"
path: vsix-artifacts
merge-multiple: true
# 2. Publish the extension to VS Code Marketplace
- name: Publish to VS Code Marketplace
run: |
cd extensions/vscode
npx vsce publish --pre-release --packagePath ../../alpine-x64/*.vsix ../../darwin-arm64/*.vsix ../../darwin-x64/*.vsix ../../linux-arm64/*.vsix ../../linux-armhf/*.vsix ../../linux-x64/*.vsix ../../win32-x64/*.vsix ../../win32-arm64/*.vsix
npx vsce publish --pre-release --packagePath ../../vsix-artifacts/*.vsix
env:
VSCE_PAT: ${{ secrets.VSCE_TOKEN }}
@ -231,7 +232,7 @@ jobs:
continue-on-error: true
run: |
cd extensions/vscode
npx ovsx publish --pre-release -p ${{ secrets.VSX_REGISTRY_TOKEN }} --packagePath ../../alpine-x64/*.vsix ../../darwin-arm64/*.vsix ../../darwin-x64/*.vsix ../../linux-arm64/*.vsix ../../linux-armhf/*.vsix ../../linux-x64/*.vsix ../../win32-x64/*.vsix ../../win32-arm64/*.vsix
npx ovsx publish --pre-release -p ${{ secrets.VSX_REGISTRY_TOKEN }} --packagePath ../../vsix-artifacts/*.vsix
# 4. Update the package.json version and push changes
# - name: Update version in package.json

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

@ -311,10 +311,17 @@ export class CompletionProvider {
// Get completion
const llm = await this.getLlm();
if (!llm) {
return undefined;
}
// Ignore empty API keys for Mistral since we currently write
// a template provider without one during onboarding
if (llm.providerName === "mistral" && llm.apiKey === "") {
return undefined;
}
// Set temperature (but don't overrride)
if (llm.completionOptions.temperature === undefined) {
llm.completionOptions.temperature = 0.01;

View file

@ -10,8 +10,13 @@ import {
IdeSettings,
ILLM,
} from "../index.js";
import Ollama from "../llm/llms/Ollama.js";
import { GlobalContext } from "../util/GlobalContext.js";
import { finalToBrowserConfig } from "./load.js";
import {
LOCAL_ONBOARDING_CHAT_MODEL,
ONBOARDING_LOCAL_MODEL_TITLE,
} from "./onboarding.js";
import ControlPlaneProfileLoader from "./profile/ControlPlaneProfileLoader.js";
import { IProfileLoader } from "./profile/IProfileLoader.js";
import LocalProfileLoader from "./profile/LocalProfileLoader.js";
@ -279,9 +284,18 @@ export class ConfigHandler {
async llmFromTitle(title?: string): Promise<ILLM> {
const config = await this.loadConfig();
const model =
config.models.find((m) => m.title === title) || config.models[0];
const model = config.models.find((m) => m.title === title);
if (!model) {
if (title === ONBOARDING_LOCAL_MODEL_TITLE) {
// Special case, make calls to Ollama before we have it in the config
const ollama = new Ollama({
model: LOCAL_ONBOARDING_CHAT_MODEL,
});
return ollama;
} else if (config.models.length > 0) {
return config.models[0];
}
throw new Error("No model found");
}

View file

@ -3,9 +3,28 @@ import {
ModelDescription,
SerializedContinueConfig,
SlashCommandDescription,
} from "../index.js";
} from "../";
export const DEFAULT_CHAT_MODEL_CONFIG: ModelDescription = {
model: "claude-3-5-sonnet-20240620",
provider: "anthropic",
apiKey: "",
title: "Claude 3.5 Sonnet",
};
export const DEFAULT_AUTOCOMPLETE_MODEL_CONFIG: ModelDescription = {
title: "Codestral",
provider: "mistral",
model: "codestral-latest",
apiKey: "",
};
export const FREE_TRIAL_MODELS: ModelDescription[] = [
{
title: "Claude 3 Sonnet (Free Trial)",
provider: "free-trial",
model: "claude-3-sonnet-20240229",
},
{
title: "GPT-4o (Free Trial)",
provider: "free-trial",
@ -25,11 +44,6 @@ export const FREE_TRIAL_MODELS: ModelDescription[] = [
provider: "free-trial",
model: "codestral",
},
{
title: "Claude 3 Sonnet (Free Trial)",
provider: "free-trial",
model: "claude-3-sonnet-20240229",
},
];
export const defaultContextProvidersVsCode: ContextProviderWithParams[] = [
@ -91,7 +105,8 @@ export const defaultSlashCommandsJetBrains = [
];
export const defaultConfig: SerializedContinueConfig = {
models: [],
models: [DEFAULT_CHAT_MODEL_CONFIG],
tabAutocompleteModel: DEFAULT_AUTOCOMPLETE_MODEL_CONFIG,
customCommands: [
{
name: "test",
@ -100,17 +115,13 @@ export const defaultConfig: SerializedContinueConfig = {
description: "Write unit tests for highlighted code",
},
],
tabAutocompleteModel: {
title: "Starcoder2 3b",
provider: "ollama",
model: "starcoder2:3b",
},
contextProviders: defaultContextProvidersVsCode,
slashCommands: defaultSlashCommandsVscode,
};
export const defaultConfigJetBrains: SerializedContinueConfig = {
models: FREE_TRIAL_MODELS,
models: [DEFAULT_CHAT_MODEL_CONFIG],
tabAutocompleteModel: DEFAULT_AUTOCOMPLETE_MODEL_CONFIG,
customCommands: [
{
name: "test",
@ -119,11 +130,6 @@ export const defaultConfigJetBrains: SerializedContinueConfig = {
description: "Write unit tests for highlighted code",
},
],
tabAutocompleteModel: {
title: "Starcoder2 3b",
provider: "ollama",
model: "starcoder2:3b",
},
contextProviders: defaultContextProvidersJetBrains,
slashCommands: defaultSlashCommandsJetBrains,
};

View file

@ -306,7 +306,7 @@ async function intermediateToFinalConfig(
(model) => model.providerName === "free-trial",
);
if (freeTrialModels.length > 0) {
const ghAuthToken = await ide.getGitHubAuthToken();
const ghAuthToken = await ide.getGitHubAuthToken({});
for (const model of freeTrialModels) {
(model as FreeTrial).setupGhAuthToken(ghAuthToken);
}
@ -341,7 +341,7 @@ async function intermediateToFinalConfig(
// This shouldn't happen
throw new Error("Free trial cannot be used with control plane");
}
const ghAuthToken = await ide.getGitHubAuthToken();
const ghAuthToken = await ide.getGitHubAuthToken({});
(llm as FreeTrial).setupGhAuthToken(ghAuthToken);
}
return llm;
@ -356,7 +356,14 @@ async function intermediateToFinalConfig(
// These context providers are always included, regardless of what, if anything,
// the user has configured in config.json
const codebaseContextParams = ((config.contextProviders || []).filter(isContextProviderWithParams).find(cp => cp.name === "codebase") as ContextProviderWithParams | undefined)?.params || {};
const codebaseContextParams =
(
(config.contextProviders || [])
.filter(isContextProviderWithParams)
.find((cp) => cp.name === "codebase") as
| ContextProviderWithParams
| undefined
)?.params || {};
const DEFAULT_CONTEXT_PROVIDERS = [
new FileContextProvider({}),
new CodebaseContextProvider(codebaseContextParams),

View file

@ -1,56 +1,51 @@
import { SerializedContinueConfig } from "../index.js";
import { FREE_TRIAL_MODELS } from "./default.js";
import { SerializedContinueConfig } from "../";
import { FREE_TRIAL_MODELS } from "./default";
export const TRIAL_FIM_MODEL = "codestral-latest";
export const ONBOARDING_LOCAL_MODEL_TITLE = "Ollama";
export const LOCAL_ONBOARDING_FIM_MODEL = "starcoder2:3b";
export const LOCAL_ONBOARDING_CHAT_MODEL = "llama3.1:8b";
export const LOCAL_ONBOARDING_CHAT_TITLE = "Llama 3.1 8B";
export function setupApiKeysMode(
/**
* We set the "best" chat + autocopmlete models by default
* whenever a user doesn't have a config.json
*/
export function setupBestConfig(
config: SerializedContinueConfig,
): SerializedContinueConfig {
return {
...config,
models: config.models.filter((model) => model.provider !== "free-trial"),
embeddingsProvider: {
provider: "free-trial",
},
reranker: {
name: "free-trial",
},
};
}
export function setupLocalMode(
export function setupLocalConfig(
config: SerializedContinueConfig,
): SerializedContinueConfig {
return {
...config,
models: [
{
title: "Llama 3",
title: LOCAL_ONBOARDING_CHAT_TITLE,
provider: "ollama",
model: "llama3",
},
{
title: ONBOARDING_LOCAL_MODEL_TITLE,
provider: "ollama",
model: "AUTODETECT",
model: LOCAL_ONBOARDING_CHAT_MODEL,
},
...config.models.filter((model) => model.provider !== "free-trial"),
],
tabAutocompleteModel: {
title: "Starcoder 3b",
provider: "ollama",
model: "starcoder2:3b",
model: LOCAL_ONBOARDING_FIM_MODEL,
},
embeddingsProvider: {
provider: "ollama",
model: "nomic-embed-text",
},
reranker: undefined,
};
}
export function setupFreeTrialMode(
export function setupQuickstartConfig(
config: SerializedContinueConfig,
): SerializedContinueConfig {
return {
@ -73,16 +68,16 @@ export function setupFreeTrialMode(
};
}
export function setupLocalAfterFreeTrial(
export function setupLocalConfigAfterFreeTrial(
config: SerializedContinueConfig,
): SerializedContinueConfig {
return {
...config,
models: [
{
title: "Llama 3",
title: LOCAL_ONBOARDING_CHAT_TITLE,
provider: "ollama",
model: "llama3",
model: LOCAL_ONBOARDING_CHAT_MODEL,
},
{
title: ONBOARDING_LOCAL_MODEL_TITLE,

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

@ -16,6 +16,7 @@ class CodeContextProvider extends BaseContextProvider {
displayTitle: "Code",
description: "Type to search",
type: "submenu",
dependsOnIndexing: true,
};
async getContextItems(

View file

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

View file

@ -90,7 +90,8 @@ class DocsContextProvider extends BaseContextProvider {
await docsService.isJetBrainsAndPreIndexedDocsProvider();
if (isJetBrainsAndPreIndexedDocsProvider) {
extras.ide.errorPopup(
extras.ide.showToast(
"error",
`${DocsService.preIndexedDocsEmbeddingsProvider.id} is configured as ` +
"the embeddings provider, but it cannot be used with JetBrains. " +
"Please select a different embeddings provider to use the '@docs' " +
@ -108,8 +109,9 @@ class DocsContextProvider extends BaseContextProvider {
});
}
const embeddingsProvider =
await docsService.getEmbeddingsProvider(!!preIndexedDoc);
const embeddingsProvider = await docsService.getEmbeddingsProvider(
!!preIndexedDoc,
);
const [vector] = await embeddingsProvider.embed([extras.fullInput]);

View file

@ -21,6 +21,7 @@ class FileContextProvider extends BaseContextProvider {
displayTitle: "Files",
description: "Type to search",
type: "submenu",
dependsOnIndexing: true,
};
async getContextItems(

View file

@ -34,6 +34,7 @@ class FileTreeContextProvider extends BaseContextProvider {
description: "Attach a representation of the file tree",
type: "normal",
renderInlineAs: "",
dependsOnIndexing: true,
};
async getContextItems(

View file

@ -5,7 +5,11 @@ import {
ContextSubmenuItem,
LoadSubmenuItemsArgs,
} from "../../index.js";
import { getBasename, groupByLastNPathParts, getUniqueFilePath } from "../../util/index.js";
import {
getBasename,
groupByLastNPathParts,
getUniqueFilePath,
} from "../../util/index.js";
import { BaseContextProvider } from "../index.js";
class FolderContextProvider extends BaseContextProvider {
@ -14,6 +18,7 @@ class FolderContextProvider extends BaseContextProvider {
displayTitle: "Folder",
description: "Type to search",
type: "submenu",
dependsOnIndexing: true,
};
async getContextItems(
@ -35,7 +40,7 @@ class FolderContextProvider extends BaseContextProvider {
return {
id: folder,
title: getBasename(folder),
description: getUniqueFilePath(folder, folderGroups)
description: getUniqueFilePath(folder, folderGroups),
};
});
}

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,6 +1,7 @@
import { RequestOptions } from "../../../index.js";
import { RequestOptions } from "../../../";
// @ts-ignore
import adf2md from "adf-to-md";
interface JiraClientOptions {
domain: string;
username: string;
@ -112,7 +113,7 @@ export class JiraClient {
if (typeof issue.fields.description === "string") {
result.description = issue.fields.description;
} else if (issue.fields.description) {
result.description = adf2md(issue.fields.description).result;
result.description = adf2md.validate(issue.fields.description).result;
} else {
result.description = "";
}
@ -122,7 +123,7 @@ export class JiraClient {
const body =
typeof comment.body === "string"
? comment.body
: adf2md(comment.body).result;
: adf2md.validate(comment.body).result;
return {
body,

View file

@ -12,6 +12,7 @@ class RepoMapContextProvider extends BaseContextProvider {
displayTitle: "Repository Map",
description: "List of files and signatures",
type: "normal",
dependsOnIndexing: true,
};
async getContextItems(

View file

@ -4,6 +4,7 @@ import {
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";
@ -66,6 +67,14 @@ export async function retrieveContextItemsFromEmbeddings(
? RerankerRetrievalPipeline
: NoRerankerRetrievalPipeline;
if (filterDirectory) {
// Handle relative paths
filterDirectory = await resolveRelativePathInWorkspace(
filterDirectory,
extras.ide,
);
}
const pipelineOptions: RetrievalPipelineOptions = {
nFinal,
nRetrieve,

View file

@ -3,10 +3,10 @@ import type { ContextItemId, IDE, IndexingProgressUpdate } from ".";
import { CompletionProvider } from "./autocomplete/completionProvider";
import { ConfigHandler } from "./config/ConfigHandler";
import {
setupApiKeysMode,
setupFreeTrialMode,
setupLocalAfterFreeTrial,
setupLocalMode,
setupBestConfig,
setupLocalConfig,
setupLocalConfigAfterFreeTrial,
setupQuickstartConfig,
} from "./config/onboarding";
import { createNewPromptFile } from "./config/promptFile";
import { addModel, addOpenAIKey, deleteModel } from "./config/util";
@ -15,7 +15,6 @@ import { ContinueServerClient } from "./continueServer/stubs/client";
import { getAuthUrlForTokenPage } from "./control-plane/auth/index";
import { ControlPlaneClient } from "./control-plane/client";
import { CodebaseIndexer, PauseToken } from "./indexing/CodebaseIndexer";
import DocsCrawler from "./indexing/docs/DocsCrawler";
import DocsService from "./indexing/docs/DocsService";
import Ollama from "./llm/llms/Ollama";
import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
@ -169,12 +168,6 @@ export class Core {
(..._) => Promise.resolve([]),
);
try {
DocsCrawler.verifyOrInstallChromium();
} catch (err) {
console.debug(`Failed to install Chromium: ${err}`);
}
const on = this.messenger.on.bind(this.messenger);
this.messenger.onError((err) => {
@ -183,7 +176,7 @@ export class Core {
message: err.message,
stack: err.stack,
});
this.messenger.request("errorPopup", { message: err.message });
this.ide.showToast("error", err.message);
});
// New
@ -279,9 +272,9 @@ export class Core {
}
if (hasFailed) {
this.ide.infoPopup(`Failed to index ${msg.data.startUrl}`);
this.ide.showToast("info", `Failed to index ${msg.data.startUrl}`);
} else {
this.ide.infoPopup(`Successfully indexed ${msg.data.startUrl}`);
this.ide.showToast("info", `Successfully indexed ${msg.data.startUrl}`);
this.messenger.send("refreshSubmenuItems", undefined);
}
});
@ -351,7 +344,10 @@ export class Core {
id,
}));
} catch (e) {
this.ide.errorPopup(`Error getting context items from ${name}: ${e}`);
this.ide.showToast(
"error",
`Error getting context items from ${name}: ${e}`,
);
return [];
}
});
@ -472,7 +468,7 @@ export class Core {
}
}
} catch (e) {
console.warn(`Error listing Ollama models: ${e}`);
console.debug(`Error listing Ollama models: ${e}`);
return undefined;
}
});
@ -610,31 +606,27 @@ export class Core {
on("completeOnboarding", (msg) => {
const mode = msg.data.mode;
Telemetry.capture("onboardingSelection", {
mode,
});
if (mode === "custom") {
if (mode === "Custom") {
return;
}
let editConfigJsonCallback: Parameters<typeof editConfigJson>[0];
switch (mode) {
case "local":
editConfigJsonCallback = setupLocalMode;
case "Local":
editConfigJsonCallback = setupLocalConfig;
break;
case "freeTrial":
editConfigJsonCallback = setupFreeTrialMode;
case "Quickstart":
editConfigJsonCallback = setupQuickstartConfig;
break;
case "localAfterFreeTrial":
editConfigJsonCallback = setupLocalAfterFreeTrial;
case "LocalAfterFreeTrial":
editConfigJsonCallback = setupLocalConfigAfterFreeTrial;
break;
case "apiKeys":
editConfigJsonCallback = setupApiKeysMode;
case "Best":
editConfigJsonCallback = setupBestConfig;
break;
default:

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() !== ""
);

45
core/index.d.ts vendored
View file

@ -1,3 +1,5 @@
import { GetGhTokenArgs } from "./protocol/ide";
declare global {
interface Window {
ide?: "vscode";
@ -121,11 +123,12 @@ export interface ILLM extends LLMOptions {
export type ContextProviderType = "normal" | "query" | "submenu";
export interface ContextProviderDescription {
title: string;
title: ContextProviderName;
displayTitle: string;
description: string;
renderInlineAs?: string;
type: ContextProviderType;
dependsOnIndexing?: boolean;
}
export type FetchFunction = (url: string | URL, init?: any) => Promise<any>;
@ -316,6 +319,9 @@ export interface LLMFullCompletionOptions extends BaseCompletionOptions {
model?: string;
}
export type ToastType = "info" | "error" | "warning";
export interface LLMOptions {
model: string;
@ -362,6 +368,7 @@ export interface LLMOptions {
watsonxProjectId?: string;
watsonxStopToken?: string;
watsonxApiVersion?: string;
watsonxFullUrl?: string;
cacheSystemMessage?: boolean;
}
@ -496,13 +503,15 @@ export interface IDE {
getBranch(dir: string): Promise<string>;
getTags(artifactId: string): Promise<IndexTag[]>;
getRepoName(dir: string): Promise<string | undefined>;
errorPopup(message: string): Promise<void>;
infoPopup(message: string): Promise<void>;
showToast(
type: ToastType,
message: string,
...otherParams: any[]
): Promise<any>;
getGitRootPath(dir: string): Promise<string | undefined>;
listDir(dir: string): Promise<[string, FileType][]>;
getLastModified(files: string[]): Promise<{ [path: string]: number }>;
getGitHubAuthToken(): Promise<string | undefined>;
getGitHubAuthToken(args: GetGhTokenArgs): Promise<string | undefined>;
// LSP
gotoDefinition(location: Location): Promise<RangeInFile[]>;
@ -568,7 +577,15 @@ type ContextProviderName =
| "docs"
| "gitlab-mr"
| "os"
| "currentFile";
| "currentFile"
| "outline"
| "continue-proxy"
| "highlights"
| "file"
| "issue"
| "repo-map"
| "url"
| string;
type TemplateType =
| "llama2"
@ -621,6 +638,7 @@ type ModelProvider =
| "msty"
| "watsonx"
| "openrouter"
| "sambanova"
| "nvidia"
| "vllm"
| "mock";
@ -772,6 +790,7 @@ export interface ModelDescription {
}
export type EmbeddingsProviderName =
| "bedrock"
| "huggingface-tei"
| "transformers.js"
| "ollama"
@ -781,6 +800,7 @@ export type EmbeddingsProviderName =
| "gemini"
| "continue-proxy"
| "deepinfra"
| "nvidia"
| "voyage"
| "mistral";
@ -793,6 +813,12 @@ export interface EmbedOptions {
apiVersion?: string;
requestOptions?: RequestOptions;
maxChunkSize?: number;
maxBatchSize?: number;
// AWS options
profile?: string;
// AWS and GCP Options
region?: string;
}
export interface EmbeddingsProviderDescription extends EmbedOptions {
@ -913,6 +939,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

@ -1,28 +1,81 @@
import DocsCrawler, { type PageData } from "./DocsCrawler";
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 = 1_000_000;
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("crawl", () => {
describe("GitHub repositories", () => {
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 () => {
const docsCrawler = new DocsCrawler(new URL(repoUrl));
crawlResults = [];
for await (const page of docsCrawler.crawl()) {
for await (const page of docsCrawler.crawl(new URL(repoUrl))) {
crawlResults.push(page);
}
}, TIMEOUT);
}, TIMEOUT_MS);
test("finds expected markdown files", async () => {
expect(crawlResults.some((page) => page.path.endsWith("README.md"))).toBe(
@ -50,81 +103,36 @@ describe.skip("crawl", () => {
});
});
describe.only("Non-Github repository sites", () => {
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",
];
describe("Chromium Crawler", () => {
let shouldUseChromiumSpy: any;
const NUM_PAGES_TO_CRAWL = 10;
beforeAll(() => {
shouldUseChromiumSpy = jest
.spyOn(docsCrawler as any, "shouldUseChromium")
.mockReturnValue(true);
});
for (const site of TEST_SITES) {
const crawlResults: PageData[] = [];
const docsCrawler = new DocsCrawler(
new URL(site),
NUM_PAGES_TO_CRAWL,
);
afterAll(() => {
shouldUseChromiumSpy.mockRestore();
});
for await (const page of docsCrawler.crawl()) {
crawlResults.push(page);
}
describe("Pre-indexed Docs", () => {
crawlTest(Object.keys(preIndexedDocs));
});
// `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,
);
});
describe("Pre-indexed Docs", () => {
const results: { [url: string]: boolean } = {};
let totalTests = 0;
let passedTests = 0;
Object.keys(preIndexedDocs).forEach((url) => {
test(
`Crawl test for ${url}`,
async () => {
totalTests++;
let pageFound = false;
try {
const docsCrawler = new DocsCrawler(new URL(url), 1);
for await (const page of docsCrawler.crawl()) {
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,
);
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,11 +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 { getChromiumPath, getContinueUtilsPath } from "../../util/paths";
import { Handler, HTTPResponse, Page } from "puppeteer";
import {
editConfigJson,
getChromiumPath,
getContinueUtilsPath,
} from "../../util/paths";
// @ts-ignore
// @prettier-ignore
import PCR from "puppeteer-chromium-resolver";
import { ContinueConfig, IDE } from "../..";
export type PageData = {
url: string;
@ -13,35 +20,89 @@ export type PageData = {
content: string;
};
export default class DocsCrawler {
LINK_GROUP_SIZE = 2; // Controls parallelization of crawler
GITHUB_HOST = "github.com";
static MAX_REQUESTS_PER_CRAWL = 1000;
markdownRegex = new RegExp(/\.(md|mdx)$/);
octokit = new Octokit({
auth: undefined,
});
static PCR_CONFIG = {
downloadPath: getContinueUtilsPath(),
};
class DocsCrawler {
private readonly MAX_REQUESTS_PER_CRAWL = 1000;
private readonly GITHUB_HOST = "github.com";
private readonly chromiumInstaller: ChromiumInstaller;
constructor(
private readonly startUrl: URL,
private readonly maxRequestsPerCrawl: number = DocsCrawler.MAX_REQUESTS_PER_CRAWL,
) {}
static verifyOrInstallChromium() {
if (!fs.existsSync(getChromiumPath())) {
PCR(DocsCrawler.PCR_CONFIG);
}
private readonly ide: IDE,
private readonly config: ContinueConfig,
) {
this.chromiumInstaller = new ChromiumInstaller(this.ide, this.config);
}
async *crawl(): AsyncGenerator<PageData> {
if (this.startUrl.host === this.GITHUB_HOST) {
yield* this.crawlGithubRepo();
private shouldUseChromium() {
return (
this.config.experimental?.useChromiumForDocsCrawling &&
this.chromiumInstaller.isInstalled()
);
}
async *crawl(
startUrl: URL,
maxRequestsPerCrawl: number = this.MAX_REQUESTS_PER_CRAWL,
): AsyncGenerator<PageData> {
if (startUrl.host === this.GITHUB_HOST) {
yield* new GitHubCrawler(startUrl).crawl();
} else if (this.shouldUseChromium()) {
yield* new ChromiumCrawler(startUrl, maxRequestsPerCrawl).crawl();
} else {
yield* this.crawlSite();
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();
}
}
}
}
}
class GitHubCrawler {
private readonly markdownRegex = new RegExp(/\.(md|mdx)$/);
private octokit = new Octokit({ auth: undefined });
constructor(private readonly startUrl: URL) {}
async *crawl(): AsyncGenerator<PageData> {
console.debug(
`[${
(this.constructor as any).name
}] Crawling GitHub repo: ${this.startUrl.toString()}`,
);
const urlStr = this.startUrl.toString();
const [_, owner, repo] = this.startUrl.pathname.split("/");
const branch = await this.getGithubRepoDefaultBranch(owner, repo);
const paths = await this.getGitHubRepoPaths(owner, repo, branch);
for await (const path of paths) {
const content = await this.getGithubRepoFileContent(path, owner, repo);
yield { path, url: urlStr, content: content ?? "" };
}
}
@ -49,11 +110,7 @@ export default class DocsCrawler {
owner: string,
repo: string,
): Promise<string> {
const repoInfo = await this.octokit.repos.get({
owner,
repo,
});
const repoInfo = await this.octokit.repos.get({ owner, repo });
return repoInfo.data.default_branch;
}
@ -68,21 +125,17 @@ export default class DocsCrawler {
owner,
repo,
tree_sha: branch,
headers: {
"X-GitHub-Api-Version": "2022-11-28",
},
headers: { "X-GitHub-Api-Version": "2022-11-28" },
recursive: "true",
},
);
const paths = tree.data.tree
return tree.data.tree
.filter(
(file: any) =>
file.type === "blob" && this.markdownRegex.test(file.path ?? ""),
)
.map((file: any) => file.path);
return paths;
}
private async getGithubRepoFileContent(
@ -95,34 +148,274 @@ export default class DocsCrawler {
owner,
repo,
path,
headers: {
Accept: "application/vnd.github.raw+json",
},
headers: { Accept: "application/vnd.github.raw+json" },
});
return response.data as unknown as string;
} catch (error) {
console.debug("Error fetching file contents:", error);
return null;
}
}
}
private async *crawlGithubRepo() {
console.debug(`Crawling GitHub repo: ${this.startUrl.toString()}`);
class CheerioCrawler {
private readonly IGNORE_PATHS_ENDING_IN = [
"favicon.ico",
"robots.txt",
".rst.txt",
"genindex",
"py-modindex",
"search.html",
"search",
"genindex.html",
"changelog",
"changelog.html",
];
const urlStr = this.startUrl.toString();
const [_, owner, repo] = this.startUrl.pathname.split("/");
const branch = await this.getGithubRepoDefaultBranch(owner, repo);
const paths = await this.getGitHubRepoPaths(owner, repo, branch);
constructor(
private readonly startUrl: URL,
private readonly maxRequestsPerCrawl: number,
) {}
for await (const path of paths) {
const content = await this.getGithubRepoFileContent(path, owner, repo);
async *crawl(): AsyncGenerator<PageData> {
yield* this.crawlPage(this.startUrl);
}
yield {
path,
url: urlStr,
content: content ?? "",
};
private async *crawlPage(
url: URL,
maxDepth: number = 3,
): AsyncGenerator<PageData> {
console.log(
`[${
(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);
try {
const promises = batch.map(({ path, depth }) =>
this.getLinksFromUrl(baseUrl, path).then((links) => ({
links,
path,
depth,
})),
);
const results = await Promise.all(promises);
for (const {
links: { html, links: linksArray },
path,
depth,
} of results) {
if (html !== "" && depth <= maxDepth) {
yield { url: url.toString(), path, content: html };
}
if (depth < maxDepth) {
for (let link of linksArray) {
if (!paths.some((p) => p.path === link)) {
paths.push({ path: link, depth: depth + 1 });
}
}
}
}
} catch (e) {
console.debug("Error while crawling page: ", e);
}
index += batch.length;
}
console.log("Crawl completed");
}
private async getLinksFromUrl(url: string, path: string) {
const baseUrl = new URL(url);
const location = new URL(path, url);
let response;
try {
response = await fetch(location.toString());
} catch (error: unknown) {
if (
error instanceof Error &&
error.message.includes("maximum redirect")
) {
console.error(
`[${
(this.constructor as any).name
}] Maximum redirect reached for: ${location.toString()}`,
);
return { html: "", links: [] };
}
console.error(error);
return { html: "", links: [] };
}
const html = await response.text();
let links: string[] = [];
if (url.includes("github.com")) {
return { html, links };
}
const $ = cheerio.load(html);
$("a").each((_: any, element: any) => {
const href = $(element).attr("href");
if (!href) {
return;
}
const parsedUrl = new URL(href, url);
if (parsedUrl.hostname === baseUrl.hostname) {
links.push(parsedUrl.pathname);
}
});
links = [...new Set(links)].filter((link) => {
return (
!link.includes("#") &&
!this.IGNORE_PATHS_ENDING_IN.some((ending) => link.endsWith(ending))
);
});
return { html, links };
}
private splitUrl(url: URL) {
const baseUrl = `${url.protocol}//${url.hostname}${
url.port ? ":" + url.port : ""
}`;
const basePath = url.pathname;
return { baseUrl, basePath };
}
}
class ChromiumCrawler {
private readonly LINK_GROUP_SIZE = 2;
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: ${this.startUrl}`,
);
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",
],
executablePath: stats.executablePath,
});
const page = await browser.newPage();
try {
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(),
): AsyncGenerator<PageData> {
const urlStr = curUrl.toString();
if (visitedLinks.has(urlStr)) {
return;
}
await this.gotoPageAndHandleRedirects(page, urlStr);
const htmlContent = await page.content();
const linkGroups = await this.getLinkGroupsFromPage(page, curUrl);
this.curCrawlCount++;
visitedLinks.add(urlStr);
yield {
path: curUrl.pathname,
url: urlStr,
content: htmlContent,
};
for (const linkGroup of linkGroups) {
let enqueuedLinkCount = this.curCrawlCount;
for (const link of linkGroup) {
enqueuedLinkCount++;
console.log({ enqueuedLinkCount, url: this.startUrl });
if (enqueuedLinkCount <= this.maxRequestsPerCrawl) {
yield* this.crawlSitePages(page, new URL(link), visitedLinks);
}
}
}
}
@ -145,8 +438,6 @@ export default class DocsCrawler {
private async getLinksFromPage(page: Page, curUrl: URL) {
const links = await page.$$eval("a", (links) => links.map((a) => a.href));
// This additional step is due to issues getting the URL module to work
// in an $$eval command
const cleanedLinks = links
.map(this.stripHashFromUrl)
.filter(
@ -179,70 +470,89 @@ export default class DocsCrawler {
return groups;
}
}
private async *crawlSitePages(
page: Page,
curUrl: URL,
visitedLinks: Set<string> = new Set(),
curRequestCount: number = 0,
): AsyncGenerator<PageData> {
if (curRequestCount >= this.maxRequestsPerCrawl) {
console.warn("Max requests per crawl reached. Stopping crawler.");
return;
}
class ChromiumInstaller {
static PCR_CONFIG = { downloadPath: getContinueUtilsPath() };
if (visitedLinks.has(curUrl.toString())) {
return;
}
console.debug(`Crawling page: ${curUrl.toString()}`);
await page.goto(curUrl.toString());
const htmlContent = await page.content();
const linkGroups = await this.getLinkGroupsFromPage(page, curUrl);
const requestCount = curRequestCount + 1;
visitedLinks.add(curUrl.toString());
yield {
path: curUrl.pathname,
url: curUrl.toString(),
content: htmlContent,
};
for (const linkGroup of linkGroups) {
for (const link of linkGroup) {
yield* this.crawlSitePages(
page,
new URL(link),
visitedLinks,
requestCount,
);
}
constructor(
private readonly ide: IDE,
private readonly config: ContinueConfig,
) {
if (this.shouldInstallOnStartup()) {
console.log("Installing Chromium");
void this.install();
}
}
private async *crawlSite(): AsyncGenerator<PageData> {
console.debug(`Crawling site repo: ${this.startUrl}`);
isInstalled() {
return fs.existsSync(getChromiumPath());
}
const stats = await PCR(DocsCrawler.PCR_CONFIG);
shouldInstallOnStartup() {
return (
!this.isInstalled() &&
this.config.experimental?.useChromiumForDocsCrawling
);
}
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",
],
executablePath: stats.executablePath,
});
shouldProposeUseChromiumOnCrawlFailure() {
const { experimental } = this.config;
const page = await browser.newPage();
return (
experimental?.useChromiumForDocsCrawling === undefined ||
experimental.useChromiumForDocsCrawling
);
}
try {
yield* this.crawlSitePages(page, this.startUrl);
} catch (e) {
console.debug("Error getting links: ", e);
} finally {
await browser.close();
async proposeAndAttemptInstall(site: string) {
const userAcceptedInstall = await this.proposeInstall(site);
if (userAcceptedInstall) {
const didInstall = await this.install();
return didInstall;
}
}
async install() {
try {
await PCR(ChromiumInstaller.PCR_CONFIG);
ChromiumCrawler.setUseChromiumForDocsCrawling(true);
return true;
} catch (error) {
console.debug("Error installing Chromium : ", error);
console.debug(
"Setting 'useChromiumForDocsCrawling' to 'false' in config.json",
);
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,
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 {
@ -75,16 +76,14 @@ export default class DocsService {
private config!: ContinueConfig;
private sqliteDb?: Database;
// If we are instantiating a new DocsService from `getContextItems()`,
// we have access to the direct config object.
// When instantiating the DocsService from core, we have access
// to a ConfigHandler instance.
private docsCrawler!: DocsCrawler;
constructor(
configOrHandler: ConfigHandler,
configHandler: ConfigHandler,
private readonly ide: IDE,
private readonly messenger?: IMessenger<ToCoreProtocol, FromCoreProtocol>,
) {
this.isInitialized = this.init(configOrHandler);
this.isInitialized = this.init(configHandler);
}
static getSingleton() {
@ -92,11 +91,11 @@ export default class DocsService {
}
static createSingleton(
configOrHandler: ConfigHandler,
configHandler: ConfigHandler,
ide: IDE,
messenger?: IMessenger<ToCoreProtocol, FromCoreProtocol>,
) {
const docsService = new DocsService(configOrHandler, ide, messenger);
const docsService = new DocsService(configHandler, ide, messenger);
DocsService.instance = docsService;
return docsService;
}
@ -141,12 +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.infoPopup(
"No 'docs' provider configured under 'contextProviders' in config.json",
);
return;
const didAddDocsContextProvider =
await this.showAddDocsContextProviderToast();
if (!didAddDocsContextProvider) {
return;
}
}
const docs = await this.list();
@ -156,7 +177,7 @@ export default class DocsService {
while (!(await generator.next()).done) {}
}
this.ide.infoPopup("Docs indexing completed");
this.ide.showToast("info", "Docs indexing completed");
}
async list() {
@ -202,10 +223,8 @@ export default class DocsService {
let processedPages = 0;
let maxKnownPages = 1;
const docsCrawler = new DocsCrawler(new URL(startUrl));
// Crawl pages and retrieve info as articles
for await (const page of docsCrawler.crawl()) {
for await (const page of this.docsCrawler.crawl(new URL(startUrl))) {
processedPages++;
const article = pageToArticle(page);
@ -385,19 +404,9 @@ export default class DocsService {
return favicon;
}
/**
* A ConfigHandler is passed to the DocsService in `core` when
* we don't yet have access to the config object. This handler
* is used to set up a single instance of the DocsService that
* subscribes to config updates, e.g. to trigger re-indexing
* on a new embeddings provider.
*/
private async init(configHandler: ConfigHandler) {
if (configHandler instanceof ConfigHandler) {
this.config = await configHandler.loadConfig();
} else {
this.config = configHandler;
}
this.config = await configHandler.loadConfig();
this.docsCrawler = new DocsCrawler(this.ide, this.config);
const embeddingsProvider = await this.getEmbeddingsProvider();
@ -475,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} (
@ -725,7 +736,8 @@ export default class DocsService {
if (isJetBrainsAndPreIndexedDocsProvider) {
// A bit noisy for teams users whom have no choice if their admin is the one who didn't setup an embeddingsProvider
// this.ide.errorPopup(
// this.ide.showToast(
// "error",
// "The 'transformers.js' embeddings provider currently cannot be used to index " +
// "documentation in JetBrains. To enable documentation indexing, you can use " +
// "any of the other providers described in the docs: " +

View file

@ -45,7 +45,9 @@ abstract class BaseEmbeddingsProvider implements IBaseEmbeddingsProvider {
}
}
defaultOptions?: EmbedOptions | undefined;
maxBatchSize?: number | undefined;
get maxBatchSize(): number | undefined {
return this.options.maxBatchSize ?? (this.constructor as typeof BaseEmbeddingsProvider).maxBatchSize;
}
abstract embed(chunks: string[]): Promise<number[][]>;
@ -53,7 +55,7 @@ abstract class BaseEmbeddingsProvider implements IBaseEmbeddingsProvider {
return this.options.maxChunkSize ?? DEFAULT_MAX_CHUNK_SIZE;
}
static getBatchedChunks(chunks: string[]): string[][] {
getBatchedChunks(chunks: string[]): string[][] {
if (!this.maxBatchSize) {
console.warn(
`${this.getBatchedChunks.name} should only be called if 'maxBatchSize' is defined`,
@ -62,15 +64,10 @@ abstract class BaseEmbeddingsProvider implements IBaseEmbeddingsProvider {
return [chunks];
}
if (chunks.length > this.maxBatchSize) {
return [chunks];
}
const batchedChunks = [];
for (let i = 0; i < chunks.length; i += this.maxBatchSize) {
const batchSizedChunk = chunks.slice(i, i + this.maxBatchSize);
batchedChunks.push(batchSizedChunk);
batchedChunks.push(chunks.slice(i, i + this.maxBatchSize));
}
return batchedChunks;

View file

@ -0,0 +1,93 @@
import {
BedrockRuntimeClient,
InvokeModelCommand,
} from "@aws-sdk/client-bedrock-runtime";
import { fromIni } from "@aws-sdk/credential-providers";
import { EmbeddingsProviderName, EmbedOptions, FetchFunction } from "../../index.js";
import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js";
class BedrockEmbeddingsProvider extends BaseEmbeddingsProvider {
static providerName: EmbeddingsProviderName = "bedrock";
static defaultOptions: Partial<EmbedOptions> | undefined = {
model: "amazon.titan-embed-text-v2:0",
region: "us-east-1"
};
profile?: string | undefined;
constructor(options: EmbedOptions, fetch: FetchFunction) {
super(options, fetch);
if (!options.apiBase) {
options.apiBase = `https://bedrock-runtime.${options.region}.amazonaws.com`;
}
if (options.profile) {
this.profile = options.profile;
} else {
this.profile = "bedrock";
}
}
async embed(chunks: string[]) {
const credentials = await this._getCredentials();
const client = new BedrockRuntimeClient({
region: this.options.region,
credentials: {
accessKeyId: credentials.accessKeyId,
secretAccessKey: credentials.secretAccessKey,
sessionToken: credentials.sessionToken || "",
},
});
return (
await Promise.all(
chunks.map(async (chunk) => {
const input = this._generateInvokeModelCommandInput(chunk, this.options);
const command = new InvokeModelCommand(input);
const response = await client.send(command);
if (response.body) {
const responseBody = JSON.parse(new TextDecoder().decode(response.body));
return [responseBody.embedding];
}
}),
)
).flat();
}
private _generateInvokeModelCommandInput(
prompt: string,
options: EmbedOptions,
): any {
const payload = {
"inputText": prompt,
"dimensions": 512,
"normalize": true
};
return {
body: JSON.stringify(payload),
modelId: this.options.model,
accept: "application/json",
contentType: "application/json"
};
}
private async _getCredentials() {
try {
return await
fromIni({
profile: this.profile
})();
} catch (e) {
console.warn(
`AWS profile with name ${this.profile} not found in ~/.aws/credentials, using default profile`,
);
return await fromIni()();
}
}
}
export default BedrockEmbeddingsProvider;

View file

@ -18,16 +18,7 @@ class CohereEmbeddingsProvider extends BaseEmbeddingsProvider {
this.options.apiBase += "/";
}
const batchedChunks = [];
for (
let i = 0;
i < chunks.length;
i += CohereEmbeddingsProvider.maxBatchSize
) {
batchedChunks.push(
chunks.slice(i, i + CohereEmbeddingsProvider.maxBatchSize),
);
}
const batchedChunks = this.getBatchedChunks(chunks);
return (
await Promise.all(
batchedChunks.map(async (batch) => {

View file

@ -24,16 +24,7 @@ class FreeTrialEmbeddingsProvider extends BaseEmbeddingsProvider {
}
async embed(chunks: string[]) {
const batchedChunks = [];
for (
let i = 0;
i < chunks.length;
i += FreeTrialEmbeddingsProvider.maxBatchSize
) {
batchedChunks.push(
chunks.slice(i, i + FreeTrialEmbeddingsProvider.maxBatchSize),
);
}
const batchedChunks = this.getBatchedChunks(chunks);
return (
await Promise.all(
batchedChunks.map(async (batch) => {

View file

@ -8,7 +8,7 @@ import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js";
*/
class GeminiEmbeddingsProvider extends BaseEmbeddingsProvider {
static providerName: EmbeddingsProviderName = "gemini";
static maxBatchSize = 2048;
static maxBatchSize = 100;
static defaultOptions = {
apiBase: "https://generativelanguage.googleapis.com/v1/",
@ -55,10 +55,10 @@ class GeminiEmbeddingsProvider extends BaseEmbeddingsProvider {
}
async embed(chunks: string[]) {
const batches = GeminiEmbeddingsProvider.getBatchedChunks(chunks);
const batchedChunks = this.getBatchedChunks(chunks);
const results = await Promise.all(
batches.map((batch) => this.getSingleBatchEmbedding(batch)),
batchedChunks.map((batch) => this.getSingleBatchEmbedding(batch)),
);
return results.flat();
}

View file

@ -9,7 +9,10 @@ import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js";
class HuggingFaceTEIEmbeddingsProvider extends BaseEmbeddingsProvider {
static providerName: EmbeddingsProviderName = "huggingface-tei";
maxBatchSize = 32;
private _maxBatchSize?: number;
get maxBatchSize(): number | undefined {
return this._maxBatchSize ?? super.maxBatchSize;
}
static defaultOptions: Partial<EmbedOptions> | undefined = {
apiBase: "http://localhost:8080",
@ -24,18 +27,16 @@ class HuggingFaceTEIEmbeddingsProvider extends BaseEmbeddingsProvider {
}
this.doInfoRequest().then((response) => {
this.options.model = response.model_id;
this.maxBatchSize = response.max_client_batch_size;
this._maxBatchSize = response.max_client_batch_size;
});
}
async embed(chunks: string[]) {
const promises = [];
for (let i = 0; i < chunks.length; i += this.maxBatchSize) {
promises.push(
this.doEmbedRequest(chunks.slice(i, i + this.maxBatchSize)),
);
}
const results = await Promise.all(promises);
const batchedChunks = this.getBatchedChunks(chunks);
const results = await Promise.all(
batchedChunks.map((batch) => this.doEmbedRequest(batch)),
);
return results.flat();
}

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

@ -35,16 +35,7 @@ class OpenAIEmbeddingsProvider extends BaseEmbeddingsProvider {
}
async embed(chunks: string[]) {
const batchedChunks = [];
for (
let i = 0;
i < chunks.length;
i += OpenAIEmbeddingsProvider.maxBatchSize
) {
batchedChunks.push(
chunks.slice(i, i + OpenAIEmbeddingsProvider.maxBatchSize),
);
}
const batchedChunks = this.getBatchedChunks(chunks);
return (
await Promise.all(
batchedChunks.map(async (batch) => {

View file

@ -1,5 +1,6 @@
import { EmbeddingsProviderName } from "../../index.js";
import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js";
import BedrockEmbeddingsProvider from "./BedrockEmbeddingsProvider.js";
import CohereEmbeddingsProvider from "./CohereEmbeddingsProvider.js";
import ContinueProxyEmbeddingsProvider from "./ContinueProxyEmbeddingsProvider.js";
import DeepInfraEmbeddingsProvider from "./DeepInfraEmbeddingsProvider.js";
@ -10,6 +11,7 @@ import MistralEmbeddingsProvider from "./MistralEmbeddingsProvider.js";
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 (
@ -20,6 +22,7 @@ export const allEmbeddingsProviders: Record<
EmbeddingsProviderName,
EmbeddingsProviderConstructor
> = {
bedrock: BedrockEmbeddingsProvider,
ollama: OllamaEmbeddingsProvider,
"transformers.js": TransformersJsEmbeddingsProvider,
openai: OpenAIEmbeddingsProvider,
@ -29,6 +32,7 @@ export const allEmbeddingsProviders: Record<
gemini: GeminiEmbeddingsProvider,
"continue-proxy": ContinueProxyEmbeddingsProvider,
deepinfra: DeepInfraEmbeddingsProvider,
nvidia: NvidiaEmbeddingsProvider,
voyage: VoyageEmbeddingsProvider,
mistral: MistralEmbeddingsProvider,
};

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;
@ -323,6 +325,20 @@ ${prompt}`;
) {
text =
"You may need to add pre-paid credits before using the OpenAI API.";
} else if (
resp.status === 401 &&
(resp.url.includes("api.mistral.ai") ||
resp.url.includes("codestral.mistral.ai"))
) {
if (resp.url.includes("codestral.mistral.ai")) {
throw new Error(
`You are using a Mistral API key, which is not compatible with the Codestral API. Please either obtain a Codestral API key, or use the Mistral API by setting "apiBase" to "https://api.mistral.ai/v1" in config.json.`,
);
} else {
throw new Error(
`You are using a Codestral API key, which is not compatible with the Mistral API. Please either obtain a Mistral API key, or use the the Codestral API by setting "apiBase" to "https://codestral.mistral.ai/v1" in config.json.`,
);
}
}
throw new Error(
`HTTP ${resp.status} ${resp.statusText} from ${resp.url}\n\n${text}`,
@ -332,8 +348,14 @@ ${prompt}`;
return resp;
} catch (e: any) {
// Errors to ignore
if (!e.message.includes("/api/show")) {
console.warn(
if (e.message.includes("/api/tags")) {
throw new Error(`Error fetching tags: ${e.message}`);
} else if (e.message.includes("/api/show")) {
throw new Error(
`HTTP ${e.response.status} ${e.response.statusText} from ${e.response.url}\n\n${e.response.body}`,
);
} else {
console.debug(
`${e.message}\n\nCode: ${e.code}\nError number: ${e.errno}\nSyscall: ${e.erroredSysCall}\nType: ${e.type}\n\n${e.stack}`,
);

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

@ -89,9 +89,15 @@ class OpenAI extends BaseLLM {
return model;
}
private isO1Model(model?: string): boolean {
return (
!!model && (model.startsWith("o1-preview") || model.startsWith("o1-mini"))
);
}
protected _convertArgs(options: any, messages: ChatMessage[]) {
const url = new URL(this.apiBase!);
const finalOptions = {
const finalOptions: any = {
messages: messages.map(this._convertMessage),
model: this._convertModelName(options.model),
max_tokens: options.maxTokens,
@ -99,6 +105,7 @@ class OpenAI extends BaseLLM {
top_p: options.topP,
frequency_penalty: options.frequencyPenalty,
presence_penalty: options.presencePenalty,
stream: options.stream ?? true,
stop:
// Jan + Azure OpenAI don't truncate and will throw an error
this.maxStopWords !== undefined
@ -113,6 +120,21 @@ class OpenAI extends BaseLLM {
: options.stop,
};
// OpenAI o1-preview and o1-mini:
if (this.isO1Model(options.model)) {
// a) use max_completion_tokens instead of max_tokens
finalOptions.max_completion_tokens = options.maxTokens;
finalOptions.max_tokens = undefined;
// b) don't support streaming currently
finalOptions.stream = false;
// c) don't support system message
finalOptions.messages = finalOptions.messages?.filter(
(message: any) => message?.role !== "system",
);
}
return finalOptions;
}
@ -216,12 +238,9 @@ class OpenAI extends BaseLLM {
return;
}
const body = {
...this._convertArgs(options, messages),
stream: true,
};
const body = this._convertArgs(options, messages);
// Empty messages cause an error in LM Studio
body.messages = body.messages.map((m) => ({
body.messages = body.messages.map((m: any) => ({
...m,
content: m.content === "" ? " " : m.content,
})) as any;
@ -231,6 +250,13 @@ class OpenAI extends BaseLLM {
body: JSON.stringify(body),
});
// Handle non-streaming response
if (body.stream === false) {
const data = await response.json();
yield data.choices[0].message;
return;
}
for await (const value of streamSse(response)) {
if (value.choices?.[0]?.delta?.content) {
yield value.choices[0].delta;

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,
];

100
core/package-lock.json generated
View file

@ -22,6 +22,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",
@ -6256,6 +6257,46 @@
"node": ">=10"
}
},
"node_modules/cheerio": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/cheerio/-/cheerio-1.0.0.tgz",
"integrity": "sha512-quS9HgjQpdaXOvsZz82Oz7uxtXiy6UIsIQcpBj7HRw2M63Skasm9qlDocAM7jNuaxdhpPU7c4kJN+gA5MCu4ww==",
"dependencies": {
"cheerio-select": "^2.1.0",
"dom-serializer": "^2.0.0",
"domhandler": "^5.0.3",
"domutils": "^3.1.0",
"encoding-sniffer": "^0.2.0",
"htmlparser2": "^9.1.0",
"parse5": "^7.1.2",
"parse5-htmlparser2-tree-adapter": "^7.0.0",
"parse5-parser-stream": "^7.1.2",
"undici": "^6.19.5",
"whatwg-mimetype": "^4.0.0"
},
"engines": {
"node": ">=18.17"
},
"funding": {
"url": "https://github.com/cheeriojs/cheerio?sponsor=1"
}
},
"node_modules/cheerio-select": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/cheerio-select/-/cheerio-select-2.1.0.tgz",
"integrity": "sha512-9v9kG0LvzrlcungtnJtpGNxY+fzECQKhK4EGJX2vByejiMX84MFNQw4UxPJl3bFbTMw+Dfs37XaIkCwTZfLh4g==",
"dependencies": {
"boolbase": "^1.0.0",
"css-select": "^5.1.0",
"css-what": "^6.1.0",
"domelementtype": "^2.3.0",
"domhandler": "^5.0.3",
"domutils": "^3.0.1"
},
"funding": {
"url": "https://github.com/sponsors/fb55"
}
},
"node_modules/chownr": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/chownr/-/chownr-2.0.0.tgz",
@ -7038,6 +7079,18 @@
"iconv-lite": "^0.6.2"
}
},
"node_modules/encoding-sniffer": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/encoding-sniffer/-/encoding-sniffer-0.2.0.tgz",
"integrity": "sha512-ju7Wq1kg04I3HtiYIOrUrdfdDvkyO9s5XM8QAj/bN61Yo/Vb4vgJxy5vi4Yxk01gWHbrofpPtpxM8bKger9jhg==",
"dependencies": {
"iconv-lite": "^0.6.3",
"whatwg-encoding": "^3.1.1"
},
"funding": {
"url": "https://github.com/fb55/encoding-sniffer?sponsor=1"
}
},
"node_modules/end-of-stream": {
"version": "1.4.4",
"resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.4.tgz",
@ -8612,6 +8665,24 @@
"integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==",
"dev": true
},
"node_modules/htmlparser2": {
"version": "9.1.0",
"resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-9.1.0.tgz",
"integrity": "sha512-5zfg6mHUoaer/97TxnGpxmbR7zJtPwIYFMZ/H5ucTlPZhKvtum05yiPK3Mgai3a0DyVxv7qYqoweaEd2nrYQzQ==",
"funding": [
"https://github.com/fb55/htmlparser2?sponsor=1",
{
"type": "github",
"url": "https://github.com/sponsors/fb55"
}
],
"dependencies": {
"domelementtype": "^2.3.0",
"domhandler": "^5.0.3",
"domutils": "^3.1.0",
"entities": "^4.5.0"
}
},
"node_modules/http-cache-semantics": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/http-cache-semantics/-/http-cache-semantics-4.1.1.tgz",
@ -11507,6 +11578,29 @@
"url": "https://github.com/inikulin/parse5?sponsor=1"
}
},
"node_modules/parse5-htmlparser2-tree-adapter": {
"version": "7.0.0",
"resolved": "https://registry.npmjs.org/parse5-htmlparser2-tree-adapter/-/parse5-htmlparser2-tree-adapter-7.0.0.tgz",
"integrity": "sha512-B77tOZrqqfUfnVcOrUvfdLbz4pu4RopLD/4vmu3HUPswwTA8OH0EMW9BlWR2B0RCoiZRAHEUu7IxeP1Pd1UU+g==",
"dependencies": {
"domhandler": "^5.0.2",
"parse5": "^7.0.0"
},
"funding": {
"url": "https://github.com/inikulin/parse5?sponsor=1"
}
},
"node_modules/parse5-parser-stream": {
"version": "7.1.2",
"resolved": "https://registry.npmjs.org/parse5-parser-stream/-/parse5-parser-stream-7.1.2.tgz",
"integrity": "sha512-JyeQc9iwFLn5TbvvqACIF/VXG6abODeB3Fwmv/TGdLk2LfbWkaySGY72at4+Ty7EkPZj854u4CrICqNk2qIbow==",
"dependencies": {
"parse5": "^7.0.0"
},
"funding": {
"url": "https://github.com/inikulin/parse5?sponsor=1"
}
},
"node_modules/path-exists": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz",
@ -13749,9 +13843,9 @@
}
},
"node_modules/undici": {
"version": "6.18.2",
"resolved": "https://registry.npmjs.org/undici/-/undici-6.18.2.tgz",
"integrity": "sha512-o/MQLTwRm9IVhOqhZ0NQ9oXax1ygPjw6Vs+Vq/4QRjbOAC3B1GCHy7TYxxbExKlb7bzDRzt9vBWU6BDz0RFfYg==",
"version": "6.19.8",
"resolved": "https://registry.npmjs.org/undici/-/undici-6.19.8.tgz",
"integrity": "sha512-U8uCCl2x9TK3WANvmBavymRzxbfFYG+tAu+fgx3zxQy3qdagQqBLwJVrdyO1TBfUXvfKveMKJZhpvUYoOjM+4g==",
"engines": {
"node": ">=18.17"
}

View file

@ -51,6 +51,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

@ -22,6 +22,13 @@ export type ProtocolGeneratorType<T> = AsyncGenerator<{
content: T;
}>;
export type OnboardingModes =
| "Local"
| "Best"
| "Custom"
| "Quickstart"
| "LocalAfterFreeTrial";
export interface ListHistoryOptions {
offset?: number;
limit?: number;
@ -137,13 +144,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
"index/indexingProgressBarInitialized": [undefined, void];
completeOnboarding: [
{
mode:
| "local"
| "apiKeys"
| "custom"
| "freeTrial"
| "localAfterFreeTrial"
| "bestExperience";
mode: OnboardingModes;
},
void,
];

View file

@ -1,8 +1,8 @@
import { ControlPlaneSessionInfo } from "../control-plane/client.js";
import type {
ContinueRcJson,
DiffLine,
FileType,
IDE,
IdeInfo,
IdeSettings,
IndexTag,
@ -11,7 +11,12 @@ import type {
Range,
RangeInFile,
Thread,
} from "../index.js";
} from "../";
import { ControlPlaneSessionInfo } from "../control-plane/client";
export interface GetGhTokenArgs {
force?: boolean;
}
export type ToIdeFromWebviewOrCoreProtocol = {
// Methods from IDE type
@ -67,15 +72,17 @@ export type ToIdeFromWebviewOrCoreProtocol = {
getBranch: [{ dir: string }, string];
getRepoName: [{ dir: string }, string | undefined];
errorPopup: [{ message: string }, void];
infoPopup: [{ message: string }, void];
showToast: [
Parameters<IDE["showToast"]>,
Awaited<ReturnType<IDE["showToast"]>>,
];
getGitRootPath: [{ dir: string }, string | undefined];
listDir: [{ dir: string }, [string, FileType][]];
getLastModified: [{ files: string[] }, { [path: string]: number }];
gotoDefinition: [{ location: Location }, RangeInFile[]];
getGitHubAuthToken: [undefined, string | undefined];
getGitHubAuthToken: [GetGhTokenArgs, string | undefined];
getControlPlaneSessionInfo: [
{ silent: boolean },
ControlPlaneSessionInfo | undefined,

View file

@ -58,7 +58,7 @@ export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & {
setColors: [{ [key: string]: string }, void];
"jetbrains/editorInsetRefresh": [undefined, void];
addApiKey: [undefined, void];
setupLocalModel: [undefined, void];
setupLocalConfig: [undefined, void];
incrementFtc: [undefined, void];
openOnboarding: [undefined, void];
openOnboardingCard: [undefined, void];
};

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

@ -12,12 +12,21 @@ import {
Range,
RangeInFile,
Thread,
ToastType,
} from "../index.d.js";
import { GetGhTokenArgs } from "../protocol/ide.js";
import { getContinueGlobalPath } from "./paths.js";
class FileSystemIde implements IDE {
constructor(private readonly workspaceDir: string) {}
showToast(
type: ToastType,
message: string,
...otherParams: any[]
): Promise<void> {
return Promise.resolve();
}
pathSep(): Promise<string> {
return Promise.resolve(path.sep);
}
@ -42,7 +51,7 @@ class FileSystemIde implements IDE {
enableDebugLogs: false,
};
}
async getGitHubAuthToken(): Promise<string | undefined> {
async getGitHubAuthToken(args: GetGhTokenArgs): Promise<string | undefined> {
return undefined;
}
async getLastModified(files: string[]): Promise<{ [path: string]: number }> {
@ -68,28 +77,25 @@ class FileSystemIde implements IDE {
dirent.isDirectory()
? (2 as FileType.Directory)
: dirent.isSymbolicLink()
? (64 as FileType.SymbolicLink)
: (1 as FileType.File),
? (64 as FileType.SymbolicLink)
: (1 as FileType.File),
]);
return Promise.resolve(all);
}
infoPopup(message: string): Promise<void> {
return Promise.resolve();
}
errorPopup(message: string): Promise<void> {
return Promise.resolve();
}
getRepoName(dir: string): Promise<string | undefined> {
return Promise.resolve(undefined);
}
async getTags(artifactId: string): Promise<IndexTag[]> {
const directory =(await this.getWorkspaceDirs())[0];
return [{
artifactId,
branch: await this.getBranch(directory),
directory
}];
const directory = (await this.getWorkspaceDirs())[0];
return [
{
artifactId,
branch: await this.getBranch(directory),
directory,
},
];
}
getIdeInfo(): Promise<IdeInfo> {

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(

21
core/util/ideUtils.ts Normal file
View file

@ -0,0 +1,21 @@
import { IDE } from "..";
export async function resolveRelativePathInWorkspace(
path: string,
ide: IDE,
): Promise<string | undefined> {
const pathSep = await ide.pathSep();
if (path.startsWith(pathSep)) {
return path;
}
const workspaces = await ide.getWorkspaceDirs();
for (const workspace of workspaces) {
const fullPath = `${workspace}${pathSep}${path}`;
if (await ide.fileExists(fullPath)) {
return fullPath;
}
}
return undefined;
}

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

@ -11,7 +11,10 @@ import type {
RangeInFile,
Thread,
} from "../index.js";
import { ToIdeFromWebviewOrCoreProtocol } from "../protocol/ide.js";
import {
GetGhTokenArgs,
ToIdeFromWebviewOrCoreProtocol,
} from "../protocol/ide.js";
import { FromIdeProtocol } from "../protocol/index.js";
export class MessageIde implements IDE {
@ -25,6 +28,7 @@ export class MessageIde implements IDE {
callback: (data: FromIdeProtocol[T][0]) => FromIdeProtocol[T][1],
) => void,
) {}
pathSep(): Promise<string> {
return this.request("pathSep", undefined);
}
@ -41,8 +45,8 @@ export class MessageIde implements IDE {
getIdeSettings(): Promise<IdeSettings> {
return this.request("getIdeSettings", undefined);
}
getGitHubAuthToken(): Promise<string | undefined> {
return this.request("getGitHubAuthToken", undefined);
getGitHubAuthToken(args: GetGhTokenArgs): Promise<string | undefined> {
return this.request("getGitHubAuthToken", args);
}
getLastModified(files: string[]): Promise<{ [path: string]: number }> {
return this.request("getLastModified", { files });
@ -54,13 +58,9 @@ export class MessageIde implements IDE {
return this.request("listDir", { dir });
}
infoPopup(message: string): Promise<void> {
return this.request("infoPopup", { message });
}
errorPopup(message: string): Promise<void> {
return this.request("errorPopup", { message });
}
showToast: IDE["showToast"] = (...params) => {
return this.request("showToast", params);
};
getRepoName(dir: string): Promise<string | undefined> {
return this.request("getRepoName", { dir });

View file

@ -33,8 +33,8 @@ export class ReverseMessageIde {
}
private initializeListeners() {
this.on("getGitHubAuthToken", () => {
return this.ide.getGitHubAuthToken();
this.on("getGitHubAuthToken", (data) => {
return this.ide.getGitHubAuthToken(data);
});
this.on("getLastModified", (data) => {
@ -49,12 +49,8 @@ export class ReverseMessageIde {
return this.ide.listDir(data.dir);
});
this.on("infoPopup", (data) => {
return this.ide.infoPopup(data.message);
});
this.on("errorPopup", (data) => {
return this.ide.errorPopup(data.message);
this.on("showToast", (data) => {
return this.ide.showToast(...data);
});
this.on("getRepoName", (data) => {

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

@ -38,7 +38,7 @@ We offer a selection of pre-indexed documentation sites for popular frameworks a
### Through the `@docs` Context Provider
To add a single documentation site, we recommend going through the `@docs` context provider.
To add a single documentation site, we recommend using the `@docs` context provider.
1. Type `@docs` in the chat panel, hit enter
2. Type "add" and select the "Add Docs" option
@ -59,7 +59,6 @@ The configuration schema is as follows:
"startUrl": "https://docs.continue.dev/intro",
"rootUrl": "https://docs.continue.dev",
"faviconUrl": "https://docs.continue.dev/favicon.ico",
"maxDepth": 3
}
]
```
@ -68,18 +67,21 @@ The configuration schema is as follows:
- `startUrl`: The URL where the indexing process should begin.
- `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.
- `maxDepth`: The maximum number of levels deep the indexer should crawl from the start URL.
## 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
### Why did my documentation site fail to index?
Our current crawler is designed to work with static websites and may encounter issues with dynamic or JavaScript-heavy sites. If your documentation site failed to index, it's possible that it contains non-static elements that our crawler couldn't process.
If you're experiencing issues with indexing a documentation site, please let us know. We're continuously improving our indexing capabilities and would appreciate your feedback to help us enhance the feature.
<a href="https://discord.com/channels/1108621136150929458/1156679146932535376" className="button button--primary">Report Indexing Issues on Discord</a>
### How often is the indexed content updated?
Currently we do not automatically re-index your docs. If you would like to force a re-index, you can use the following command: `Continue: Docs Force Re-Index`.

Binary file not shown.

After

Width:  |  Height:  |  Size: 858 KiB

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).
```json title="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)

View file

@ -36,6 +36,49 @@ 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.
<!-- ## Usage
## Configuration
![usage-gif](../Model%20Providers/assets/watsonx1.gif) -->
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](../assets/watsonx2.gif)

View file

@ -90,3 +90,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"
],
@ -200,8 +201,8 @@
"### Free Trial\nNew users can try out Continue for free using a proxy server that securely makes calls to OpenAI using our API key. If you are ready to use your own API key or have used all 250 free uses, you can enter your API key in config.json where it says `apiKey=\"\"` or select another model provider.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/freetrial)",
"### Anthropic\nTo get started with Anthropic models, you first need to sign up for the open beta [here](https://claude.ai/login) to obtain an API key.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/anthropicllm)",
"### Cohere\nTo use Cohere, visit the [Cohere dashboard](https://dashboard.cohere.com/api-keys) to create an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/cohere)",
"### Bedrock\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)",
"### Bedrock Imported Models\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)",
"### Bedrock\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock)",
"### Bedrock Imported Models\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock)",
"### Sagemaker\nSagemaker is AWS' machine learning platform.",
"### Together\nTogether is a hosted service that provides extremely fast streaming of open-source language models. To get started with Together:\n1. Obtain an API key from [here](https://together.ai)\n2. Paste below\n3. Select a model preset\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/together)",
"### Ollama\nTo get started with Ollama, follow these steps:\n1. Download from [ollama.ai](https://ollama.ai/) and open the application\n2. Open a terminal and run `ollama run <MODEL_NAME>`. Example model names are `codellama:7b-instruct` or `llama2:7b-text`. You can find the full list [here](https://ollama.ai/library).\n3. Make sure that the model name used in step 2 is the same as the one in config.json (e.g. `model=\"codellama:7b-instruct\"`)\n4. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/ollama)",
@ -242,6 +243,21 @@
"description": "The base URL of the LLM API.",
"type": "string"
},
"region": {
"title": "Region",
"description": "The region where the model is hosted",
"type": "string"
},
"profile": {
"title": "Profile",
"description": "The AWS security profile to use",
"type": "string"
},
"modelArn": {
"title": "Profile",
"description": "The AWS arn for the imported model",
"type": "string"
},
"contextLength": {
"title": "Context Length",
"description": "The maximum context length of the LLM in tokens, as counted by countTokens.",
@ -383,7 +399,8 @@
"huggingface-inference-api",
"replicate",
"together",
"cloudflare"
"cloudflare",
"sambanova"
]
}
},
@ -393,6 +410,21 @@
"required": ["apiKey"]
}
},
{
"if": {
"properties": {
"provider": {
"enum": [
"bedrockimport"
]
}
},
"required": ["provider"]
},
"then": {
"required": ["modelArn"]
}
},
{
"if": {
"properties": {
@ -1254,6 +1286,9 @@
"watsonxStopToken": {
"type": "string"
},
"watsonxFullUrl": {
"type": "string"
},
"model": {
"enum": [
"ibm/granite-13b-chat-v2",
@ -1266,6 +1301,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."
}
}
}
}
]
},
@ -2029,7 +2093,9 @@
"cohere",
"free-trial",
"gemini",
"voyage"
"voyage",
"nvidia",
"bedrock"
]
},
"model": {
@ -2052,6 +2118,16 @@
"type": "integer",
"minimum": 128,
"exclusiveMaximum": 2147483647
},
"region": {
"title": "Region",
"description": "The region where the model is hosted",
"type": "string"
},
"profile": {
"title": "Profile",
"description": "The AWS security profile to use",
"type": "string"
}
},
"required": ["provider"],
@ -2060,20 +2136,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.66
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

@ -33,6 +33,8 @@ import javax.swing.*
import com.intellij.ide.plugins.PluginManager
import com.intellij.openapi.components.service
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.openapi.wm.ex.ToolWindowManagerListener
import org.jetbrains.plugins.terminal.TerminalToolWindowFactory
@ -68,20 +70,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 +136,8 @@ class ContinuePluginStartupActivity : StartupActivity, Disposable, DumbAware {
showTutorial(project)
}
settings.addRemoteSyncJob()
val ideProtocolClient = IdeProtocolClient(
continuePluginService,
defaultStrategy,
@ -186,11 +190,16 @@ class ContinuePluginStartupActivity : StartupActivity, Disposable, DumbAware {
)
// Reload the WebView
continuePluginService?.let {
val workspacePaths =
if (project.basePath != null) arrayOf(project.basePath) else emptyList<String>()
continuePluginService?.let { pluginService ->
val allModulePaths = ModuleManager.getInstance(project).modules
.flatMap { module -> ModuleRootManager.getInstance(module).contentRoots.map { it.path } }
.map { Paths.get(it).normalize() }
continuePluginService.workspacePaths = workspacePaths as Array<String>
val topLevelModulePaths = allModulePaths
.filter { modulePath -> allModulePaths.none { it != modulePath && modulePath.startsWith(it) } }
.map { it.toString() }
pluginService.workspacePaths = topLevelModulePaths.toTypedArray()
}
EditorFactory.getInstance().eventMulticaster.addSelectionListener(

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

@ -3,6 +3,7 @@ package com.github.continuedev.continueintellijextension.`continue`
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
import com.github.continuedev.continueintellijextension.services.TelemetryService
import com.github.continuedev.continueintellijextension.toolWindow.MessageTypes
import com.google.gson.Gson
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
@ -56,7 +57,7 @@ class CoreMessenger(private val project: Project, esbuildPath: String, continueC
val data = responseMap["data"]
// IDE listeners
if (ideMessageTypes.contains(messageType)) {
if (MessageTypes.ideMessageTypes.contains(messageType)) {
ideProtocolClient.handleMessage(json) { data ->
val message = gson.toJson(mapOf(
"messageId" to messageId,
@ -68,7 +69,7 @@ class CoreMessenger(private val project: Project, esbuildPath: String, continueC
}
// Forward to webview
if (PASS_THROUGH_TO_WEBVIEW.contains(messageType)) {
if (MessageTypes.PASS_THROUGH_TO_WEBVIEW.contains(messageType)) {
// TODO: Currently we aren't set up to receive a response back from the webview
// Can circumvent for getDefaultsModelTitle here for now
if (messageType == "getDefaultModelTitle") {
@ -88,7 +89,7 @@ class CoreMessenger(private val project: Project, esbuildPath: String, continueC
// Responses for messageId
responseListeners[messageId]?.let { listener ->
listener(data)
if (generatorTypes.contains(messageType)) {
if (MessageTypes.generatorTypes.contains(messageType)) {
val done = (data as Map<String, Boolean?>)["done"]
if (done == true) {
responseListeners.remove(messageId)
@ -100,64 +101,6 @@ class CoreMessenger(private val project: Project, esbuildPath: String, continueC
}
}
private val generatorTypes = listOf(
"llm/streamComplete",
"llm/streamChat",
"command/run",
"streamDiffLines"
)
private val ideMessageTypes = listOf(
"readRangeInFile",
"isTelemetryEnabled",
"getUniqueId",
"getWorkspaceConfigs",
"getDiff",
"getTerminalContents",
"getWorkspaceDirs",
"showLines",
"listFolders",
"getContinueDir",
"writeFile",
"fileExists",
"showVirtualFile",
"openFile",
"runCommand",
"saveFile",
"readFile",
"showDiff",
"getOpenFiles",
"getCurrentFile",
"getPinnedFiles",
"getSearchResults",
"getProblems",
"subprocess",
"getBranch",
"getIdeInfo",
"getIdeSettings",
"errorPopup",
"getRepoName",
"listDir",
"getGitRootPath",
"getLastModified",
"insertAtCursor",
"applyToFile",
"getGitHubAuthToken",
"setGitHubAuthToken",
"pathSep",
"getControlPlaneSessionInfo",
"logoutOfControlPlane",
"getTerminalContents"
)
private val PASS_THROUGH_TO_WEBVIEW = listOf<String>(
"configUpdate",
"getDefaultModelTitle",
"indexProgress",
"refreshSubmenuItems",
"didChangeAvailableProfiles"
)
private fun setPermissions(destination: String) {
val osName = System.getProperty("os.name").toLowerCase()
if (osName.contains("mac") || osName.contains("darwin")) {

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) {
@ -461,8 +480,9 @@ class IdeProtocolClient (
}
"getBranch" -> {
// Get the current branch name
val dir = (data as Map<String, Any>)["dir"] as String
val builder = ProcessBuilder("git", "rev-parse", "--abbrev-ref", "HEAD")
builder.directory(File(workspacePath ?: "."))
builder.directory(File(dir))
val process = builder.start()
val reader = BufferedReader(InputStreamReader(process.inputStream))
@ -473,15 +493,21 @@ class IdeProtocolClient (
}
"getRepoName" -> {
// Get the current repository name
val dir = (data as Map<String, Any>)["dir"] as String
val builder = ProcessBuilder("git", "config", "--get", "remote.origin.url")
builder.directory(File(workspacePath ?: "."))
val process = builder.start()
builder.directory(File(dir))
var output = "NONE"
try {
val process = builder.start()
val reader = BufferedReader(InputStreamReader(process.inputStream))
val output = reader.readLine()
process.waitFor()
val reader = BufferedReader(InputStreamReader(process.inputStream))
output = reader.readLine()
process.waitFor()
} catch (error: Exception) {
println("Git not found: " + error)
}
respond(output ?: "NONE")
respond(output)
}
// NEW //
@ -592,7 +618,8 @@ class IdeProtocolClient (
}
"getSearchResults" -> {
respond("")
val query = (data as Map<String, Any>)["query"] as String
respond(search(query))
}
// Other
@ -634,7 +661,7 @@ class IdeProtocolClient (
if (ghAuthToken == null) {
// Open a dialog so user can enter their GitHub token
continuePluginService.sendToWebview("openOnboarding", null, uuid())
continuePluginService.sendToWebview("openOnboardingCard", null, uuid())
respond(null)
} else {
respond(ghAuthToken)
@ -850,10 +877,15 @@ class IdeProtocolClient (
}
private fun workspaceDirectories(): Array<String> {
val dirs = this.continuePluginService.workspacePaths
if (dirs?.isNotEmpty() == true) {
return dirs
}
if (this.workspacePath != null) {
return arrayOf(this.workspacePath)
}
return arrayOf<String>();
return arrayOf()
}
private fun listDirectoryContents(directory: String?): List<String> {
@ -1018,6 +1050,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 && state.remoteConfigServerUrl!!.isNotEmpty()) {
// 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

@ -1,32 +1,22 @@
package com.github.continuedev.continueintellijextension.toolWindow
import com.github.continuedev.continueintellijextension.activities.showTutorial
import com.github.continuedev.continueintellijextension.activities.ContinuePluginStartupActivity
import com.github.continuedev.continueintellijextension.constants.getConfigJsonPath
import com.github.continuedev.continueintellijextension.constants.getContinueGlobalPath
import com.github.continuedev.continueintellijextension.`continue`.*
import com.github.continuedev.continueintellijextension.factories.CustomSchemeHandlerFactory
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
import com.google.gson.Gson
import com.google.gson.JsonObject
import com.google.gson.JsonParser
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.io.StreamUtil
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.ui.jcef.*
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import org.cef.CefApp
import org.cef.browser.CefBrowser
import org.cef.handler.CefLoadHandlerAdapter
import java.io.File
import java.io.IOException
import java.nio.charset.StandardCharsets
import java.nio.file.Paths
class ContinueBrowser(val project: Project, url: String, useOsr: Boolean = false) {
private val heightChangeListeners = mutableListOf<(Int) -> Unit>()
@ -118,13 +108,20 @@ class ContinueBrowser(val project: Project, url: String, useOsr: Boolean = false
val ide = continuePluginService.ideProtocolClient;
val respond = fun(data: Any?) {
val jsonData = mutableMapOf(
"messageId" to messageId,
"data" to data,
"messageType" to messageType
)
val jsonString = Gson().toJson(jsonData)
sendToWebview(messageType, data, messageId ?: uuid())
// This matches the way that we expect receive messages in IdeMessenger.ts (gui)
// and the way they are sent in VS Code (webviewProtocol.ts)
var result: Map<String, Any?>? = null
if (MessageTypes.generatorTypes.contains(messageType)) {
result = data as? Map<String, Any?>
} else {
result = mutableMapOf(
"status" to "success",
"done" to false,
"content" to data
)
}
sendToWebview(messageType, result, messageId ?: uuid())
}
if (PASS_THROUGH_TO_CORE.contains(messageType)) {

View file

@ -0,0 +1,64 @@
package com.github.continuedev.continueintellijextension.toolWindow
class MessageTypes {
companion object {
val generatorTypes = listOf(
"llm/streamComplete",
"llm/streamChat",
"command/run",
"streamDiffLines"
)
val ideMessageTypes = listOf(
"readRangeInFile",
"isTelemetryEnabled",
"getUniqueId",
"getWorkspaceConfigs",
"getDiff",
"getTerminalContents",
"getWorkspaceDirs",
"showLines",
"listFolders",
"getContinueDir",
"writeFile",
"fileExists",
"showVirtualFile",
"openFile",
"runCommand",
"saveFile",
"readFile",
"showDiff",
"getOpenFiles",
"getCurrentFile",
"getPinnedFiles",
"getSearchResults",
"getProblems",
"subprocess",
"getBranch",
"getIdeInfo",
"getIdeSettings",
"errorPopup",
"getRepoName",
"listDir",
"getGitRootPath",
"getLastModified",
"insertAtCursor",
"applyToFile",
"getGitHubAuthToken",
"setGitHubAuthToken",
"pathSep",
"getControlPlaneSessionInfo",
"logoutOfControlPlane",
"getTerminalContents"
)
val PASS_THROUGH_TO_WEBVIEW = listOf<String>(
"configUpdate",
"getDefaultModelTitle",
"indexProgress",
"refreshSubmenuItems",
"didChangeAvailableProfiles",
"addContextItem"
)
}
}

View file

@ -192,6 +192,7 @@
"msty",
"watsonx",
"openrouter",
"sambanova",
"nvidia",
"vllm"
],
@ -200,8 +201,8 @@
"### Free Trial\nNew users can try out Continue for free using a proxy server that securely makes calls to OpenAI using our API key. If you are ready to use your own API key or have used all 250 free uses, you can enter your API key in config.json where it says `apiKey=\"\"` or select another model provider.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/freetrial)",
"### Anthropic\nTo get started with Anthropic models, you first need to sign up for the open beta [here](https://claude.ai/login) to obtain an API key.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/anthropicllm)",
"### Cohere\nTo use Cohere, visit the [Cohere dashboard](https://dashboard.cohere.com/api-keys) to create an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/cohere)",
"### Bedrock\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)",
"### Bedrock Imported Models\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)",
"### Bedrock\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock)",
"### Bedrock Imported Models\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock)",
"### Sagemaker\nSagemaker is AWS' machine learning platform.",
"### Together\nTogether is a hosted service that provides extremely fast streaming of open-source language models. To get started with Together:\n1. Obtain an API key from [here](https://together.ai)\n2. Paste below\n3. Select a model preset\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/together)",
"### Ollama\nTo get started with Ollama, follow these steps:\n1. Download from [ollama.ai](https://ollama.ai/) and open the application\n2. Open a terminal and run `ollama run <MODEL_NAME>`. Example model names are `codellama:7b-instruct` or `llama2:7b-text`. You can find the full list [here](https://ollama.ai/library).\n3. Make sure that the model name used in step 2 is the same as the one in config.json (e.g. `model=\"codellama:7b-instruct\"`)\n4. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/ollama)",
@ -242,6 +243,21 @@
"description": "The base URL of the LLM API.",
"type": "string"
},
"region": {
"title": "Region",
"description": "The region where the model is hosted",
"type": "string"
},
"profile": {
"title": "Profile",
"description": "The AWS security profile to use",
"type": "string"
},
"modelArn": {
"title": "Profile",
"description": "The AWS arn for the imported model",
"type": "string"
},
"contextLength": {
"title": "Context Length",
"description": "The maximum context length of the LLM in tokens, as counted by countTokens.",
@ -383,7 +399,8 @@
"huggingface-inference-api",
"replicate",
"together",
"cloudflare"
"cloudflare",
"sambanova"
]
}
},
@ -393,6 +410,21 @@
"required": ["apiKey"]
}
},
{
"if": {
"properties": {
"provider": {
"enum": [
"bedrockimport"
]
}
},
"required": ["provider"]
},
"then": {
"required": ["modelArn"]
}
},
{
"if": {
"properties": {
@ -1254,6 +1286,9 @@
"watsonxStopToken": {
"type": "string"
},
"watsonxFullUrl": {
"type": "string"
},
"model": {
"enum": [
"ibm/granite-13b-chat-v2",
@ -1266,6 +1301,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."
}
}
}
}
]
},
@ -2029,7 +2093,9 @@
"cohere",
"free-trial",
"gemini",
"voyage"
"voyage",
"nvidia",
"bedrock"
]
},
"model": {
@ -2052,6 +2118,16 @@
"type": "integer",
"minimum": 128,
"exclusiveMaximum": 2147483647
},
"region": {
"title": "Region",
"description": "The region where the model is hosted",
"type": "string"
},
"profile": {
"title": "Profile",
"description": "The AWS security profile to use",
"type": "string"
}
},
"required": ["provider"],
@ -2060,20 +2136,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

@ -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"
],
@ -200,10 +201,10 @@
"### Free Trial\nNew users can try out Continue for free using a proxy server that securely makes calls to OpenAI using our API key. If you are ready to use your own API key or have used all 250 free uses, you can enter your API key in config.json where it says `apiKey=\"\"` or select another model provider.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/freetrial)",
"### Anthropic\nTo get started with Anthropic models, you first need to sign up for the open beta [here](https://claude.ai/login) to obtain an API key.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/anthropicllm)",
"### Cohere\nTo use Cohere, visit the [Cohere dashboard](https://dashboard.cohere.com/api-keys) to create an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/cohere)",
"### Bedrock\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)",
"### Bedrock Imported Models\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)",
"### Bedrock\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock)",
"### Bedrock Imported Models\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock)",
"### Sagemaker\nSagemaker is AWS' machine learning platform.",
"### Together\nTogether is a hosted service that provides extremely fast streaming of open-source language models. To get started with Together:\n1. Obtain an API key from [here](https://together.ai)\n2. Paste below\n3. Select a model preset\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/together)",
"### Together\nTogether is a hosted service that provides extremely fast streaming of open-source language models. To get started with Together:\n1. Obtain an API key from [here](https://together.ai)\n2. Paste below\n3. Select a model preset\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/togetherllm)",
"### Ollama\nTo get started with Ollama, follow these steps:\n1. Download from [ollama.ai](https://ollama.ai/) and open the application\n2. Open a terminal and run `ollama run <MODEL_NAME>`. Example model names are `codellama:7b-instruct` or `llama2:7b-text`. You can find the full list [here](https://ollama.ai/library).\n3. Make sure that the model name used in step 2 is the same as the one in config.json (e.g. `model=\"codellama:7b-instruct\"`)\n4. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/ollama)",
"### Huggingface TGI\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/huggingfacetgi)",
"### Huggingface Inference API\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/huggingfaceinferenceapi)",
@ -242,6 +243,21 @@
"description": "The base URL of the LLM API.",
"type": "string"
},
"region": {
"title": "Region",
"description": "The region where the model is hosted",
"type": "string"
},
"profile": {
"title": "Profile",
"description": "The AWS security profile to use",
"type": "string"
},
"modelArn": {
"title": "Profile",
"description": "The AWS arn for the imported model",
"type": "string"
},
"contextLength": {
"title": "Context Length",
"description": "The maximum context length of the LLM in tokens, as counted by countTokens.",
@ -383,7 +399,8 @@
"huggingface-inference-api",
"replicate",
"together",
"cloudflare"
"cloudflare",
"sambanova"
]
}
},
@ -393,6 +410,19 @@
"required": ["apiKey"]
}
},
{
"if": {
"properties": {
"provider": {
"enum": ["bedrockimport"]
}
},
"required": ["provider"]
},
"then": {
"required": ["modelArn"]
}
},
{
"if": {
"properties": {
@ -494,7 +524,7 @@
"if": {
"properties": {
"provider": {
"enum": ["openai", "azure"]
"enum": ["openai"]
}
},
"required": ["provider"]
@ -678,13 +708,13 @@
"anyOf": [
{
"enum": [
"claude-2",
"claude-instant-1",
"claude-3-5-sonnet-20240620",
"claude-3-opus-20240229",
"claude-3-sonnet-20240229",
"claude-3-haiku-20240307",
"claude-2.1",
"claude-2",
"claude-instant-1"
"claude-2.1"
]
},
{
@ -727,7 +757,6 @@
"anyOf": [
{
"enum": [
"anthropic.claude-3-5-sonnet-20240620-v1:0",
"claude-3-sonnet-20240229",
"claude-3-haiku-20240307",
"claude-2"
@ -774,6 +803,7 @@
},
"model": {
"enum": [
"chat-bison-001",
"gemini-pro",
"gemini-1.5-pro-latest",
"gemini-1.5-pro",
@ -914,33 +944,33 @@
"anyOf": [
{
"enum": [
"mistral:7b",
"llama2:7b",
"llama2:13b",
"codellama:7b",
"codellama:13b",
"codellama:34b",
"codellama:70b",
"llama3:8b",
"llama3:70b",
"llama3.1:8b",
"llama3.1:70b",
"llama3.1:405b",
"phi:2",
"phind:codellama:34b",
"wizardcoder:7b",
"wizardcoder:13b",
"wizardcoder:34b",
"zephyr:7b",
"codeup:13b",
"deepseek:7b",
"deepseek:33b",
"neural:chat:7b",
"deepseek:1b",
"stable:code:3b",
"starcoder:1b",
"starcoder:3b",
"starcoder2:3b",
"mistral-7b",
"llama2-7b",
"llama2-13b",
"codellama-7b",
"codellama-13b",
"codellama-34b",
"codellama-70b",
"llama3-8b",
"llama3-70b",
"llama3.1-8b",
"llama3.1-70b",
"llama3.1-405b",
"phi-2",
"phind-codellama-34b",
"wizardcoder-7b",
"wizardcoder-13b",
"wizardcoder-34b",
"zephyr-7b",
"codeup-13b",
"deepseek-7b",
"deepseek-33b",
"neural-chat-7b",
"deepseek-1b",
"stable-code-3b",
"starcoder-1b",
"starcoder-3b",
"starcoder2-3b",
"AUTODETECT"
]
},
@ -1205,6 +1235,7 @@
"claude-2.1",
"command-r",
"command-r-plus",
"chat-bison-001",
"gemini-pro",
"gemini-1.5-pro-latest",
"gemini-1.5-pro",
@ -1254,6 +1285,9 @@
"watsonxStopToken": {
"type": "string"
},
"watsonxFullUrl": {
"type": "string"
},
"model": {
"enum": [
"ibm/granite-13b-chat-v2",
@ -1266,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."
}
}
}
}
]
},
@ -2030,7 +2089,8 @@
"free-trial",
"gemini",
"voyage",
"mistral"
"nvidia",
"bedrock"
]
},
"model": {
@ -2053,6 +2113,16 @@
"type": "integer",
"minimum": 128,
"exclusiveMaximum": 2147483647
},
"region": {
"title": "Region",
"description": "The region where the model is hosted",
"type": "string"
},
"profile": {
"title": "Profile",
"description": "The AWS security profile to use",
"type": "string"
}
},
"required": ["provider"],
@ -2061,7 +2131,7 @@
"if": {
"properties": {
"provider": {
"enum": ["cohere", "voyage"]
"enum": ["cohere", "voyage", "nvidia", "gemini"]
}
},
"required": ["provider"]
@ -2069,109 +2139,6 @@
"then": {
"required": ["apiKey"]
}
},
{
"if": {
"properties": {
"provider": {
"enum": ["gemini"]
}
},
"required": ["provider"]
},
"then": {
"required": ["apiKey"],
"properties": {
"model": {
"enum": ["models/text-embedding-004"]
}
}
}
},
{
"if": {
"properties": {
"provider": {
"enum": ["ollama"]
}
},
"required": ["provider"]
},
"then": {
"properties": {
"model": {
"enum": ["nomic-embed-text"]
}
}
}
},
{
"if": {
"properties": {
"provider": {
"enum": ["openai", "azure"]
}
},
"required": ["provider"]
},
"then": {
"properties": {
"model": {
"enum": ["text-embedding-3-large", "text-embedding-3-small"]
}
}
}
},
{
"if": {
"properties": {
"provider": {
"enum": ["mistral"]
}
},
"required": ["provider"]
},
"then": {
"properties": {
"model": {
"enum": ["mistral-embed"]
}
}
}
},
{
"if": {
"properties": {
"provider": {
"enum": ["voyage"]
}
},
"required": ["provider"]
},
"then": {
"properties": {
"model": {
"enum": ["voyage-code-2"]
}
}
}
},
{
"if": {
"properties": {
"provider": {
"enum": ["cohere"]
}
},
"required": ["provider"]
},
"then": {
"properties": {
"model": {
"enum": ["embed-english-v3.0", "embed-english-light-v3.0"]
}
}
}
}
]
},
@ -2509,16 +2476,13 @@
"type": "object",
"properties": {
"inlineEdit": {
"description": "The 'title' property of the model you wish to use for inline edits",
"type": "string"
"$ref": "#/definitions/ModelTitle"
},
"applyCodeBlock": {
"description": "The 'title' property of the model you wish to use for applying code blocks",
"type": "string"
"$ref": "#/definitions/ModelTitle"
},
"repoMapFileSelection": {
"description": "The 'title' property of the model you wish to use for repo map file selections",
"type": "string"
"$ref": "#/definitions/ModelTitle"
}
}
},
@ -2581,6 +2545,12 @@
}
}
}
},
"ModelTitle": {
"type": "string",
"enum": {
"$data": "/models/title"
}
}
}
}

View file

@ -195,6 +195,7 @@
"msty",
"watsonx",
"openrouter",
"sambanova",
"nvidia",
"vllm"
],
@ -203,8 +204,8 @@
"### Free Trial\nNew users can try out Continue for free using a proxy server that securely makes calls to OpenAI using our API key. If you are ready to use your own API key or have used all 250 free uses, you can enter your API key in config.json where it says `apiKey=\"\"` or select another model provider.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/freetrial)",
"### Anthropic\nTo get started with Anthropic models, you first need to sign up for the open beta [here](https://claude.ai/login) to obtain an API key.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/anthropicllm)",
"### Cohere\nTo use Cohere, visit the [Cohere dashboard](https://dashboard.cohere.com/api-keys) to create an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/cohere)",
"### Bedrock\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)",
"### Bedrock Imported Models\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)",
"### Bedrock\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock)",
"### Bedrock Imported Models\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock)",
"### Sagemaker\nSagemaker is AWS' machine learning platform.",
"### Together\nTogether is a hosted service that provides extremely fast streaming of open-source language models. To get started with Together:\n1. Obtain an API key from [here](https://together.ai)\n2. Paste below\n3. Select a model preset\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/together)",
"### Ollama\nTo get started with Ollama, follow these steps:\n1. Download from [ollama.ai](https://ollama.ai/) and open the application\n2. Open a terminal and run `ollama run <MODEL_NAME>`. Example model names are `codellama:7b-instruct` or `llama2:7b-text`. You can find the full list [here](https://ollama.ai/library).\n3. Make sure that the model name used in step 2 is the same as the one in config.json (e.g. `model=\"codellama:7b-instruct\"`)\n4. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/ollama)",
@ -245,6 +246,21 @@
"description": "The base URL of the LLM API.",
"type": "string"
},
"region": {
"title": "Region",
"description": "The region where the model is hosted",
"type": "string"
},
"profile": {
"title": "Profile",
"description": "The AWS security profile to use",
"type": "string"
},
"modelArn": {
"title": "Profile",
"description": "The AWS arn for the imported model",
"type": "string"
},
"contextLength": {
"title": "Context Length",
"description": "The maximum context length of the LLM in tokens, as counted by countTokens.",
@ -395,7 +411,8 @@
"huggingface-inference-api",
"replicate",
"together",
"cloudflare"
"cloudflare",
"sambanova"
]
}
},
@ -409,6 +426,25 @@
]
}
},
{
"if": {
"properties": {
"provider": {
"enum": [
"bedrockimport"
]
}
},
"required": [
"provider"
]
},
"then": {
"required": [
"modelArn"
]
}
},
{
"if": {
"properties": {
@ -1390,6 +1426,9 @@
"watsonxStopToken": {
"type": "string"
},
"watsonxFullUrl": {
"type": "string"
},
"model": {
"enum": [
"ibm/granite-13b-chat-v2",
@ -1405,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."
}
}
}
}
]
},
@ -2257,7 +2329,9 @@
"cohere",
"free-trial",
"gemini",
"voyage"
"voyage",
"nvidia",
"bedrock"
]
},
"model": {
@ -2280,6 +2354,16 @@
"type": "integer",
"minimum": 128,
"exclusiveMaximum": 2147483647
},
"region": {
"title": "Region",
"description": "The region where the model is hosted",
"type": "string"
},
"profile": {
"title": "Profile",
"description": "The AWS security profile to use",
"type": "string"
}
},
"required": [
@ -2292,25 +2376,8 @@
"provider": {
"enum": [
"cohere",
"voyage"
]
}
},
"required": [
"provider"
]
},
"then": {
"required": [
"apiKey"
]
}
},
{
"if": {
"properties": {
"provider": {
"enum": [
"voyage",
"nvidia",
"gemini"
]
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 755 KiB

View file

@ -1,21 +1,8 @@
# 👋 Welcome to Continue
# Move Continue to the right sidebar
## ❗️ Before you get started
![Move Continue to right sidebar](./move-to-right-sidebar.gif)
Continue is currently in the left sidebar, but we recommend moving it to the right. This way it won't cover your file explorer.
Continue is currently in the left sidebar, but we recommend moving it to the right.
This way it won't cover your file explorer.
You can move it back at any time. If you close the sidebar, it can be re-opened with <kbd>Cmd/Ctrl</kbd> + <kbd>L</kbd>.
![Move Continue to right sidebar](./sidebar.gif)
## 🔑 Most important shortcuts
> If you'd prefer different keys, these shortcuts can be customized in VS Code settings.
<kbd>Cmd/Ctrl</kbd> + <kbd>L</kbd> = Select code
<kbd>Cmd/Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>L</kbd> = Select code for follow-up
<kbd>Cmd/Ctrl</kbd> + <kbd>I</kbd> = Quick edit
<kbd>Cmd/Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>R</kbd> = Automatically debug terminal

View file

@ -1,12 +1,12 @@
{
"name": "continue",
"version": "0.8.48",
"version": "0.9.209",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "continue",
"version": "0.8.48",
"version": "0.9.209",
"license": "Apache-2.0",
"dependencies": {
"@electron/rebuild": "^3.2.10",
@ -108,6 +108,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

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

@ -16,6 +16,7 @@ import type {
} from "core";
import { Range } from "core";
import { walkDir } from "core/indexing/walkDir";
import { GetGhTokenArgs } from "core/protocol/ide";
import {
editConfigJson,
getConfigJsonPath,
@ -42,6 +43,7 @@ class VsCodeIde implements IDE {
) {
this.ideUtils = new VsCodeIdeUtils();
}
pathSep(): Promise<string> {
return Promise.resolve(this.ideUtils.path.sep);
}
@ -74,7 +76,7 @@ class VsCodeIde implements IDE {
private authToken: string | undefined;
private askedForAuth = false;
async getGitHubAuthToken(): Promise<string | undefined> {
async getGitHubAuthToken(args: GetGhTokenArgs): Promise<string | undefined> {
// Saved auth token
if (this.authToken) {
return this.authToken;
@ -90,6 +92,14 @@ class VsCodeIde implements IDE {
}
try {
if (args.force) {
this.askedForAuth = true;
this.authToken = await vscode.authentication
.getSession("github", [], { createIfNone: true })
.then((session) => session.accessToken);
return this.authToken;
}
// If we haven't asked yet, give explanation of what is happening and why
// But don't wait to return this immediately
// We will use a callback to refresh the config
@ -107,7 +117,7 @@ class VsCodeIde implements IDE {
"continue.continueGUIView.focus",
);
(await this.vscodeWebviewProtocolPromise).request(
"openOnboarding",
"openOnboardingCard",
undefined,
);
@ -191,13 +201,24 @@ class VsCodeIde implements IDE {
return undefined;
}
async infoPopup(message: string): Promise<void> {
vscode.window.showInformationMessage(message);
}
showToast: IDE["showToast"] = async (...params) => {
const [type, message, ...otherParams] = params;
const { showErrorMessage, showWarningMessage, showInformationMessage } =
vscode.window;
async errorPopup(message: string): Promise<void> {
vscode.window.showErrorMessage(message);
}
switch (type) {
case "error":
return showErrorMessage(message, "Show logs").then((selection) => {
if (selection === "Show logs") {
vscode.commands.executeCommand("workbench.action.toggleDevTools");
}
});
case "info":
return showInformationMessage(message, ...otherParams);
case "warning":
return showWarningMessage(message, ...otherParams);
}
};
async getRepoName(dir: string): Promise<string | undefined> {
const repo = await this.getRepo(vscode.Uri.file(dir));

View file

@ -38,7 +38,7 @@ export class ContinueCompletionProvider
showFreeTrialLoginMessage(
e.message,
this.configHandler.reloadConfig.bind(this.configHandler),
() => this.webviewProtocol.request("openOnboarding", undefined),
() => this.webviewProtocol.request("openOnboardingCard", undefined),
);
return;
}
@ -50,7 +50,7 @@ export class ContinueCompletionProvider
),
);
} else if (val === "Download Ollama") {
vscode.env.openExternal(vscode.Uri.parse("https://ollama.ai"));
vscode.env.openExternal(vscode.Uri.parse("https://ollama.ai/download"));
}
});
}

View file

@ -4,6 +4,7 @@ import {
CONTINUE_WORKSPACE_KEY,
getContinueWorkspaceConfig,
} from "../util/workspaceConfig";
import { ILLM } from "core";
export enum StatusBarStatus {
Disabled,
@ -134,3 +135,37 @@ export function monitorBatteryChanges(battery: Battery): vscode.Disposable {
}
});
}
export function getAutocompleteStatusBarDescription(
selected: string | undefined,
{ title, apiKey, providerName }: ILLM,
): string | undefined {
if (title !== selected) {
return undefined;
}
let description = "Currently selected";
// Only set for Mistral since our default config includes Codestral without
// an API key
if ((apiKey === undefined || apiKey === "") && providerName === "mistral") {
description += " (Missing API key)";
}
return description;
}
export function getAutocompleteStatusBarTitle(
selected: string | undefined,
{ title }: ILLM,
): string {
if (!title) {
return "Unnamed Model";
}
if (title === selected) {
return `$(check) ${title}`;
}
return title;
}

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