Merge branch 'main' into nate/quick-edit-f4d8

This commit is contained in:
Nate 2025-01-10 08:59:58 -08:00
commit 6568b80a64
204 changed files with 3757 additions and 1969 deletions

View file

@ -0,0 +1,9 @@
## 0.8.66 - 2024-12-20
### Changed
* Improved autocomplete in untitled files
### Fixed
* Display more mid-line completions
* Restored syntax highlighting
* Fix tool use bug for models that don't support tools
* Autodetect mistral API key type
* Fixes Azure OpenAI regressions

View file

@ -1,4 +0,0 @@
project: extensions/vscode
kind: Changed
body: Improved autocomplete in untitled files
time: 2024-12-13T09:15:05.552877-08:00

View file

@ -1,4 +0,0 @@
project: extensions/vscode
kind: Fixed
body: Display more mid-line completions
time: 2024-12-13T09:14:54.808683-08:00

View file

@ -1,4 +0,0 @@
project: extensions/vscode
kind: Fixed
body: Restored syntax highlighting
time: 2024-12-13T09:15:19.485189-08:00

View file

@ -1,4 +0,0 @@
project: extensions/vscode
kind: Fixed
body: Fix tool use bug for models that don't support tools
time: 2024-12-16T22:08:02.399772-08:00

View file

@ -1,4 +0,0 @@
project: extensions/vscode
kind: Fixed
body: Autodetect mistral API key type
time: 2024-12-16T22:08:18.369444-08:00

View file

@ -0,0 +1,83 @@
---
name: 📖 Documentation Issue Report
description: Report issues related to the documentation
labels: [area:docs]
body:
- type: markdown
attributes:
value: |
## Thank you for helping us improve our documentation!
We appreciate your feedback. Before submitting, please check if a similar issue already exists.
### Quick Contribution Tips:
- Click "Edit this page" at the bottom of any page on [docs.continue.dev](https://docs.continue.dev) to contribute directly.
- For local development, see [CONTRIBUTING.md](https://github.com/continuedev/continue/blob/main/CONTRIBUTING.md#-updating--improving-documentation).
- type: dropdown
id: doc-issue-category
attributes:
label: Issue Category
description: Select the category that best describes your issue.
options:
- Undocumented feature or missing documentation
- Incorrect or outdated information
- Suggestion for existing article
- Broken or dead link
- Documentation organization issue
- Other (please describe in the details section)
validations:
required: true
- type: input
id: page-url
attributes:
label: Affected Documentation Page URL
description: Provide the URL of the specific page where you encountered the issue.
placeholder: "https://docs.continue.dev/path/to/page"
validations:
required: false
- type: textarea
id: details
attributes:
label: Issue Description
description: Please describe the issue in detail. Include specifics about missing information, outdated content, or improvements needed.
placeholder: |
Examples:
- Missing section on [topic]
- Incorrect information about [subject]
- Outdated example code for [feature]
- Suggestion to improve [section] by [details]
validations:
required: true
- type: textarea
id: expected-content
attributes:
label: Expected Content
description: If applicable, provide the content you believe should be added or updated.
placeholder: "Suggested details or changes for the documentation..."
- type: textarea
id: additional-info
attributes:
label: Additional Information
description: Add any other relevant information that may help us understand and resolve your issue.
placeholder: "Additional context, screenshots, or related links..."
- type: input
id: related-issue
attributes:
label: Related Issue
description: If this issue is related to an existing GitHub issue, provide the issue number.
placeholder: "#123"
- type: checkboxes
id: terms
attributes:
label: Code of Conduct
description: By submitting this issue, you agree to follow our [Code of Conduct](https://github.com/continuedev/continue/blob/main/CODE_OF_CONDUCT.md)
options:
- label: I agree to follow this project's Code of Conduct
required: true

View file

@ -96,7 +96,7 @@ jobs:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
install-gui:
needs: [install-root, install-core]
needs: [ install-root, install-core ]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
@ -157,7 +157,7 @@ jobs:
npx tsc --noEmit
binary-checks:
needs: [install-root, install-core]
needs: [ install-root, install-core ]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
@ -193,7 +193,7 @@ jobs:
npx tsc --noEmit
install-vscode:
needs: [install-root, install-core]
needs: [ install-root, install-core ]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
@ -277,7 +277,7 @@ jobs:
vscode-get-test-file-matrix:
runs-on: ubuntu-latest
needs: [install-root, install-vscode]
needs: [ install-root, install-vscode ]
outputs:
test_file_matrix: ${{ steps.vscode-get-test-file-matrix.outputs.test_file_matrix }}
steps:
@ -306,7 +306,7 @@ jobs:
vscode-package-extension:
runs-on: ubuntu-latest
needs: [install-vscode, install-core]
needs: [ install-vscode, install-core ]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
@ -338,7 +338,7 @@ jobs:
vscode-download-e2e-dependencies:
runs-on: ubuntu-latest
needs: [install-vscode, install-core]
needs: [ install-vscode, install-core ]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
@ -445,7 +445,7 @@ jobs:
path: extensions/vscode/e2e/storage/screenshots
gui-tests:
needs: [install-gui, install-core]
needs: [ install-gui, install-core ]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
@ -476,7 +476,7 @@ jobs:
npm test
jetbrains-tests:
needs: [install-root, install-core]
needs: [ install-root, core-checks ]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
@ -573,3 +573,5 @@ jobs:
name: jb-failure-report
path: |
${{ github.workspace }}/extensions/intellij/build/reports

View file

@ -188,7 +188,7 @@ After you've written your context provider, make sure to complete the following:
### Adding an LLM Provider
Continue has support for more than a dozen different LLM "providers", making it easy to use models running on OpenAI, Ollama, Together, LM Studio, Msty, and more. You can find all of the existing providers [here](https://github.com/continuedev/continue/tree/main/core/llm/llms), and if you see one missing, you can add it with the following steps:
Continue has support for more than a dozen different LLM "providers", making it easy to use models running on OpenAI, Ollama, Together, Novita AI, LM Studio, Msty, and more. You can find all of the existing providers [here](https://github.com/continuedev/continue/tree/main/core/llm/llms), and if you see one missing, you can add it with the following steps:
1. Create a new file in the `core/llm/llms` directory. The name of the file should be the name of the provider, and it should export a class that extends `BaseLLM`. This class should contain the following minimal implementation. We recommend viewing pre-existing providers for more details. The [LlamaCpp Provider](./core/llm/llms/LlamaCpp.ts) is a good simple example.
@ -209,7 +209,7 @@ While any model that works with a supported provider can be used with Continue,
1. Add a `ModelPackage` entry for the model into [configs/models.ts](./gui/src/pages/AddNewModel/configs/models.ts), following the lead of the many examples near the top of the file
2. Add the model within its provider's array to [AddNewModel.tsx](./gui/src/pages/AddNewModel/AddNewModel.tsx) (add provider if needed)
- [index.d.ts](./core/index.d.ts) - This file defines the TypeScript types used throughout Continue. You'll find a `ModelName` type. Be sure to add the name of your model to this.
- LLM Providers: Since many providers use their own custom strings to identify models, you'll have to add the translation from Continue's model name (the one you added to `index.d.ts`) and the model string for each of these providers: [Ollama](./core/llm/llms/Ollama.ts), [Together](./core/llm/llms/Together.ts), and [Replicate](./core/llm/llms/Replicate.ts). You can find their full model lists here: [Ollama](https://ollama.ai/library), [Together](https://docs.together.ai/docs/inference-models), [Replicate](https://replicate.com/collections/streaming-language-models).
- LLM Providers: Since many providers use their own custom strings to identify models, you'll have to add the translation from Continue's model name (the one you added to `index.d.ts`) and the model string for each of these providers: [Ollama](./core/llm/llms/Ollama.ts), [Together](./core/llm/llms/Together.ts), [Novita AI](./core/llm/llms/Novita.ts), and [Replicate](./core/llm/llms/Replicate.ts). You can find their full model lists here: [Ollama](https://ollama.ai/library), [Together](https://docs.together.ai/docs/inference-models), [Novita AI](https://novita.ai/llm-api?utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link), [Replicate](https://replicate.com/collections/streaming-language-models).
- [Prompt Templates](./core/llm/index.ts) - In this file you'll find the `autodetectTemplateType` function. Make sure that for the model name you just added, this function returns the correct template type. This is assuming that the chat template for that model is already built in Continue. If not, you will have to add the template type and corresponding edit and chat templates.
### Adding Pre-indexed Documentation

View file

@ -118,22 +118,6 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
}
(async () => {
// Informs of where to look for node_sqlite3.node https://www.npmjs.com/package/bindings#:~:text=The%20searching%20for,file%20is%20found
// This is only needed for our `pkg` command
fs.writeFileSync(
"out/package.json",
JSON.stringify(
{
name: "binary",
version: "1.0.0",
author: "Continue Dev, Inc",
license: "Apache-2.0",
},
undefined,
2,
),
);
console.log("[info] Downloading prebuilt lancedb...");
for (const target of targets) {
if (targetToLanceDb[target]) {
@ -209,6 +193,8 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
format: "cjs",
platform: "node",
sourcemap: true,
minify: true,
treeShaking: true,
loader: {
// eslint-disable-next-line @typescript-eslint/naming-convention
".node": "file",
@ -274,21 +260,19 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
`node_modules/${targetToLanceDb[target]}/index.node`,
`${targetDir}/index.node`,
);
// Informs the `continue-binary` of where to look for node_sqlite3.node
// https://www.npmjs.com/package/bindings#:~:text=The%20searching%20for,file%20is%20found
fs.writeFileSync(`${targetDir}/package.json`, "");
}
// Our dummy `package.json` is no longer needed so we can remove it.
// If it isn't removed, then running locally via `node out/index.js` will fail
// with a `Failed to locate bindings` error
fs.unlinkSync("out/package.json");
const pathsToVerify = [];
for (target of targets) {
for (const target of targets) {
const exe = target.startsWith("win") ? ".exe" : "";
const targetDir = `bin/${target}`;
pathsToVerify.push(
`${targetDir}/continue-binary${exe}`,
`${targetDir}/index.node`, // @lancedb
"package.json", // Informs of where to look for node_sqlite3.node https://www.npmjs.com/package/bindings#:~:text=The%20searching%20for,file%20is%20found
`${targetDir}/build/Release/node_sqlite3.node`,
);
}

View file

@ -23,8 +23,7 @@
"scripts": {
"test": "jest",
"build": "node build.js",
"build:dev": "tsc",
"esbuild": "node build.js --esbuild-only"
"build:darwin-x64": "node build.js --os darwin-x64"
},
"license": "Apache-2.0",
"devDependencies": {

View file

@ -1,8 +1,8 @@
import { SerializedContinueConfig } from "core";
// import Mock from "core/llm/llms/Mock.js";
import { FromIdeProtocol, ToIdeProtocol } from "core/protocol/index.js";
import FileSystemIde from "core/util/filesystem";
import { IMessenger } from "core/protocol/messenger";
import FileSystemIde from "core/util/filesystem";
import fs from "fs";
import {
ChildProcessWithoutNullStreams,
@ -186,10 +186,11 @@ describe("Test Suite", () => {
});
it("should return valid config object", async () => {
const { config } = await messenger.request(
const { result } = await messenger.request(
"config/getSerializedProfileInfo",
undefined,
);
const { config } = result;
expect(config).toHaveProperty("models");
expect(config).toHaveProperty("embeddingsProvider");
expect(config).toHaveProperty("contextProviders");
@ -229,18 +230,17 @@ describe("Test Suite", () => {
await messenger.request("config/addModel", {
model,
});
const { config } = await messenger.request(
"config/getSerializedProfileInfo",
undefined,
);
expect(config.models.some((m) => m.title === model.title)).toBe(true);
const {
result: { config },
} = await messenger.request("config/getSerializedProfileInfo", undefined);
expect(config!.models.some((m) => m.title === model.title)).toBe(true);
await messenger.request("config/deleteModel", { title: model.title });
const { config: configAfterDelete } = await messenger.request(
"config/getSerializedProfileInfo",
undefined,
);
expect(configAfterDelete.models.some((m) => m.title === model.title)).toBe(
const {
result: { config: configAfterDelete },
} = await messenger.request("config/getSerializedProfileInfo", undefined);
expect(configAfterDelete!.models.some((m) => m.title === model.title)).toBe(
false,
);
});

View file

@ -3,11 +3,9 @@ import { TRIAL_FIM_MODEL } from "../config/onboarding.js";
import { IDE, ILLM } from "../index.js";
import OpenAI from "../llm/llms/OpenAI.js";
import { DEFAULT_AUTOCOMPLETE_OPTS } from "../util/parameters.js";
import { PosthogFeatureFlag, Telemetry } from "../util/posthog.js";
import { shouldCompleteMultiline } from "./classification/shouldCompleteMultiline.js";
import { ContextRetrievalService } from "./context/ContextRetrievalService.js";
// @prettier-ignore
import { BracketMatchingService } from "./filtering/BracketMatchingService.js";
import { CompletionStreamer } from "./generation/CompletionStreamer.js";
@ -123,10 +121,10 @@ export class CompletionProvider {
}
private async _getAutocompleteOptions() {
const config = await this.configHandler.loadConfig();
const { config } = await this.configHandler.loadConfig();
const options = {
...DEFAULT_AUTOCOMPLETE_OPTS,
...config.tabAutocompleteOptions,
...config?.tabAutocompleteOptions,
};
return options;
}

View file

@ -7,7 +7,7 @@ Continue now provides support for tab autocomplete in [VS Code](https://marketpl
We recommend setting up tab-autocomplete with a local Ollama instance. To do this, first download the latest version of Ollama from [here](https://ollama.ai). Then, run the following command to download our recommended model:
```bash
ollama run qwen2.5-coder:1.5b
ollama run qwen2.5-coder:1.5b-base
```
Once it has been downloaded, you should begin to see completions in VS Code.
@ -101,7 +101,7 @@ This object allows you to customize the behavior of tab-autocomplete. The availa
"tabAutocompleteModel": {
"title": "Tab Autocomplete Model",
"provider": "ollama",
"model": "qwen2.5-coder:1.5b",
"model": "qwen2.5-coder:1.5b-base",
"apiBase": "https://<my endpoint>"
},
"tabAutocompleteOptions": {
@ -123,9 +123,9 @@ Follow these steps to ensure that everything is set up correctly:
1. Make sure you have the "Enable Tab Autocomplete" setting checked (in VS Code, you can toggle by clicking the "Continue" button in the status bar).
2. Make sure you have downloaded Ollama.
3. Run `ollama run qwen2.5-coder:1.5b` to verify that the model is downloaded.
3. Run `ollama run qwen2.5-coder:1.5b-base` to verify that the model is downloaded.
4. Make sure that any other completion providers are disabled (e.g. Copilot), as they may interfere.
5. Make sure that you aren't also using another Ollama model for chat. This will cause Ollama to constantly load and unload the models from memory, resulting in slow responses (or none at all) for both.
5. If you are using another Ollama model for chat and your resources are limited, this will cause Ollama to constantly load and unload the models from memory, resulting in slow responses (or none at all) for both. A resolution for this could be using the same model for chat and autocomplete.
6. Check the output of the logs to find any potential errors (cmd/ctrl+shift+p -> "Toggle Developer Tools" -> "Console" tab in VS Code, ~/.continue/logs/core.log in JetBrains).
7. If you are still having issues, please let us know in our [Discord](https://discord.gg/vapESyrFmJ) and we'll help as soon as possible.

View file

@ -316,6 +316,19 @@ export async function* skipLines(stream: LineStream): LineStream {
}
}
/**
* Handles cases where original lines have a trailing whitespace, but new lines do not.
* @param {LineStream} stream - The input stream of lines.
* @yields {string} Filtered lines that are stripped of trailing whitespace
*/
export async function* removeTrailingWhitespace(
stream: LineStream,
): LineStream {
for await (const line of stream) {
yield line.trimEnd();
}
}
/**
* Filters and processes lines from a code block, removing unnecessary markers and handling edge cases.
*

View file

@ -5,7 +5,7 @@ const CommitMessageCommand: SlashCommand = {
name: "commit",
description: "Generate a commit message for current changes",
run: async function* ({ ide, llm, params }) {
const includeUnstaged = params?.includeUnstaged ?? true;
const includeUnstaged = params?.includeUnstaged ?? false;
const diff = await ide.getDiff(includeUnstaged);
if (diff.length === 0) {

View file

@ -1,5 +1,6 @@
import { SlashCommand } from "../../index.js";
import { removeQuotesAndEscapes } from "../../util/index.js";
import { streamResponse } from "../../llm/stream.js";
const HttpSlashCommand: SlashCommand = {
name: "http",
@ -23,14 +24,8 @@ const HttpSlashCommand: SlashCommand = {
if (response.body === null) {
throw new Error("Response body is null");
}
const reader = response.body.getReader();
while (true) {
const { done, value } = await reader.read();
if (done) {
break;
}
const decoded = new TextDecoder("utf-8").decode(value);
yield decoded;
for await (const chunk of streamResponse(response)) {
yield chunk;
}
},
};

View file

@ -18,8 +18,8 @@ describe.skip("Test the ConfigHandler and E2E config loading", () => {
});
test("should load the default config successfully", async () => {
const config = await testConfigHandler.loadConfig();
expect(config.models.length).toBe(defaultConfig.models.length);
const result = await testConfigHandler.loadConfig();
expect(result.config!.models.length).toBe(defaultConfig.models.length);
});
test.skip("should add a system message from config.ts", async () => {

View file

@ -25,6 +25,7 @@ import {
ProfileDescription,
ProfileLifecycleManager,
} from "./ProfileLifecycleManager.js";
import { pathToFileURL } from "url";
export type { ProfileDescription };
@ -60,13 +61,13 @@ export class ConfigHandler {
// Always load local profile immediately in case control plane doesn't load
try {
this.loadConfig();
void this.loadConfig();
} catch (e) {
console.error("Failed to load config: ", e);
}
// Load control plane profiles
this.fetchControlPlaneProfiles();
void this.fetchControlPlaneProfiles();
}
// This will be the local profile
@ -88,7 +89,7 @@ export class ConfigHandler {
async openConfigProfile(profileId?: string) {
let openProfileId = profileId || this.selectedProfileId;
if (openProfileId === "local") {
await this.ide.openFile(getConfigJsonPath());
await this.ide.openFile(pathToFileURL(getConfigJsonPath()).toString());
} else {
await this.ide.openUrl(
"https://app.continue.dev/",
@ -146,12 +147,8 @@ export class ConfigHandler {
async setSelectedProfile(profileId: string) {
this.selectedProfileId = profileId;
const newConfig = await this.loadConfig();
this.notifyConfigListeners({
config: newConfig,
errors: undefined,
configLoadInterrupted: false,
});
const result = await this.loadConfig();
this.notifyConfigListeners(result);
const selectedProfiles =
this.globalContext.get("lastSelectedProfileForWorkspace") ?? {};
selectedProfiles[await this.getWorkspaceId()] = profileId;
@ -170,7 +167,7 @@ export class ConfigHandler {
// Automatically refresh config when Continue-related IDE (e.g. VS Code) settings are changed
updateIdeSettings(ideSettings: IdeSettings) {
this.ideSettingsPromise = Promise.resolve(ideSettings);
this.reloadConfig();
void this.reloadConfig();
}
updateControlPlaneSessionInfo(
@ -236,15 +233,15 @@ export class ConfigHandler {
return this.profiles.map((p) => p.profileDescription);
}
async loadConfig(): Promise<ContinueConfig> {
return (
await this.currentProfile.loadConfig(this.additionalContextProviders)
).config!; // <-- TODO
async loadConfig(): Promise<ConfigResult<ContinueConfig>> {
return await this.currentProfile.loadConfig(
this.additionalContextProviders,
);
}
async llmFromTitle(title?: string): Promise<ILLM> {
const config = await this.loadConfig();
const model = config.models.find((m) => m.title === title);
const { config } = await this.loadConfig();
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
@ -252,8 +249,8 @@ export class ConfigHandler {
model: LOCAL_ONBOARDING_CHAT_MODEL,
});
return ollama;
} else if (config.models.length > 0) {
return config.models[0];
} else if (config?.models?.length) {
return config?.models[0];
}
throw new Error("No model found");
@ -264,6 +261,6 @@ export class ConfigHandler {
registerCustomContextProvider(contextProvider: IContextProvider) {
this.additionalContextProviders.push(contextProvider);
this.reloadConfig();
void this.reloadConfig();
}
}

View file

@ -13,8 +13,8 @@ export interface ProfileDescription {
}
export class ProfileLifecycleManager {
private savedConfig: ConfigResult<ContinueConfig> | undefined;
private savedBrowserConfig?: BrowserSerializedContinueConfig;
private savedConfigResult: ConfigResult<ContinueConfig> | undefined;
private savedBrowserConfigResult?: ConfigResult<BrowserSerializedContinueConfig>;
private pendingConfigPromise?: Promise<ConfigResult<ContinueConfig>>;
constructor(private readonly profileLoader: IProfileLoader) {}
@ -35,15 +35,15 @@ export class ProfileLifecycleManager {
}
clearConfig() {
this.savedConfig = undefined;
this.savedBrowserConfig = undefined;
this.savedConfigResult = undefined;
this.savedBrowserConfigResult = undefined;
this.pendingConfigPromise = undefined;
}
// Clear saved config and reload
async reloadConfig(): Promise<ConfigResult<ContinueConfig>> {
this.savedConfig = undefined;
this.savedBrowserConfig = undefined;
this.savedConfigResult = undefined;
this.savedBrowserConfigResult = undefined;
this.pendingConfigPromise = undefined;
return this.loadConfig([], true);
@ -55,8 +55,8 @@ export class ProfileLifecycleManager {
): Promise<ConfigResult<ContinueConfig>> {
// If we already have a config, return it
if (!forceReload) {
if (this.savedConfig) {
return this.savedConfig;
if (this.savedConfigResult) {
return this.savedConfigResult;
} else if (this.pendingConfigPromise) {
return this.pendingConfigPromise;
}
@ -72,7 +72,7 @@ export class ProfileLifecycleManager {
result.config.contextProviders ?? []
).concat(additionalContextProviders);
this.savedConfig = result;
this.savedConfigResult = result;
resolve(result);
} else if (result.errors) {
reject(
@ -82,15 +82,17 @@ export class ProfileLifecycleManager {
});
// Wait for the config promise to resolve
this.savedConfig = await this.pendingConfigPromise;
this.savedConfigResult = await this.pendingConfigPromise;
this.pendingConfigPromise = undefined;
return this.savedConfig;
return this.savedConfigResult;
}
async getSerializedConfig(
additionalContextProviders: IContextProvider[],
): Promise<ConfigResult<BrowserSerializedContinueConfig>> {
if (!this.savedBrowserConfig) {
if (this.savedBrowserConfigResult) {
return this.savedBrowserConfigResult;
} else {
const result = await this.loadConfig(additionalContextProviders);
if (!result.config) {
return {
@ -98,12 +100,11 @@ export class ProfileLifecycleManager {
config: undefined,
};
}
this.savedBrowserConfig = finalToBrowserConfig(result.config);
const serializedConfig = finalToBrowserConfig(result.config);
return {
...result,
config: serializedConfig,
};
}
return {
config: this.savedBrowserConfig,
errors: [],
configLoadInterrupted: false,
};
}
}

View file

@ -7,6 +7,7 @@ import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
import { ContinueConfig, MCPOptions, SlashCommand, Tool } from "../..";
import { constructMcpSlashCommand } from "../../commands/slash/mcp";
import { ConfigValidationError } from "../../config/validation";
import { encodeMCPToolUri } from "../../tools/callTool";
import MCPContextProvider from "../providers/MCPContextProvider";
export class MCPManagerSingleton {
@ -71,6 +72,7 @@ class MCPConnection {
return new StdioClientTransport({
command: options.transport.command,
args: options.transport.args,
env: options.transport.env,
});
case "websocket":
return new WebSocketClientTransport(new URL(options.transport.url));
@ -132,7 +134,7 @@ class MCPConnection {
if (!error.message.startsWith("StdioClientTransport already started")) {
return {
fatal: false,
message: `Failed to connect to MCP ${mcpId}: ${error.message}`,
message: `Failed to connect to MCP: ${error.message}`,
};
}
}
@ -172,7 +174,7 @@ class MCPConnection {
readonly: false,
type: "function",
wouldLikeTo: `use the ${tool.name} tool`,
uri: `mcp://${tool.name}`,
uri: encodeMCPToolUri(mcpId, tool.name),
}));
config.tools = [...config.tools, ...continueTools];

View file

@ -0,0 +1,57 @@
import { BaseContextProvider } from "..";
import {
ContextItem,
ContextProviderDescription,
ContextProviderExtras,
ContextSubmenuItem,
LoadSubmenuItemsArgs,
} from "../..";
import { clipboardCache } from "../../util/clipboardCache";
const MAX_CLIPBOARD_ITEMS = 10;
class ClipboardContextProvider extends BaseContextProvider {
static description: ContextProviderDescription = {
title: "clipboard",
displayTitle: "Clipboard",
description: "Recent copies",
type: "submenu",
};
async getContextItems(
query: string,
extras: ContextProviderExtras,
): Promise<ContextItem[]> {
// Assume the query is a cache id
const id = query.trim();
const content = clipboardCache.get(id);
if (content) {
clipboardCache.select(id);
return [
{
name: "Clipboard item",
description: content.slice(0, 20),
content,
},
];
}
return [];
}
async loadSubmenuItems(
args: LoadSubmenuItemsArgs,
): Promise<ContextSubmenuItem[]> {
const recentClipboardItems = clipboardCache.getNItems(MAX_CLIPBOARD_ITEMS);
console.log(recentClipboardItems);
return recentClipboardItems.map((item, index) => {
return {
id: item.id,
title: item.content.slice(0, 20),
description: `#${index + 1}`,
};
});
}
}
export default ClipboardContextProvider;

View file

@ -80,22 +80,28 @@ class DocsContextProvider extends BaseContextProvider {
query: string,
extras: ContextProviderExtras,
): Promise<ContextItem[]> {
// Get docs service
const docsService = DocsService.getSingleton();
if (!docsService) {
console.error(`${DocsService.name} has not been initialized`);
return [];
}
await docsService.isInitialized;
// Get chunks
let chunks = await docsService.retrieveChunksFromQuery(
extras.fullInput, // confusing: fullInput = the query, query = startUrl in this case
query,
this.options?.nRetrieve ?? DocsContextProvider.nRetrieve,
);
if (!chunks?.length) {
return [];
}
// We found chunks, so check if there's a favicon for the docs page
const favicon = await docsService.getFavicon(query);
// Rerank if there's a rerankder
if (extras.reranker) {
chunks = await this._rerankChunks(
chunks,
@ -139,18 +145,30 @@ class DocsContextProvider extends BaseContextProvider {
async loadSubmenuItems(
args: LoadSubmenuItemsArgs,
): Promise<ContextSubmenuItem[]> {
// Get docs service
const docsService = DocsService.getSingleton();
if (!docsService) {
console.error(`${DocsService.name} has not been initialized`);
return [];
}
await docsService.isInitialized;
const docs = (await docsService.listMetadata()) ?? [];
const canUsePreindexedDocs = await docsService.canUsePreindexedDocs();
// Create map of docs url -> submenu item
const submenuItemsMap = new Map<string, ContextSubmenuItem>();
// Add custom docs from config
const docs = (await docsService.listMetadata()) ?? [];
for (const { startUrl, title, favicon } of docs) {
submenuItemsMap.set(startUrl, {
title,
id: startUrl,
description: new URL(startUrl).hostname,
icon: favicon,
});
}
// Add pre-indexed docs if supported
const canUsePreindexedDocs = await docsService.canUsePreindexedDocs();
if (canUsePreindexedDocs) {
for (const { startUrl, title } of Object.values(preIndexedDocs)) {
submenuItemsMap.set(startUrl, {
@ -164,17 +182,8 @@ class DocsContextProvider extends BaseContextProvider {
}
}
for (const { startUrl, title, favicon } of docs) {
submenuItemsMap.set(startUrl, {
title,
id: startUrl,
description: new URL(startUrl).hostname,
icon: favicon,
});
}
// Create array and sort if pre-indexed is supported
const submenuItems = Array.from(submenuItemsMap.values());
if (canUsePreindexedDocs) {
return this._sortByPreIndexedDocs(submenuItems);
}

View file

@ -22,6 +22,9 @@ class HttpContextProvider extends BaseContextProvider {
this.options.description ||
"Retrieve a context item from a custom server",
type: "normal",
renderInlineAs:
this.options.renderInlineAs ||
HttpContextProvider.description.renderInlineAs,
};
}

View file

@ -73,7 +73,15 @@ class MCPContextProvider extends BaseContextProvider {
async loadSubmenuItems(
args: LoadSubmenuItemsArgs,
): Promise<ContextSubmenuItem[]> {
return (this.options as MCPContextProviderOptions).submenuItems;
return (this.options as MCPContextProviderOptions).submenuItems.map(
(item, index) => ({
...item,
id: JSON.stringify({
mcpId: String(index),
uri: item.id,
}),
}),
);
}
}

View file

@ -1,15 +1,15 @@
import fetch from "node-fetch";
import { contextProviderClassFromName } from ".";
import {
ContextProviderExtras,
ContextProviderWithParams,
IContextProvider,
} from "../..";
import { ConfigHandler } from "../../config/ConfigHandler";
import { contextProviderClassFromName } from ".";
import { ControlPlaneClient } from "../../control-plane/client";
import FileSystemIde from "../../util/filesystem";
import { TEST_DIR } from "../../test/testDir";
import FileSystemIde from "../../util/filesystem";
const CONTEXT_PROVIDERS_TO_TEST: ContextProviderWithParams[] = [
{ name: "diff", params: {} },
@ -33,7 +33,10 @@ async function getContextProviderExtras(
async (text) => {},
new ControlPlaneClient(Promise.resolve(undefined)),
);
const config = await configHandler.loadConfig();
const { config } = await configHandler.loadConfig();
if (!config) {
throw new Error("Config not found");
}
return {
fullInput,

View file

@ -1,5 +1,6 @@
import { BaseContextProvider } from "../";
import { ContextProviderName } from "../../";
import ClipboardContextProvider from "./ClipboardContextProvider";
import CodeContextProvider from "./CodeContextProvider";
import ContinueProxyContextProvider from "./ContinueProxyContextProvider";
@ -62,6 +63,7 @@ export const Providers: (typeof BaseContextProvider)[] = [
GreptileContextProvider,
WebContextProvider,
MCPContextProvider,
ClipboardContextProvider,
];
export function contextProviderClassFromName(

View file

@ -12,7 +12,7 @@ import {
setupLocalConfigAfterFreeTrial,
setupQuickstartConfig,
} from "./config/onboarding";
import { addModel, deleteModel } from "./config/util";
import { addContextProvider, addModel, deleteModel } from "./config/util";
import { recentlyEditedFilesCache } from "./context/retrieval/recentlyEditedFilesCache";
import { ContinueServerClient } from "./continueServer/stubs/client";
import { getAuthUrlForTokenPage } from "./control-plane/auth/index";
@ -46,6 +46,7 @@ import * as URI from "uri-js";
import { SYSTEM_PROMPT_DOT_FILE } from "./config/getSystemPromptDotFile";
import type { IMessenger, Message } from "./protocol/messenger";
import { localPathToUri } from "./util/pathToUri";
import { clipboardCache } from "./util/clipboardCache";
export class Core {
// implements IMessenger<ToCoreProtocol, FromCoreProtocol>
@ -65,7 +66,7 @@ export class Core {
private abortedMessageIds: Set<string> = new Set();
private async config() {
return this.configHandler.loadConfig();
return (await this.configHandler.loadConfig()).config;
}
invoke<T extends keyof ToCoreProtocol>(
@ -120,11 +121,9 @@ export class Core {
);
this.configHandler.onConfigUpdate(async (result) => {
const serialized = await (
await this.configHandler.getSerializedConfig()
).config!;
const serializedResult = await this.configHandler.getSerializedConfig();
this.messenger.send("configUpdate", {
config: serialized,
result: serializedResult,
profileId: this.configHandler.currentProfile.profileId,
});
});
@ -178,12 +177,12 @@ export class Core {
});
const getLlm = async () => {
const config = await this.configHandler.loadConfig();
const { config } = await this.configHandler.loadConfig();
const selected = this.globalContext.get("selectedTabAutocompleteModel");
return (
config.tabAutocompleteModels?.find(
config?.tabAutocompleteModels?.find(
(model) => model.title === selected,
) ?? config.tabAutocompleteModels?.[0]
) ?? config?.tabAutocompleteModels?.[0]
);
};
this.completionProvider = new CompletionProvider(
@ -261,7 +260,7 @@ export class Core {
on("config/newPromptFile", async (msg) => {
await createNewPromptFileV2(
this.ide,
(await this.config()).experimental?.promptPath,
(await this.config())?.experimental?.promptPath,
);
await this.configHandler.reloadConfig();
});
@ -272,7 +271,7 @@ export class Core {
on("config/reload", async (msg) => {
void this.configHandler.reloadConfig();
return (await this.configHandler.getSerializedConfig()).config!; // <-- TODO
return await this.configHandler.getSerializedConfig();
});
on("config/ideSettingsUpdate", (msg) => {
@ -282,6 +281,10 @@ export class Core {
return this.configHandler.listProfiles();
});
on("config/addContextProvider", async (msg) => {
addContextProvider(msg.data);
});
// Context providers
on("context/addDocs", async (msg) => {
void this.docsService.indexAndAdd(msg.data);
@ -292,11 +295,16 @@ export class Core {
});
on("context/indexDocs", async (msg) => {
await this.docsService.syncOrReindexAllDocsWithPrompt(msg.data.reIndex);
await this.docsService.syncDocsWithPrompt(msg.data.reIndex);
});
on("context/loadSubmenuItems", async (msg) => {
console.log("Load SUMBENU ITEMS", msg);
const config = await this.config();
if (!config) {
return [];
}
const items = await config.contextProviders
?.find((provider) => provider.description.title === msg.data.title)
?.loadSubmenuItems({
@ -312,6 +320,10 @@ export class Core {
const { name, query, fullInput, selectedCode, selectedModelTitle } =
msg.data;
const config = await this.config();
if (!config) {
return [];
}
const llm = await this.configHandler.llmFromTitle(selectedModelTitle);
const provider = config.contextProviders?.find(
(provider) => provider.description.title === name,
@ -366,17 +378,27 @@ export class Core {
on("config/getSerializedProfileInfo", async (msg) => {
return {
config: (await this.configHandler.getSerializedConfig()).config!, // <-- TODO
result: await this.configHandler.getSerializedConfig(),
profileId: this.configHandler.currentProfile.profileId,
};
});
on("clipboardCache/add", (msg) => {
console.log("ADD TO CLIPBOARD", msg);
clipboardCache.add(uuidv4(), msg.data.content);
this.messenger.send("refreshSubmenuItems", undefined);
});
async function* llmStreamChat(
configHandler: ConfigHandler,
abortedMessageIds: Set<string>,
msg: Message<ToCoreProtocol["llm/streamChat"][0]>,
) {
const config = await configHandler.loadConfig();
const { config } = await configHandler.loadConfig();
if (!config) {
throw new Error("Config not loaded");
}
// Stop TTS on new StreamChat
if (config.experimental?.readResponseTTS) {
void TTS.kill();
@ -407,7 +429,6 @@ export class Core {
const chunk = next.value;
// @ts-ignore
yield { content: chunk };
next = await gen.next();
}
@ -480,7 +501,11 @@ export class Core {
return completion;
});
on("llm/listModels", async (msg) => {
const config = await this.configHandler.loadConfig();
const { config } = await this.configHandler.loadConfig();
if (!config) {
return [];
}
const model =
config.models.find((model) => model.title === msg.data.title) ??
config.models.find((model) => model.title?.startsWith(msg.data.title));
@ -533,7 +558,11 @@ export class Core {
selectedCode,
} = msg.data;
const config = await configHandler.loadConfig();
const { config } = await configHandler.loadConfig();
if (!config) {
throw new Error("Config not loaded");
}
const llm = await configHandler.llmFromTitle(modelTitle);
const slashCommand = config.slashCommands?.find(
(sc) => sc.name === slashCommandName,
@ -800,7 +829,7 @@ export class Core {
});
on("indexing/setPaused", async (msg) => {
if (msg.data.type === "docs") {
// this.docsService.setPaused(msg.data.id, msg.data.paused);
// this.docsService.setPaused(msg.data.id, msg.data.paused); // not supported yet
}
});
on("docs/getSuggestedDocs", async (msg) => {
@ -846,7 +875,11 @@ export class Core {
});
on("tools/call", async ({ data: { toolCall, selectedModelTitle } }) => {
const config = await this.configHandler.loadConfig();
const { config } = await this.configHandler.loadConfig();
if (!config) {
throw new Error("Config not loaded");
}
const tool = config.tools.find(
(t) => t.function.name === toolCall.function.name,
);

View file

@ -158,4 +158,12 @@ describe("deterministicApplyLazyEdit(", () => {
test("should acknowledge jsx_expression lazy comments", async () => {
await expectDiff("migration-page.tsx");
});
test.skip("should handle case where surrounding class is neglected, with lazy block surrounding", async () => {
await expectDiff("calculator-class-neglected.js");
});
test("should handle case where surrounding class is neglected, without lazy block surrounding", async () => {
await expectDiff("calculator-only-method.js");
});
});

View file

@ -1,3 +1,5 @@
import path from "path";
import { distance } from "fastest-levenshtein";
import Parser from "web-tree-sitter";
@ -7,10 +9,6 @@ import { myersDiff } from "../../diff/myers";
import { getParserForFile } from "../../util/treeSitter";
import { findInAst } from "./findInAst";
import {
getFileExtensionFromBasename,
getUriFileExtension,
} from "../../util/uri";
type AstReplacements = Array<{
nodeToReplace: Parser.SyntaxNode;
@ -104,6 +102,24 @@ function shouldRejectDiff(diff: DiffLine[]): boolean {
return false;
}
function nodeSurroundedInLazyBlocks(
parser: Parser,
file: string,
filename: string,
): { newTree: Parser.Tree; newFile: string } | undefined {
const ext = path.extname(filename).slice(1);
const language = LANGUAGES[ext];
if (language) {
const newFile = `${language.singleLineComment} ... existing code ...\n\n${file}\n\n${language.singleLineComment} ... existing code...`;
const newTree = parser.parse(newFile);
return { newTree, newFile };
}
return undefined;
}
// TODO: If we don't have high confidence, return undefined to fall back to slower methods
export async function deterministicApplyLazyEdit(
oldFile: string,
@ -117,6 +133,7 @@ export async function deterministicApplyLazyEdit(
const oldTree = parser.parse(oldFile);
let newTree = parser.parse(newLazyFile);
let reconstructedNewFile: string | undefined = undefined;
// If there is no lazy block anywhere, we add our own to the outsides
// so that large chunks of the file don't get removed
@ -127,24 +144,51 @@ export async function deterministicApplyLazyEdit(
);
if (firstSimilarNode?.parent?.equals(oldTree.rootNode)) {
// If so, we tack lazy blocks to start and end, and run the usual algorithm
const extension = getFileExtensionFromBasename(filename);
const language = LANGUAGES[extension];
if (language) {
newLazyFile = `${language.singleLineComment} ... existing code ...\n\n${newLazyFile}\n\n${language.singleLineComment} ... existing code...`;
newTree = parser.parse(newLazyFile);
const result = nodeSurroundedInLazyBlocks(parser, newLazyFile, filename);
if (result) {
newLazyFile = result.newFile;
newTree = result.newTree;
}
} else {
// If not, we need to recursively search for the nodes that are being rewritten,
// and we apply a slightly different algorithm
return undefined; // TODO
const newCodeNumLines = newTree.rootNode.text.split("\n").length;
const matchingNode = findInAst(
oldTree.rootNode,
(node) => programNodeIsSimilar(newTree.rootNode, node),
// This isn't perfect—we want the length of the matching code in the old tree
// and the new version could have more lines, or fewer. But should work a lot.
(node) => node.text.split("\n").length >= newCodeNumLines,
);
if (matchingNode) {
// Now that we've successfully matched the node from the old tree,
// we create the full new lazy file
const startIndex = matchingNode.startIndex;
const endIndex = matchingNode.endIndex;
const oldText = oldTree.rootNode.text;
reconstructedNewFile =
oldText.slice(0, startIndex) +
newTree.rootNode.text +
oldText.slice(endIndex);
} else {
console.warn("No matching node found for lazy block");
return undefined;
}
}
}
const replacements: AstReplacements = [];
findLazyBlockReplacements(oldTree.rootNode, newTree.rootNode, replacements);
if (!reconstructedNewFile) {
const replacements: AstReplacements = [];
findLazyBlockReplacements(oldTree.rootNode, newTree.rootNode, replacements);
const newFullFile = reconstructNewFile(oldFile, newLazyFile, replacements);
const diff = myersDiff(oldFile, newFullFile);
reconstructedNewFile = reconstructNewFile(
oldFile,
newLazyFile,
replacements,
);
}
const diff = myersDiff(oldFile, reconstructedNewFile);
// If the diff is too messy and seems likely borked, we fall back to LLM strategy
if (shouldRejectDiff(diff)) {
@ -181,6 +225,50 @@ function stringsWithinLevDistThreshold(
return dist / Math.min(a.length, b.length) <= threshold;
}
function programNodeIsSimilar(
programNode: Parser.SyntaxNode,
otherNode: Parser.SyntaxNode,
): boolean {
// Check purely based on whether they are similar strings
const newLines = programNode.text.split("\n");
const oldLines = otherNode.text.split("\n");
// Check that there is a line that matches the start of the old range
const oldFirstLine = oldLines[0].trim();
let matchForOldFirstLine = -1;
for (let i = 0; i < newLines.length; i++) {
if (newLines[i].trim() === oldFirstLine) {
matchForOldFirstLine = i;
break;
}
}
if (matchForOldFirstLine < 0) {
return false;
}
// Check that the last lines match each other
const oldLastLine = oldLines[oldLines.length - 1].trim();
const newLastLine = newLines[newLines.length - 1].trim();
if (oldLastLine !== newLastLine) {
return false;
}
// Check that the number of matching lines is at least half of the shorter length
let matchingLines = 0;
for (let i = 0; i < Math.min(newLines.length, oldLines.length); i++) {
if (oldLines[i].trim() === newLines[matchForOldFirstLine + i].trim()) {
matchingLines += 1;
}
}
if (matchingLines >= Math.max(newLines.length, oldLines.length) / 2) {
return true;
}
return false;
}
/**
* Determine whether two nodes are similar
* @param a

View file

@ -3,6 +3,7 @@ import Parser from "web-tree-sitter";
export function findInAst(
node: Parser.SyntaxNode,
criterion: (node: Parser.SyntaxNode) => boolean,
shouldRecurse: (node: Parser.SyntaxNode) => boolean = () => true,
): Parser.SyntaxNode | null {
const stack = [node];
while (stack.length > 0) {
@ -10,7 +11,10 @@ export function findInAst(
if (criterion(node)) {
return node;
}
stack.push(...node.children);
if (shouldRecurse(node)) {
stack.push(...node.children);
}
}
return null;
}

View file

@ -1,6 +1,7 @@
import {
filterLeadingAndTrailingNewLineInsertion,
filterLeadingNewline,
removeTrailingWhitespace,
stopAtLines,
} from "../../autocomplete/filtering/streamTransforms/lineStream.js";
import { streamDiff } from "../../diff/streamDiff.js";
@ -23,7 +24,10 @@ export async function* streamLazyApply(
}
const promptMessages = promptFactory(oldCode, filename, newCode);
const lazyCompletion = llm.streamChat(promptMessages, new AbortController().signal);
const lazyCompletion = llm.streamChat(
promptMessages,
new AbortController().signal,
);
// Do find and replace over the lazy edit response
async function* replacementFunction(
@ -46,6 +50,7 @@ export async function* streamLazyApply(
// lazyCompletionLines = filterEnglishLinesAtStart(lazyCompletionLines);
lazyCompletionLines = stopAtLines(lazyCompletionLines, () => {}, ["```"]);
lazyCompletionLines = filterLeadingNewline(lazyCompletionLines);
lazyCompletionLines = removeTrailingWhitespace(lazyCompletionLines);
// Fill in unchanged code
let lines = streamFillUnchangedCode(

View file

@ -0,0 +1,103 @@
class Calculator {
constructor() {
this.result = 0;
}
add(number) {
this.result += number;
return this;
}
subtract(number) {
this.result -= number;
return this;
}
multiply(number) {
this.result *= number;
return this;
}
divide(number) {
if (number === 0) {
throw new Error("Cannot divide by zero");
}
this.result /= number;
return this;
}
getResult() {
return this.result;
}
reset() {
this.result = 0;
return this;
}
}
---
// ... existing code ...
/**
* Divides the current result by the given number
* @param {number} number - The number to divide by
* @throws {Error} If attempting to divide by zero
* @returns {Calculator} The calculator instance for chaining
*/
divide(number) {
if (number === 0) {
throw new Error("Cannot divide by zero");
}
this.result /= number;
return this;
}
// ... existing code ...
---
class Calculator {
constructor() {
this.result = 0;
}
add(number) {
this.result += number;
return this;
}
subtract(number) {
this.result -= number;
return this;
}
multiply(number) {
this.result *= number;
return this;
}
+ /**
+ * Divides the current result by the given number
+ * @param {number} number - The number to divide by
+ * @throws {Error} If attempting to divide by zero
+ * @returns {Calculator} The calculator instance for chaining
+ */
divide(number) {
if (number === 0) {
throw new Error("Cannot divide by zero");
}
this.result /= number;
return this;
}
getResult() {
return this.result;
}
reset() {
this.result = 0;
return this;
}
}

View file

@ -0,0 +1,99 @@
class Calculator {
constructor() {
this.result = 0;
}
add(number) {
this.result += number;
return this;
}
subtract(number) {
this.result -= number;
return this;
}
multiply(number) {
this.result *= number;
return this;
}
divide(number) {
if (number === 0) {
throw new Error("Cannot divide by zero");
}
this.result /= number;
return this;
}
getResult() {
return this.result;
}
reset() {
this.result = 0;
return this;
}
}
---
/**
* Divides the current result by the given number
* @param {number} number - The number to divide by
* @throws {Error} If attempting to divide by zero
* @returns {Calculator} The calculator instance for chaining
*/
divide(number) {
if (number === 0) {
throw new Error("Cannot divide by zero");
}
this.result /= number;
return this;
}
---
class Calculator {
constructor() {
this.result = 0;
}
add(number) {
this.result += number;
return this;
}
subtract(number) {
this.result -= number;
return this;
}
multiply(number) {
this.result *= number;
return this;
}
+ /**
+ * Divides the current result by the given number
+ * @param {number} number - The number to divide by
+ * @throws {Error} If attempting to divide by zero
+ * @returns {Calculator} The calculator instance for chaining
+ */
divide(number) {
if (number === 0) {
throw new Error("Cannot divide by zero");
}
this.result /= number;
return this;
}
getResult() {
return this.result;
}
reset() {
this.result = 0;
return this;
}
}

View file

@ -1,16 +1,17 @@
import { ChatMessage, DiffLine, ILLM, Prediction } from "../";
import {
filterCodeBlockLines,
filterEnglishLinesAtEnd,
filterEnglishLinesAtStart,
filterLeadingAndTrailingNewLineInsertion,
removeTrailingWhitespace,
skipLines,
stopAtLines,
} from "../autocomplete/filtering/streamTransforms/lineStream.js";
import { streamDiff } from "../diff/streamDiff.js";
import { streamLines } from "../diff/util.js";
import { ChatMessage, DiffLine, ILLM, Prediction } from "../index.js";
import { gptEditPrompt } from "../llm/templates/edit.js";
import { Telemetry } from "../util/posthog.js";
} from "../autocomplete/filtering/streamTransforms/lineStream";
import { streamDiff } from "../diff/streamDiff";
import { streamLines } from "../diff/util";
import { gptEditPrompt } from "../llm/templates/edit";
import { Telemetry } from "../util/posthog";
function constructPrompt(
prefix: string,
@ -110,6 +111,7 @@ export async function* streamDiffLines(
lines = filterCodeBlockLines(lines);
lines = stopAtLines(lines, () => {});
lines = skipLines(lines);
lines = removeTrailingWhitespace(lines);
if (inept) {
// lines = fixCodeLlamaFirstLineIndentation(lines);
lines = filterEnglishLinesAtEnd(lines);

14
core/index.d.ts vendored
View file

@ -582,6 +582,16 @@ export interface IdeSettings {
enableDebugLogs: boolean;
}
export interface FileStats {
size: number;
lastModified: number;
}
/** Map of file name to stats */
export type FileStatsMap = {
[path: string]: FileStats;
};
export interface IDE {
getIdeInfo(): Promise<IdeInfo>;
@ -665,7 +675,7 @@ export interface IDE {
listDir(dir: string): Promise<[string, FileType][]>;
getLastModified(files: string[]): Promise<{ [path: string]: number }>;
getFileStats(files: string[]): Promise<FileStatsMap>;
getGitHubAuthToken(args: GetGhTokenArgs): Promise<string | undefined>;
@ -741,6 +751,7 @@ export type ContextProviderName =
| "issue"
| "repo-map"
| "url"
| "clipboard"
| string;
export type TemplateType =
@ -930,6 +941,7 @@ export interface StdioOptions {
type: "stdio";
command: string;
args: string[];
env?: Record<string, string>;
}
export interface WebSocketOptions {

View file

@ -1,7 +1,7 @@
import { jest } from "@jest/globals";
import { execSync } from "node:child_process";
import fs from "node:fs";
import path from "path";
import { jest } from "@jest/globals";
import { ContinueServerClient } from "../continueServer/stubs/client.js";
import { testConfigHandler, testIde } from "../test/fixtures.js";
@ -14,13 +14,12 @@ import {
} from "../test/testDir.js";
import { getIndexSqlitePath } from "../util/paths.js";
import { pathToFileURL } from "node:url";
import { CodebaseIndexer, PauseToken } from "./CodebaseIndexer.js";
import { getComputeDeleteAddRemove } from "./refreshIndex.js";
import { TestCodebaseIndex } from "./TestCodebaseIndex.js";
import { CodebaseIndex } from "./types.js";
import { walkDir } from "./walkDir.js";
import { pathToFileURL } from "node:url";
import { joinPathsToUri } from "../util/uri.js";
jest.useFakeTimers();
@ -120,7 +119,7 @@ describe("CodebaseIndexer", () => {
async function getIndexPlan() {
const workspaceFiles = await walkDir(TEST_DIR, testIde);
const [tag] = await testIde.getTags(testIndex.artifactId);
const stats = await testIde.getLastModified(workspaceFiles);
const stats = await testIde.getFileStats(workspaceFiles);
const [results, lastUpdated, markComplete] =
await getComputeDeleteAddRemove(

View file

@ -6,6 +6,7 @@ import { IDE, IndexingProgressUpdate, IndexTag } from "../index.js";
import { extractMinimalStackTraceInfo } from "../util/extractMinimalStackTraceInfo.js";
import { getIndexSqlitePath, getLanceDbPath } from "../util/paths.js";
import { findUriInDirs, getUriPathBasename } from "../util/uri.js";
import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex.js";
import { CodeSnippetsCodebaseIndex } from "./CodeSnippetsIndex.js";
import { FullTextSearchCodebaseIndex } from "./FullTextSearchCodebaseIndex.js";
@ -17,7 +18,6 @@ import {
RefreshIndexResults,
} from "./types.js";
import { walkDirAsync } from "./walkDir.js";
import { findUriInDirs, getUriPathBasename } from "../util/uri.js";
export class PauseToken {
constructor(private _paused: boolean) {}
@ -75,7 +75,11 @@ export class CodebaseIndexer {
}
protected async getIndexesToBuild(): Promise<CodebaseIndex[]> {
const config = await this.configHandler.loadConfig();
const { config } = await this.configHandler.loadConfig();
if (!config) {
return [];
}
const indexes = [
new ChunkCodebaseIndex(
this.ide.readFile.bind(this.ide),
@ -110,7 +114,7 @@ export class CodebaseIndexer {
const branch = await this.ide.getBranch(foundInDir);
const repoName = await this.ide.getRepoName(foundInDir);
const indexesToBuild = await this.getIndexesToBuild();
const stats = await this.ide.getLastModified([file]);
const stats = await this.ide.getFileStats([file]);
for (const index of indexesToBuild) {
const tag = {
directory: foundInDir,
@ -198,8 +202,8 @@ export class CodebaseIndexer {
return;
}
const config = await this.configHandler.loadConfig();
if (config.disableIndexing) {
const { config } = await this.configHandler.loadConfig();
if (config?.disableIndexing) {
yield {
progress,
desc: "Indexing is disabled in config.json",
@ -389,7 +393,7 @@ export class CodebaseIndexer {
branch: string,
repoName: string | undefined,
): AsyncGenerator<IndexingProgressUpdate> {
const stats = await this.ide.getLastModified(files);
const stats = await this.ide.getFileStats(files);
const indexesToBuild = await this.getIndexesToBuild();
let completedIndexCount = 0;
let progress = 0;

View file

@ -2,13 +2,13 @@ import { jest } from "@jest/globals";
import lance from "vectordb";
import { testConfigHandler, testIde } from "../test/fixtures";
import { getLanceDbPath } from "../util/paths";
import {
mockPathAndCacheKey,
mockTag,
testContinueServerClient,
updateIndexAndAwaitGenerator,
} from "./test/indexing";
import { getLanceDbPath } from "../util/paths";
import { LanceDbIndex } from "./LanceDbIndex";
import { DatabaseConnection, SqliteDb } from "./refreshIndex";
@ -26,7 +26,10 @@ describe.skip("ChunkCodebaseIndex", () => {
}
beforeAll(async () => {
const mockConfig = await testConfigHandler.loadConfig();
const { config: mockConfig } = await testConfigHandler.loadConfig();
if (!mockConfig) {
throw new Error("Failed to load config");
}
index = new LanceDbIndex(
mockConfig.embeddingsProvider,

View file

@ -28,7 +28,8 @@ describe.skip("DocsCrawler", () => {
let docsCrawler: DocsCrawler;
beforeAll(async () => {
config = await testConfigHandler.loadConfig();
const result = await testConfigHandler.loadConfig();
config = result.config!;
mockIde = new FileSystemIde(process.cwd());
chromiumInstaller = new ChromiumInstaller(mockIde, config);
docsCrawler = new DocsCrawler(mockIde, config);

View file

@ -74,7 +74,7 @@ describe.skip("DocsService Integration Tests", () => {
expect(await docsService.hasMetadata(mockSiteConfig.startUrl)).toBe(true);
// config.json check
expect(latestConfig.docs).toContainEqual(mockSiteConfig);
expect(latestConfig.config!.docs).toContainEqual(mockSiteConfig);
// Lance DB check
let retrievedChunks = await docsService.retrieveChunksFromQuery(
@ -92,7 +92,7 @@ describe.skip("DocsService Integration Tests", () => {
// config.json check
latestConfig = await getReloadedConfig();
expect(latestConfig.docs).not.toContainEqual(
expect(latestConfig.config!.docs).not.toContainEqual(
expect.objectContaining(mockSiteConfig),
);

View file

@ -16,9 +16,8 @@ import { addContextProvider } from "../../config/util";
import DocsContextProvider from "../../context/providers/DocsContextProvider";
import TransformersJsEmbeddingsProvider from "../../llm/llms/TransformersJsEmbeddingsProvider";
import { FromCoreProtocol, ToCoreProtocol } from "../../protocol";
import { fetchFavicon, getFaviconBase64 } from "../../util/fetchFavicon";
import { GlobalContext } from "../../util/GlobalContext";
import { IMessenger } from "../../protocol/messenger";
import { fetchFavicon, getFaviconBase64 } from "../../util/fetchFavicon";
import {
editConfigJson,
getDocsSqlitePath,
@ -26,6 +25,7 @@ import {
} from "../../util/paths";
import { Telemetry } from "../../util/posthog";
import { ConfigResult } from "../../config/load";
import { Article, chunkArticle, pageToArticle } from "./article";
import DocsCrawler from "./DocsCrawler";
import { runLanceMigrations, runSqliteMigrations } from "./migrations";
@ -87,7 +87,6 @@ export default class DocsService {
public isSyncing: boolean = false;
private docsIndexingQueue = new Set<string>();
private globalContext = new GlobalContext();
private lanceTableNamesSet = new Set<string>();
private config!: ContinueConfig;
@ -123,8 +122,8 @@ export default class DocsService {
// Initialization - load config and attach config listener
private async init(configHandler: ConfigHandler) {
const config = await configHandler.loadConfig();
await this.handleConfigUpdate({ config });
const result = await configHandler.loadConfig();
await this.handleConfigUpdate(result);
configHandler.onConfigUpdate(this.handleConfigUpdate.bind(this));
}
@ -144,7 +143,7 @@ export default class DocsService {
this.config.docs?.forEach((doc) => {
if (!doc.startUrl) {
console.error("Invalid config docs entry, no start");
console.error("Invalid config docs entry, no start url", doc.title);
return;
}
@ -183,20 +182,37 @@ export default class DocsService {
}
abort(startUrl: string) {
const status = this.statuses.get(startUrl);
if (status) {
if (this.docsIndexingQueue.has(startUrl)) {
const status = this.statuses.get(startUrl);
if (status) {
this.handleStatusUpdate({
...status,
status: "aborted",
progress: 0,
description: "Canceled",
});
}
this.docsIndexingQueue.delete(startUrl);
this.handleStatusUpdate({
...status,
status: "aborted",
progress: 0,
description: "Canceled",
});
}
}
isAborted(startUrl: string) {
return this.statuses.get(startUrl)?.status === "aborted";
shouldCancel(startUrl: string, startedWithEmbedder: string) {
// Check if aborted
const isAborted = this.statuses.get(startUrl)?.status === "aborted";
if (isAborted) {
return true;
}
// Handle indexing disabled change mid-indexing
if (this.config.disableIndexing) {
this.abort(startUrl);
return true;
}
// Handle embeddings provider change mid-indexing
if (this.config.embeddingsProvider.embeddingId !== startedWithEmbedder) {
this.abort(startUrl);
return true;
}
return false;
}
// NOTE Pausing not supported for docs yet
@ -247,102 +263,86 @@ export default class DocsService {
private async handleConfigUpdate({
config: newConfig,
}: {
config: ContinueConfig | undefined;
}) {
}: ConfigResult<ContinueConfig>) {
if (newConfig) {
const oldConfig = this.config;
this.config = newConfig; // IMPORTANT - need to set up top, other methods below use this without passing it in
this.docsCrawler = new DocsCrawler(this.ide, newConfig);
if (this.config.disableIndexing) {
return;
}
// No point in indexing if no docs context provider
const hasDocsContextProvider = this.hasDocsContextProvider();
if (!hasDocsContextProvider) {
return;
}
// Skip docs indexing if not supported
// No warning message here because would show on ANY config update
const unsupported =
await this.isUsingUnsupportedPreIndexedEmbeddingsProvider();
if (unsupported) {
return;
}
await this.syncOrReindexAllDocs(newConfig, oldConfig);
await this.syncDocs(oldConfig, newConfig, false);
}
}
private async syncOrReindexAllDocs(
newConfig: ContinueConfig,
oldConfig?: ContinueConfig,
) {
// On embeddings provider change, reindex all non-preindexed docs
// change = doesn't match last successful embeddings provider
const curEmbeddingsProviderId = this.globalContext.get(
"curEmbeddingsProviderId",
);
if (
!curEmbeddingsProviderId ||
curEmbeddingsProviderId !== newConfig.embeddingsProvider.embeddingId
) {
// If not set, we're initializing
const currentDocs = await this.listMetadata();
if (currentDocs.length > 0) {
await this.reindexDocsOnNewEmbeddingsProvider();
return;
}
}
await this.syncDocsOnConfigUpdate(oldConfig, newConfig);
}
async syncOrReindexAllDocsWithPrompt(reIndex: boolean = false) {
async syncDocsWithPrompt(reIndex: boolean = false) {
if (!this.hasDocsContextProvider()) {
const didAddDocsContextProvider =
await this.showAddDocsContextProviderToast();
const actionMsg = "Add 'docs' context provider";
const res = await this.ide.showToast(
"info",
"Starting docs indexing",
actionMsg,
);
if (!didAddDocsContextProvider) {
if (res === actionMsg) {
addContextProvider({
name: DocsContextProvider.description.title,
params: {},
});
void this.ide.showToast(
"info",
"Successfuly added docs context provider",
);
} else {
return;
}
}
await this.syncOrReindexAllDocs(this.config);
await this.syncDocs(undefined, this.config, reIndex);
void this.ide.showToast("info", "Docs indexing completed");
}
// Returns true if startUrl has been indexed with current embeddingsProvider
async hasMetadata(startUrl: string): Promise<Promise<boolean>> {
const db = await this.getOrCreateSqliteDb();
const title = await db.get(
`SELECT title FROM ${DocsService.sqlitebTableName} WHERE startUrl = ?`,
`SELECT title FROM ${DocsService.sqlitebTableName} WHERE startUrl = ? AND embeddingsProviderId = ?`,
startUrl,
this.config.embeddingsProvider.embeddingId,
);
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: {},
});
void this.ide.showToast(
"info",
"Successfuly added docs context provider",
);
}
return res === actionMsg;
}
async listMetadata() {
const embeddingsProvider = this.config.embeddingsProvider;
if (!embeddingsProvider) {
return [];
}
const db = await this.getOrCreateSqliteDb();
const docs = await db.all<SqliteDocsRow[]>(
`SELECT title, startUrl, favicon FROM ${DocsService.sqlitebTableName}`,
`SELECT title, startUrl, favicon FROM ${DocsService.sqlitebTableName}
WHERE embeddingsProviderId = ?`,
embeddingsProvider.embeddingId,
);
return docs;
@ -361,17 +361,29 @@ export default class DocsService {
siteIndexingConfig: SiteIndexingConfig,
reIndex: boolean = false,
): Promise<void> {
if (this.config.disableIndexing) {
console.warn("Attempting to add/index docs when indexing is disabled");
return;
}
const { startUrl } = siteIndexingConfig;
const canUsePreindexedDocs = await this.canUsePreindexedDocs();
if (canUsePreindexedDocs) {
const preIndexedDoc = preIndexedDocs[startUrl];
const isPreIndexedDoc = !!preIndexedDoc;
if (isPreIndexedDoc) {
console.warn("Can not override pre-indexed start urls");
return;
}
}
// Queue - indexAndAdd is invoked circularly by config edits. This prevents duplicate runs
if (this.docsIndexingQueue.has(startUrl)) {
return;
}
const embeddingsProvider = await this.getEmbeddingsProvider();
this.docsIndexingQueue.add(startUrl);
const startedWithEmbedder = this.config.embeddingsProvider.embeddingId;
const indexExists = await this.hasMetadata(startUrl);
// Build status update - most of it is fixed values
@ -405,13 +417,11 @@ export default class DocsService {
}
}
// If not preindexed
const isPreIndexedDoc = !!preIndexedDocs[siteIndexingConfig.startUrl];
if (!isPreIndexedDoc) {
this.addToConfig(siteIndexingConfig);
}
try {
this.docsIndexingQueue.add(startUrl);
this.addToConfig(siteIndexingConfig);
this.handleStatusUpdate({
...fixedStatus,
status: "indexing",
@ -428,7 +438,7 @@ export default class DocsService {
estimatedProgress += 1 / 2 ** (processedPages + 1);
// NOTE - during "indexing" phase, check if aborted before each status update
if (this.isAborted(startUrl)) {
if (this.shouldCancel(startUrl, startedWithEmbedder)) {
return;
}
this.handleStatusUpdate({
@ -466,7 +476,7 @@ export default class DocsService {
for (let i = 0; i < articles.length; i++) {
const article = articles[i];
if (this.isAborted(startUrl)) {
if (this.shouldCancel(startUrl, startedWithEmbedder)) {
return;
}
this.handleStatusUpdate({
@ -503,7 +513,7 @@ export default class DocsService {
`No embeddings were created for site: ${siteIndexingConfig.startUrl}\n Num chunks: ${chunks.length}`,
);
if (this.isAborted(startUrl)) {
if (this.shouldCancel(startUrl, startedWithEmbedder)) {
return;
}
this.handleStatusUpdate({
@ -521,7 +531,7 @@ export default class DocsService {
// Add docs to databases
console.log(`Adding ${embeddings.length} embeddings to db`);
if (this.isAborted(startUrl)) {
if (this.shouldCancel(startUrl, startedWithEmbedder)) {
return;
}
this.handleStatusUpdate({
@ -539,7 +549,7 @@ export default class DocsService {
const favicon = await fetchFavicon(new URL(siteIndexingConfig.startUrl));
if (this.isAborted(startUrl)) {
if (this.shouldCancel(startUrl, startedWithEmbedder)) {
return;
}
this.handleStatusUpdate({
@ -558,7 +568,7 @@ export default class DocsService {
this.docsIndexingQueue.delete(startUrl);
if (this.isAborted(startUrl)) {
if (this.shouldCancel(startUrl, startedWithEmbedder)) {
return;
}
this.handleStatusUpdate({
@ -577,7 +587,7 @@ export default class DocsService {
console.error("Error indexing docs", e);
this.handleStatusUpdate({
...fixedStatus,
description: `No embeddings were created for site: ${siteIndexingConfig.startUrl}`,
description: `Error getting docs from: ${siteIndexingConfig.startUrl}`,
status: "failed",
progress: 1,
});
@ -650,13 +660,18 @@ export default class DocsService {
return await this.retrieveChunks(startUrl, vector, nRetrieve);
}
// This is split into its own function so that it can be recursive
// in the case of fetching preindexed docs from s3
async retrieveChunks(
startUrl: string,
vector: number[],
nRetrieve: number,
isRetry: boolean = false,
): Promise<Chunk[]> {
const isPreIndexedDoc = !!preIndexedDocs[startUrl];
const preIndexedDoc = preIndexedDocs[startUrl];
const isPreIndexedDoc = !!preIndexedDoc;
// Lance doesn't have an embeddingsprovider column, instead it includes it in the table name
const table = await this.getOrCreateLanceTable({
initializationVector: vector,
isPreIndexedDoc,
@ -673,19 +688,21 @@ export default class DocsService {
console.warn("Error retrieving chunks from LanceDB", e);
}
const hasIndexedDoc = await this.hasMetadata(startUrl);
if (!hasIndexedDoc && docs.length === 0) {
const preIndexedDoc = preIndexedDocs[startUrl];
if (isRetry || !preIndexedDoc) {
// No docs are found for preindexed? try fetching once
if (docs.length === 0 && isPreIndexedDoc) {
if (isRetry) {
return [];
}
await this.fetchAndAddPreIndexedDocEmbeddings(preIndexedDoc.title);
return await this.retrieveChunks(startUrl, vector, nRetrieve, true);
}
if (isPreIndexedDoc) {
void Telemetry.capture("docs_pre_indexed_doc_used", {
doc: preIndexedDoc["title"],
});
}
return docs.map((doc) => ({
digest: doc.path,
filepath: doc.path,
@ -710,12 +727,13 @@ export default class DocsService {
await db.exec("PRAGMA busy_timeout = 3000;");
await runSqliteMigrations(db);
// First create the table if it doesn't exist
await db.exec(`CREATE TABLE IF NOT EXISTS ${DocsService.sqlitebTableName} (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title STRING NOT NULL,
startUrl STRING NOT NULL UNIQUE,
favicon STRING
startUrl STRING NOT NULL,
favicon STRING,
embeddingsProviderId STRING
)`);
this.sqliteDb = db;
@ -725,10 +743,17 @@ export default class DocsService {
}
async getFavicon(startUrl: string) {
if (!this.config.embeddingsProvider) {
console.warn(
"Attempting to get favicon without embeddings provider specified",
);
return;
}
const db = await this.getOrCreateSqliteDb();
const result = await db.get(
`SELECT favicon FROM ${DocsService.sqlitebTableName} WHERE startUrl = ?`,
`SELECT favicon FROM ${DocsService.sqlitebTableName} WHERE startUrl = ? AND embeddingsProviderId = ?`,
startUrl,
this.config.embeddingsProvider.embeddingId,
);
if (!result) {
@ -741,9 +766,10 @@ export default class DocsService {
Sync with no embeddings provider change
Ignores pre-indexed docs
*/
private async syncDocsOnConfigUpdate(
private async syncDocs(
oldConfig: ContinueConfig | undefined,
newConfig: ContinueConfig,
reindex: boolean,
) {
try {
this.isSyncing = true;
@ -753,6 +779,7 @@ export default class DocsService {
const newConfigDocs = newConfig.docs || [];
const newConfigStartUrls = newConfigDocs.map((doc) => doc.startUrl);
// NOTE since listMetadata filters by embeddings provider id embedding model changes are accounted for here
const currentlyIndexedDocs = await this.listMetadata();
const currentStartUrls = currentlyIndexedDocs.map((doc) => doc.startUrl);
@ -775,7 +802,9 @@ export default class DocsService {
const oldConfigDoc = oldConfigDocs.find(
(d) => d.startUrl === doc.startUrl,
);
// const currentStatus = this.statuses.get(doc.startUrl);
if (
// currentStatus?.status === "complete" &&
oldConfigDoc &&
(oldConfigDoc.maxDepth !== doc.maxDepth ||
oldConfigDoc.title !== doc.title ||
@ -863,9 +892,7 @@ export default class DocsService {
return name.replace(/[^a-zA-Z0-9_.-]/g, "_");
}
private async getLanceTableNameFromEmbeddingsProvider(
isPreIndexedDoc: boolean,
) {
private async getLanceTableName(isPreIndexedDoc: boolean) {
const embeddingsProvider =
await this.getEmbeddingsProvider(isPreIndexedDoc);
@ -886,7 +913,7 @@ export default class DocsService {
const conn = await lancedb.connect(getLanceDbPath());
const tableNames = await conn.tableNames();
const tableNameFromEmbeddingsProvider =
await this.getLanceTableNameFromEmbeddingsProvider(!!isPreIndexedDoc);
await this.getLanceTableName(!!isPreIndexedDoc);
if (!tableNames.includes(tableNameFromEmbeddingsProvider)) {
if (initializationVector) {
@ -943,24 +970,35 @@ export default class DocsService {
}: AddParams) {
const db = await this.getOrCreateSqliteDb();
await db.run(
`INSERT INTO ${DocsService.sqlitebTableName} (title, startUrl, favicon) VALUES (?, ?, ?)`,
`INSERT INTO ${DocsService.sqlitebTableName} (title, startUrl, favicon, embeddingsProviderId) VALUES (?, ?, ?, ?)`,
title,
startUrl,
favicon,
this.config.embeddingsProvider.embeddingId,
);
}
private addToConfig(siteIndexingConfig: SiteIndexingConfig) {
// Handles the case where a user has manually added the doc to config.json
// so it already exists in the file
const doesDocExist = this.config.docs?.some(
(doc) => doc.startUrl === siteIndexingConfig.startUrl,
const doesEquivalentDocExist = this.config.docs?.some(
(doc) =>
doc.startUrl === siteIndexingConfig.startUrl &&
doc.faviconUrl === siteIndexingConfig.faviconUrl &&
siteIndexingConfig.title === doc.title,
// siteIndexingConfig.maxDepth === doc.maxDepth &&
// doc.rootUrl === siteIndexingConfig.rootUrl,
);
if (!doesDocExist) {
if (!doesEquivalentDocExist) {
editConfigJson((config) => ({
...config,
docs: [...(config.docs ?? []), siteIndexingConfig],
docs: [
...(config.docs?.filter(
(doc) => doc.startUrl !== siteIndexingConfig.startUrl,
) ?? []),
siteIndexingConfig,
],
}));
}
}
@ -980,10 +1018,18 @@ export default class DocsService {
}
private async deleteMetadataFromSqlite(startUrl: string) {
if (!this.config.embeddingsProvider) {
console.warn(
`Attempting to delete metadata for ${startUrl} without embeddings provider specified`,
);
return;
}
const db = await this.getOrCreateSqliteDb();
await db.run(
`DELETE FROM ${DocsService.sqlitebTableName} WHERE startUrl = ?`,
`DELETE FROM ${DocsService.sqlitebTableName} WHERE startUrl = ? AND embeddingsProviderId = ?`,
startUrl,
this.config.embeddingsProvider.embeddingId,
);
}
@ -1011,34 +1057,4 @@ export default class DocsService {
this.deleteFromConfig(startUrl);
this.messenger?.send("refreshSubmenuItems", undefined);
}
/**
* Currently this deletes re-crawls + re-indexes all docs.
* A more optimal solution in the future will be to create
* a per-embeddings-provider table for docs.
*/
private async reindexDocsOnNewEmbeddingsProvider() {
// We use config as our source of truth here since it contains additional information
// needed for re-crawling such as `faviconUrl` and `maxDepth`.
const { docs, embeddingsProvider } = this.config;
if (!docs || docs.length === 0) {
return;
}
console.log(
`Reindexing non-preindexed docs with new embeddings provider: ${embeddingsProvider.embeddingId}`,
);
await Promise.allSettled(docs.map((doc) => this.indexAndAdd(doc)));
// Important that this only is invoked after we have successfully
// cleared and reindex the docs so that the table cannot end up in an
// invalid state.
this.globalContext.update(
"curEmbeddingsProviderId",
embeddingsProvider.embeddingId,
);
console.log("Completed reindexing of all non-preindexed docs");
}
}

View file

@ -27,41 +27,65 @@ export async function runLanceMigrations(table: Table) {
export async function runSqliteMigrations(db: Database) {
await new Promise((resolve) => {
migrate(
void migrate(
"sqlite_modify_docs_columns_and_copy_to_config",
async () => {
try {
const pragma = await db.all(
`PRAGMA table_info(${DocsService.sqlitebTableName})`,
`PRAGMA table_info(${DocsService.sqlitebTableName});`,
);
const hasFaviconCol = pragma.some(
(pragma) => pragma.name === "favicon",
);
if (!hasFaviconCol) {
await db.exec(
`ALTER TABLE ${DocsService.sqlitebTableName} ADD COLUMN favicon BLOB;`,
);
}
const hasBaseUrlCol = pragma.some(
(pragma) => pragma.name === "baseUrl",
);
if (!hasFaviconCol) {
await db.exec(
`ALTER TABLE ${DocsService.sqlitebTableName} ADD COLUMN favicon BLOB`,
);
}
if (hasBaseUrlCol) {
await db.exec(
`ALTER TABLE ${DocsService.sqlitebTableName} RENAME COLUMN baseUrl TO startUrl`,
`ALTER TABLE ${DocsService.sqlitebTableName} RENAME COLUMN baseUrl TO startUrl;`,
);
}
const sqliteDocs = await db.all<
Array<Pick<SqliteDocsRow, "title" | "startUrl">>
>(`SELECT title, startUrl FROM ${DocsService.sqlitebTableName}`);
const needsToUpdateConfig = !hasFaviconCol || hasBaseUrlCol;
if (needsToUpdateConfig) {
const sqliteDocs = await db.all<
Array<Pick<SqliteDocsRow, "title" | "startUrl">>
>(`SELECT title, startUrl FROM ${DocsService.sqlitebTableName}`);
editConfigJson((config) => ({
...config,
docs: [...(config.docs || []), ...sqliteDocs],
}));
}
} finally {
resolve(undefined);
}
},
() => resolve(undefined),
);
});
editConfigJson((config) => ({
...config,
docs: [...(config.docs || []), ...sqliteDocs],
}));
await new Promise((resolve) => {
void migrate(
"sqlite_delete_docs_with_no_embeddingsProviderId",
async () => {
try {
const pragma = await db.all(
`PRAGMA table_info(${DocsService.sqlitebTableName});`,
);
const hasEmbeddingsProviderColumn = pragma.some(
(pragma) => pragma.name === "embeddingsProviderId",
);
if (!hasEmbeddingsProviderColumn) {
// gotta just delete in this case since old docs will be unusable anyway
await db.exec(`DROP TABLE ${DocsService.sqlitebTableName};`);
}
} finally {
resolve(undefined);
}

View file

@ -5,13 +5,12 @@ import plimit from "p-limit";
import { open, type Database } from "sqlite";
import sqlite3 from "sqlite3";
import { IndexTag, IndexingProgressUpdate } from "../index.js";
import { FileStatsMap, IndexTag, IndexingProgressUpdate } from "../index.js";
import { getIndexSqlitePath } from "../util/paths.js";
import {
CodebaseIndex,
IndexResultType,
LastModifiedMap,
MarkCompleteCallback,
PathAndCacheKey,
RefreshIndexResults,
@ -127,9 +126,12 @@ enum AddRemoveResultType {
Compute = "compute",
}
// Don't attempt to index anything over 5MB
const MAX_FILE_SIZE_BYTES = 5 * 1024 * 1024;
async function getAddRemoveForTag(
tag: IndexTag,
currentFiles: LastModifiedMap,
currentFiles: FileStatsMap,
readFile: (path: string) => Promise<string>,
): Promise<
[
@ -142,6 +144,12 @@ async function getAddRemoveForTag(
const newLastUpdatedTimestamp = Date.now();
const files = { ...currentFiles };
for (const path in files) {
if (files[path].size > MAX_FILE_SIZE_BYTES) {
delete files[path];
}
}
const saved = await getSavedItemsForTag(tag);
const updateNewVersion: PathAndCacheKey[] = [];
@ -157,7 +165,7 @@ async function getAddRemoveForTag(
remove.push(pathAndCacheKey);
} else {
// Exists in old and new, so determine whether it was updated
if (lastUpdated < files[item.path]) {
if (lastUpdated < files[item.path].lastModified) {
// Change was made after last update
const newHash = calculateHash(await readFile(pathAndCacheKey.path));
if (pathAndCacheKey.cacheKey !== newHash) {
@ -345,7 +353,7 @@ function mapIndexResultTypeToAddRemoveResultType(
export async function getComputeDeleteAddRemove(
tag: IndexTag,
currentFiles: LastModifiedMap,
currentFiles: FileStatsMap,
readFile: (path: string) => Promise<string>,
repoName: string | undefined,
): Promise<[RefreshIndexResults, PathAndCacheKey[], MarkCompleteCallback]> {

View file

@ -36,8 +36,4 @@ export type RefreshIndexResults = {
removeTag: PathAndCacheKey[];
};
export type LastModifiedMap = {
[path: string]: number;
};
export type RefreshIndex = (tag: IndexTag) => Promise<RefreshIndexResults>;

View file

@ -41,6 +41,7 @@ const PROVIDER_HANDLES_TEMPLATING: string[] = [
"openai",
"ollama",
"together",
"novita",
"msty",
"anthropic",
"bedrock",
@ -130,6 +131,7 @@ const PARALLEL_PROVIDERS: string[] = [
"free-trial",
"replicate",
"together",
"novita",
"sambanova",
"nebius",
"vertexai",

View file

@ -809,12 +809,12 @@ export abstract class BaseLLM implements ILLM {
if (this.shouldUseOpenAIAdapter("embed") && this.openaiAdapter) {
const result = await this.openaiAdapter.embed({
model: this.model,
input: chunks,
input: batch,
});
return result.data.map((chunk) => chunk.embedding);
}
return await this._embed(chunks);
return await this._embed(batch);
},
);

View file

@ -10,7 +10,7 @@ class Anthropic extends BaseLLM {
contextLength: 200_000,
completionOptions: {
model: "claude-3-5-sonnet-latest",
maxTokens: 4096,
maxTokens: 8192,
},
apiBase: "https://api.anthropic.com/v1/",
};

44
core/llm/llms/Novita.ts Normal file
View file

@ -0,0 +1,44 @@
import OpenAI from "./OpenAI.js";
import type { CompletionOptions, LLMOptions } from "../../index.js";
class Novita extends OpenAI {
static providerName = "novita";
static defaultOptions: Partial<LLMOptions> = {
apiBase: "https://api.novita.ai/v3/openai/",
};
private static MODEL_IDS: { [name: string]: string } = {
"llama3-8b": "meta-llama/llama-3-8b-instruct",
"llama3-70b": "meta-llama/llama-3-70b-instruct",
"llama3.1-8b": "meta-llama/llama-3.1-8b-instruct",
"llama3.1-70b": "meta-llama/llama-3.1-70b-instruct",
"llama3.1-405b": "meta-llama/llama-3.1-405b-instruct",
"llama3.2-1b": "meta-llama/llama-3.2-1b-instruct",
"llama3.2-3b": "meta-llama/llama-3.2-3b-instruct",
"llama3.2-11b": "meta-llama/llama-3.2-11b-vision-instruct",
"llama3.3-70b": "meta-llama/llama-3.3-70b-instruct",
"mistral-nemo": "mistralai/mistral-nemo",
"mistral-7b": "mistralai/mistral-7b-instruct",
};
protected _convertModelName(model: string) {
return Novita.MODEL_IDS[model] || this.model;
}
protected async *_streamComplete(
prompt: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
for await (const chunk of this._legacystreamComplete(
prompt,
signal,
options,
)) {
yield chunk;
}
}
}
export default Novita;

View file

@ -48,6 +48,7 @@ import ContinueProxy from "./stubs/ContinueProxy";
import TestLLM from "./Test";
import TextGenWebUI from "./TextGenWebUI";
import Together from "./Together";
import Novita from "./Novita";
import VertexAI from "./VertexAI";
import Vllm from "./Vllm";
import WatsonX from "./WatsonX";
@ -65,6 +66,7 @@ export const LLMClasses = [
Replicate,
TextGenWebUI,
Together,
Novita,
HuggingFaceTGI,
HuggingFaceInferenceAPI,
Kindo,

View file

@ -6,6 +6,7 @@ import type {
ChatMessage,
ContextItem,
ContextItemWithId,
ContextProviderWithParams,
ContextSubmenuItem,
DiffLine,
FileSymbolMap,
@ -20,11 +21,28 @@ import type {
SiteIndexingConfig,
ToolCall,
} from "../";
import { ConfigResult } from "../config/load";
export type ProtocolGeneratorType<T> = AsyncGenerator<{
export type ProtocolGeneratorYield<T> = {
done?: boolean;
content: T;
}>;
};
export type ProtocolGeneratorType<Y> = AsyncGenerator<
ProtocolGeneratorYield<Y>
>;
export type AsyncGeneratorYieldType<T> =
T extends AsyncGenerator<infer Y, any, any>
? Y extends ProtocolGeneratorYield<infer PR>
? PR
: never
: never;
// export type AsyncGeneratorReturnType<T> =
// T extends AsyncGenerator<any, infer R, any>
// ? R extends ProtocolGeneratorYield<infer PR>
// ? PR
// : never
// : never;
export type OnboardingModes =
| "Local"
@ -63,10 +81,14 @@ export type ToCoreFromIdeOrWebviewProtocol = {
"config/ideSettingsUpdate": [IdeSettings, void];
"config/getSerializedProfileInfo": [
undefined,
{ config: BrowserSerializedContinueConfig; profileId: string },
{
result: ConfigResult<BrowserSerializedContinueConfig>;
profileId: string;
},
];
"config/deleteModel": [{ title: string }, void];
"config/reload": [undefined, BrowserSerializedContinueConfig];
"config/addContextProvider": [ContextProviderWithParams, void];
"config/reload": [undefined, ConfigResult<BrowserSerializedContinueConfig>];
"config/listProfiles": [undefined, ProfileDescription[]];
"config/openProfile": [{ profileId: string | undefined }, void];
"context/getContextItems": [
@ -189,4 +211,5 @@ export type ToCoreFromIdeOrWebviewProtocol = {
{ toolCall: ToolCall; selectedModelTitle: string },
{ contextItems: ContextItem[] },
];
"clipboardCache/add": [{ content: string }, void];
};

View file

@ -3,6 +3,7 @@ import { ControlPlaneSessionInfo } from "../control-plane/client";
import type {
ContinueRcJson,
DiffLine,
FileStatsMap,
FileType,
IDE,
IdeInfo,
@ -84,7 +85,7 @@ export type ToIdeFromWebviewOrCoreProtocol = {
];
getGitRootPath: [{ dir: string }, string | undefined];
listDir: [{ dir: string }, [string, FileType][]];
getLastModified: [{ files: string[] }, { [path: string]: number }];
getFileStats: [{ files: string[] }, FileStatsMap];
gotoDefinition: [{ location: Location }, RangeInFile[]];

View file

@ -43,7 +43,7 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
vscMediaUrl: string;
},
];
"jetbrains/getColors": [undefined, void];
"jetbrains/getColors": [undefined, Record<string, string>];
"vscode/openMoveRightMarkdown": [undefined, void];
setGitHubAuthToken: [{ token: string }, void];
acceptDiff: [{ filepath: string; streamId?: string }, void];

View file

@ -1,8 +1,9 @@
import { GetGhTokenArgs, ToIdeFromWebviewOrCoreProtocol } from "../ide";
import { FromIdeProtocol } from "..";
import { GetGhTokenArgs, ToIdeFromWebviewOrCoreProtocol } from "../ide";
import type {
ContinueRcJson,
FileStatsMap,
FileType,
IDE,
IdeInfo,
@ -43,8 +44,8 @@ export class MessageIde implements IDE {
getGitHubAuthToken(args: GetGhTokenArgs): Promise<string | undefined> {
return this.request("getGitHubAuthToken", args);
}
getLastModified(files: string[]): Promise<{ [path: string]: number }> {
return this.request("getLastModified", { files });
getFileStats(files: string[]): Promise<FileStatsMap> {
return this.request("getFileStats", { files });
}
getGitRootPath(dir: string): Promise<string | undefined> {
return this.request("getGitRootPath", { dir });

View file

@ -38,8 +38,8 @@ export class ReverseMessageIde {
return this.ide.getGitHubAuthToken(data);
});
this.on("getLastModified", (data) => {
return this.ide.getLastModified(data.files);
this.on("getFileStats", (data) => {
return this.ide.getFileStats(data.files);
});
this.on("getGitRootPath", (data) => {

View file

@ -16,6 +16,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
"history/save",
"devdata/log",
"config/addModel",
"config/addContextProvider",
"config/newPromptFile",
"config/ideSettingsUpdate",
"config/getSerializedProfileInfo",
@ -60,6 +61,8 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
];
// Message types to pass through from core to webview
// Note: If updating these values, make a corresponding update in
// extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt
export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] =
[
"configUpdate",

View file

@ -1,3 +1,4 @@
import { ConfigResult } from "../config/load.js";
import { ConfigValidationError } from "../config/validation.js";
import type {
@ -10,7 +11,10 @@ import type {
export type ToWebviewFromIdeOrCoreProtocol = {
configUpdate: [
{ config: BrowserSerializedContinueConfig; profileId: string },
{
result: ConfigResult<BrowserSerializedContinueConfig>;
profileId: string;
},
void,
];
configError: [ConfigValidationError[] | undefined, void];

View file

@ -44,7 +44,10 @@ export function decodeMCPToolUri(uri: string): [string, string] | null {
if (url.protocol !== "mcp:") {
return null;
}
return [decodeURIComponent(url.hostname), decodeURIComponent(url.pathname)];
return [
decodeURIComponent(url.hostname),
decodeURIComponent(url.pathname).slice(1), // to remove leading '/'
];
}
async function callToolFromUri(
@ -52,6 +55,7 @@ async function callToolFromUri(
args: any,
extras: ToolExtras,
): Promise<ContextItem[]> {
// @ts-ignore
const canParse = URL.canParse(uri);
if (!canParse) {
throw new Error(`Invalid URI: ${uri}`);

View file

@ -3,13 +3,13 @@ import { inferResolvedUriFromRelativePath } from "../../util/ideUtils";
import { ToolImpl } from ".";
export const createNewFileImpl: ToolImpl = async (args, extras) => {
const resolvedFilepath = await inferResolvedUriFromRelativePath(
const resolvedFileUri = await inferResolvedUriFromRelativePath(
args.filepath,
extras.ide,
);
if (resolvedFilepath) {
await extras.ide.writeFile(resolvedFilepath, args.contents);
await extras.ide.openFile(resolvedFilepath);
if (resolvedFileUri) {
await extras.ide.writeFile(resolvedFileUri, args.contents);
await extras.ide.openFile(resolvedFileUri);
}
return [];
};

View file

@ -75,7 +75,7 @@ describe("GlobalContext", () => {
const value = globalContext.get("indexingPaused");
expect(value).toBeUndefined();
expect(consoleWarnMock).toHaveBeenCalledWith(
expect.stringContaining("Error parsing global context")
expect.stringContaining("Error parsing global context"),
);
// Clean up
@ -99,7 +99,7 @@ describe("GlobalContext", () => {
expect(value).toBeUndefined();
expect(consoleWarnMock).toHaveBeenCalledWith(
expect.stringContaining("Error updating global context")
expect.stringContaining("Error updating global context"),
);
// Clean up
@ -113,10 +113,10 @@ describe("GlobalContext", () => {
expect(globalContext.get("indexingPaused")).toBe(true);
expect(globalContext.get("selectedTabAutocompleteModel")).toBe(
"test-model"
"test-model",
);
expect(globalContext.get("hasDismissedConfigTsNoticeJetBrains")).toBe(
false
false,
);
});
@ -125,16 +125,7 @@ describe("GlobalContext", () => {
expect(globalContext.get("hasAlreadyCreatedAPromptFile")).toBe(true);
});
it("should handle curEmbeddingsProviderId correctly", () => {
globalContext.update("curEmbeddingsProviderId", "test-provider-id");
expect(globalContext.get("curEmbeddingsProviderId")).toBe(
"test-provider-id"
);
});
it("should not crash or throw when getting a key that hasn't been set", () => {
expect(
globalContext.get("hasAlreadyCreatedAPromptFile")
).toBeUndefined();
expect(globalContext.get("hasAlreadyCreatedAPromptFile")).toBeUndefined();
});
});
});

View file

@ -12,7 +12,6 @@ export type GlobalContextType = {
*
* For VS Code users, it is unnecessary since we use transformers.js by default.
*/
curEmbeddingsProviderId: string;
hasDismissedConfigTsNoticeJetBrains: boolean;
hasAlreadyCreatedAPromptFile: boolean;
showConfigUpdateToast: boolean;

View file

@ -8,7 +8,7 @@ import type { IMessenger } from "../protocol/messenger";
export class ChatDescriber {
static maxTokens = 12;
static prompt: string | undefined =
"Given the following... please reply with a short summary that is 4-8 words in length, you should summarize what the user is asking for OR what the user is trying to accomplish. You should only respond with the summary, no additional text or explanation, you don't need ending punctuation.\n\n";
"Given the following... please reply with a title for the chat that is 3-4 words in length, all words used should be directly related to the content of the chat, avoid using verbs unless they are directly related to the content of the chat, no additional text or explanation, you don't need ending punctuation.\n\n";
static messenger: IMessenger<ToCoreProtocol, FromCoreProtocol>;
static async describe(

View file

@ -0,0 +1,54 @@
class ClipboardCache {
private cache: Map<string, string>;
private order: string[];
private readonly maxSize = 30;
constructor() {
this.cache = new Map();
this.order = [];
}
add(id: string, content: string): void {
if (!content) {
return;
}
if (this.order.length >= this.maxSize) {
const oldest = this.order.pop();
if (oldest) {
this.cache.delete(oldest);
}
}
this.cache.set(id, content);
this.order.unshift(id);
}
getNItems(count: number): {
id: string;
content: string;
}[] {
return this.order.slice(0, count).map((id) => ({
id,
content: this.cache.get(id) || "",
}));
}
get(id: string): string | undefined {
return this.cache.get(id);
}
select(id: string): void {
const index = this.order.indexOf(id);
if (index > -1) {
this.order.splice(index, 1);
this.order.unshift(id);
}
}
clear(): void {
this.cache.clear();
this.order = [];
}
}
export const clipboardCache = new ClipboardCache();

View file

@ -1,7 +1,9 @@
import * as fs from "node:fs";
import { fileURLToPath } from "node:url";
import {
ContinueRcJson,
FileStatsMap,
FileType,
IDE,
IdeInfo,
@ -15,7 +17,6 @@ import {
ToastType,
} from "../index.js";
import { GetGhTokenArgs } from "../protocol/ide.js";
import { fileURLToPath } from "node:url";
class FileSystemIde implements IDE {
constructor(private readonly workspaceDir: string) {}
@ -51,15 +52,16 @@ class FileSystemIde implements IDE {
async getGitHubAuthToken(args: GetGhTokenArgs): Promise<string | undefined> {
return undefined;
}
async getLastModified(
fileUris: string[],
): Promise<{ [path: string]: number }> {
const result: { [path: string]: number } = {};
async getFileStats(fileUris: string[]): Promise<FileStatsMap> {
const result: FileStatsMap = {};
for (const uri of fileUris) {
try {
const filepath = fileURLToPath(uri);
const stats = fs.statSync(filepath);
result[uri] = stats.mtimeMs;
result[uri] = {
lastModified: stats.mtimeMs,
size: stats.size,
};
} catch (error) {
console.error(`Error getting last modified time for ${uri}:`, error);
}

View file

@ -1,5 +1,10 @@
import { IDE } from "..";
import { joinPathsToUri, pathToUriPathSegment } from "./uri";
import {
joinEncodedUriPathSegmentToUri,
joinPathsToUri,
pathToUriPathSegment,
} from "./uri";
/*
This function takes a relative (to workspace) filepath
@ -29,28 +34,28 @@ export async function resolveRelativePathInDir(
If no meaninful path match just concatenates to first dir's uri
*/
export async function inferResolvedUriFromRelativePath(
path: string,
relativePath: string,
ide: IDE,
dirCandidates?: string[],
): Promise<string> {
const dirs = dirCandidates ?? (await ide.getWorkspaceDirs());
console.log(path, dirs);
if (dirs.length === 0) {
throw new Error("inferResolvedUriFromRelativePath: no dirs provided");
}
const segments = pathToUriPathSegment(path).split("/");
const segments = pathToUriPathSegment(relativePath).split("/");
// Generate all possible suffixes from shortest to longest
const suffixes: string[] = [];
for (let i = segments.length - 1; i >= 0; i--) {
suffixes.push(segments.slice(i).join("/"));
}
console.log(suffixes);
// For each suffix, try to find a unique matching directory
for (const suffix of suffixes) {
const uris = dirs.map((dir) => ({
dir,
partialUri: joinPathsToUri(dir, suffix),
partialUri: joinEncodedUriPathSegmentToUri(dir, suffix),
}));
const promises = uris.map(async ({ partialUri, dir }) => {
const exists = await ide.fileExists(partialUri);
@ -66,15 +71,13 @@ export async function inferResolvedUriFromRelativePath(
// If exactly one directory matches, use it
if (existingUris.length === 1) {
return joinPathsToUri(existingUris[0].dir, segments.join("/"));
return joinEncodedUriPathSegmentToUri(
existingUris[0].dir,
segments.join("/"),
);
}
}
// If no unique match found, use the first directory
return joinPathsToUri(dirs[0], path);
}
interface ResolveResult {
resolvedUri: string;
matchedDir: string;
return joinPathsToUri(dirs[0], relativePath);
}

View file

@ -1,9 +1,7 @@
// Generated by continue
import * as URI from "uri-js";
import {
pathToUriPathSegment,
findUriInDirs,
relativePathOrUriToUri,
getUriPathBasename,
getUriFileExtension,
getFileExtensionFromBasename,
@ -141,26 +139,6 @@ describe("uri utils", () => {
});
});
describe("relativePathOrUriToUri", () => {
const consoleSpy = jest.spyOn(console, "trace").mockImplementation();
afterEach(() => {
consoleSpy.mockClear();
});
it("should return original URI if scheme exists", () => {
const uri = "file:///path/to/file.txt";
expect(relativePathOrUriToUri(uri, "file:///base")).toBe(uri);
});
it("should convert relative path to URI", () => {
expect(relativePathOrUriToUri("path/to/file.txt", "file:///base")).toBe(
"file:///base/path/to/file.txt",
);
expect(consoleSpy).toHaveBeenCalledWith("Received path with no scheme");
});
});
describe("getLastNUriRelativePathParts", () => {
it("should get last N parts of URI relative path", () => {
const dirUris = ["file:///workspace/project1"];

View file

@ -5,23 +5,21 @@ import * as URI from "uri-js";
\this\is\afile.ts -> this/is/afile.ts
is/already/clean -> is/already/clean
**/
export function pathToUriPathSegment(path: string) {
let clean = path.replace(/[\\]/g, "/"); // backslashes -> forward slashes
clean = clean.replace(/^\//, ""); // remove start slash
clean = clean.replace(/\/$/, ""); // remove end slash
return clean
.split("/")
.map((segment) => encodeURIComponent(segment))
.map((part) => encodeURIComponent(part))
.join("/");
}
export function getCleanUriPath(uri: string) {
const path = URI.parse(uri).path;
if (!path) {
return "";
}
return pathToUriPathSegment(path);
const path = URI.parse(uri).path ?? "";
let clean = path.replace(/^\//, ""); // remove start slash
clean = clean.replace(/\/$/, ""); // remove end slash
return clean;
}
export function findUriInDirs(
@ -36,6 +34,7 @@ export function findUriInDirs(
if (!uriComps.scheme) {
throw new Error(`Invalid uri: ${uri}`);
}
const uriPathParts = getCleanUriPath(uri).split("/");
for (const dir of dirUriCandidates) {
const dirComps = URI.parse(dir);
@ -51,14 +50,7 @@ export function findUriInDirs(
// file:///folder/file is not within file:///fold
// At this point we break the path up and check if each dir path part matches
const dirPathParts = (dirComps.path ?? "")
.replace(/^\//, "")
.split("/")
.map((part) => encodeURIComponent(part));
const uriPathParts = (uriComps.path ?? "")
.replace(/^\//, "")
.split("/")
.map((part) => encodeURIComponent(part));
const dirPathParts = getCleanUriPath(dir).split("/");
if (uriPathParts.length < dirPathParts.length) {
continue;
@ -70,7 +62,10 @@ export function findUriInDirs(
}
}
if (allDirPartsMatch) {
const relativePath = uriPathParts.slice(dirPathParts.length).join("/");
const relativePath = uriPathParts
.slice(dirPathParts.length)
.map(decodeURIComponent)
.join("/");
return {
uri,
relativePathOrBasename: relativePath,
@ -86,28 +81,13 @@ export function findUriInDirs(
};
}
/*
To smooth out the transition from path to URI will use this function to warn when path is used
This will NOT work consistently with full OS paths like c:\blah\blah or ~/Users/etc
*/
export function relativePathOrUriToUri(
relativePathOrUri: string,
defaultDirUri: string,
): string {
const out = URI.parse(relativePathOrUri);
if (out.scheme) {
return relativePathOrUri;
}
console.trace("Received path with no scheme");
return joinPathsToUri(defaultDirUri, out.path ?? "");
}
/*
Returns just the file or folder name of a URI
*/
export function getUriPathBasename(uri: string): string {
const cleanPath = getCleanUriPath(uri);
return cleanPath.split("/")?.pop() || "";
const path = getCleanUriPath(uri);
const basename = path.split("/").pop() || "";
return decodeURIComponent(basename);
}
export function getFileExtensionFromBasename(basename: string) {
@ -142,6 +122,15 @@ export function joinPathsToUri(uri: string, ...pathSegments: string[]) {
return URI.serialize(components);
}
export function joinEncodedUriPathSegmentToUri(
uri: string,
pathSegment: string,
) {
const components = URI.parse(uri);
components.path = `${components.path}/${pathSegment}`;
return URI.serialize(components);
}
export function getShortestUniqueRelativeUriPaths(
uris: string[],
dirUriCandidates: string[],
@ -153,8 +142,7 @@ export function getShortestUniqueRelativeUriPaths(
const segmentCombinationsMap = new Map<string, number>();
const segmentsInfo = uris.map((uri) => {
const { relativePathOrBasename } = findUriInDirs(uri, dirUriCandidates);
const cleanPath = pathToUriPathSegment(relativePathOrBasename);
const segments = cleanPath.split("/");
const segments = relativePathOrBasename.split("/");
const suffixes: string[] = [];
// Generate all possible suffix combinations, starting from the shortest (basename)
@ -168,18 +156,19 @@ export function getShortestUniqueRelativeUriPaths(
);
}
return { uri, segments, suffixes, cleanPath };
return { uri, segments, suffixes, relativePathOrBasename };
});
// Find shortest unique path for each URI
return segmentsInfo.map(({ uri, suffixes, cleanPath }) => {
return segmentsInfo.map(({ uri, suffixes, relativePathOrBasename }) => {
// Since suffixes are now ordered from shortest to longest,
// the first unique one we find will be the shortest
const uniqueCleanPath =
const uniquePath =
suffixes.find((suffix) => segmentCombinationsMap.get(suffix) === 1) ??
cleanPath; // fallback to full path if no unique suffix found
return { uri, uniquePath: decodeURIComponent(uniqueCleanPath) };
relativePathOrBasename; // fallback to full path if no unique suffix found
return { uri, uniquePath };
});
}
// Only used when working with system paths and relative paths
// Since doesn't account for URI segements before workspace
export function getLastNPathParts(filepath: string, n: number): string {

View file

@ -5,6 +5,10 @@ keywords: [model, autocomplete]
sidebar_position: 2
---
:::info
This page recommends models and providers for Autocomplete. Read more about how to set up your `config.json` [here](../reference.md).
:::
## Best overall experience
For the best Autocomplete experience, we recommend using Codestral through the [Mistral API](https://console.mistral.ai/). This model offers high-quality completions with an excellent understanding of code context:
@ -26,26 +30,39 @@ The API keys for Codestral and the general Mistral APIs are different. If you ar
## Local, offline / self-hosted experience
For those preferring local execution or self-hosting,`Qwen2.5-Coder 1.5B` offers a good balance of performance and quality for most users:
For those preferring local execution or self-hosting,`Qwen2.5-Coder 1.5B` offers a good balance of performance and quality for most users (e.g. using [Ollama](../customize/model-providers/top-level/ollama.md) or [LM Studio](../customize/model-providers/more/lmstudio.md)).
```json title="config.json""
{
"tabAutocompleteModel": {
"title": "Qwen2.5-Coder 1.5B",
"model": "qwen2.5-coder:1.5b",
"model": "qwen2.5-coder:1.5b-base",
"provider": "ollama"
}
}
```
Have more compute? Use `qwen2.5-coder:7b` for potentially higher-quality suggestions.
Have more compute? Use `qwen2.5-coder:7b-base` for potentially higher-quality suggestions.
:::note
For LM Studio users, navigate to the "My Models" section, find your desired model, and copy the path (e.g., `Qwen/Qwen2.5-Coder-1.5B-Instruct-GGUF/wen2.5-coder-1.5b-instruct-q4_k_m.gguf`). Use this path as the `model` value in your configuration.
For LM Studio users, navigate to the "My Models" section, find your desired model, and copy the path (e.g., `Qwen/Qwen2.5-Coder-1.5B-Instruct-GGUF/qwen2.5-coder-1.5b-instruct-q4_k_m.gguf`). Use this path as the `model` value in your configuration.
:::
### Using a remote instance
When using a remote instance you need to set the `"apiBase"` value in the configuration:
```json title="config.json""
{
"tabAutocompleteModel": {
"title": "Qwen2.5-Coder 1.5B",
"model": "qwen2.5-coder:1.5b-base",
"provider": "ollama"
"apiBase": "http://<my endpoint>:11434"
}
}
```
## Other experiences
There are many more models and providers you can use with Autocomplete. Check them out [here](../customize/model-types/autocomplete.md).
There are many more models and providers you can use with Autocomplete. Check them out [here](../customize/model-types/autocomplete.md). You can also see more examples of Autocomplete configuration [here](../customize/deep-dives/autocomplete.md)

View file

@ -15,7 +15,7 @@ The highlighted code you’ve selected by pressing <kbd>cmd/ctrl</kbd> + <kbd>L<
## Active file
You can include the currently open file as context by pressing <kbd>cmd</kbd> + <kbd>opt</kbd> + <kbd>enter</kbd> (Mac) or <kbd>ctrl</kbd> + <kbd>alt</kbd> + <kbd>enter</kbd> (Windows) when you send your request.
You can include the currently open file as context by pressing <kbd>cmd</kbd> + <kbd>opt</kbd> + <kbd>enter</kbd> (Mac) or <kbd>alt</kbd> + <kbd>enter</kbd> (Windows) when you send your request at Chat window(Prompt can't be empty).
## Specific file

View file

@ -33,7 +33,7 @@ Our current top recommendation is Claude Sonnet 3.5 from [Anthropic](../customiz
### Llama 3.1 405B from Meta
If you prefer to use an open-weight model, then Llama 3.1 405B from Meta is your best option right now. You will need to decide if you use it through a SaaS model provider (e.g. [Together](../customize/model-providers/more/together.md) or [Groq](../customize/model-providers/more/groq.md)) or self-host it (e.g. using [vLLM](../customize/model-providers//more/vllm.md) or [Ollama](../customize/model-providers/top-level/ollama.md)).
If you prefer to use an open-weight model, then Llama 3.1 405B from Meta is your best option right now. You will need to decide if you use it through a SaaS model provider (e.g. [Together](../customize/model-providers/more/together.md) or [Novita AI](../customize/model-providers/more/novita.md) or [Groq](../customize/model-providers/more/groq.md)) or self-host it (e.g. using [vLLM](../customize/model-providers//more/vllm.md) or [Ollama](../customize/model-providers/top-level/ollama.md)).
<Tabs groupId="providers">
<TabItem value="Together">
@ -48,6 +48,18 @@ If you prefer to use an open-weight model, then Llama 3.1 405B from Meta is your
]
```
</TabItem>
<TabItem value="Novita">
```json title="config.json"
"models": [
{
"title": "Llama 3.1 405B",
"provider": "novita",
"model": "meta-llama/llama-3.1-405b-instruct",
"apiKey": "[NOVITA_API_KEY]"
}
]
```
</TabItem>
<TabItem value="Groq">
```json title="config.json"
"models": [
@ -77,7 +89,7 @@ If you prefer to use an open-weight model, then Llama 3.1 405B from Meta is your
{
"title": "Llama 3.1 405B",
"provider": "ollama",
"model": "llama3.1-405b"
"model": "llama3.1:405b"
}
]
```
@ -141,7 +153,7 @@ If your local machine can run an 8B parameter model, then we recommend running L
{
"title": "Llama 3.1 8B",
"provider": "ollama",
"model": "llama3.1-8b"
"model": "llama3.1:8b"
}
]
```

View file

@ -576,6 +576,20 @@ The response 200 OK should be a JSON object with the following structure:
}
```
### `@Clipboard`
Reference recent clipboard items
```json title="config.json"
{
"contextProviders": [
{
"name": "clipboard"
}
]
}
```
### Requesting Context Providers
Not seeing what you want? Create an issue [here](https://github.com/continuedev/continue/issues/new?assignees=TyDunn&labels=enhancement&projects=&template=feature-request-%F0%9F%92%AA.md&title=) to request a new Context Provider.

View file

@ -23,7 +23,7 @@ If you want to have the best autocomplete experience, we recommend using Codestr
If you'd like to run your autocomplete model locally, we recommend using Ollama. To do this, first download the latest version of Ollama from [here](https://ollama.ai). Then, run the following command to download our recommended model:
```bash
ollama run qwen2.5-coder:1.5b
ollama run qwen2.5-coder:1.5b-base
```
Once it has been downloaded, you should begin to see completions in VS Code.
@ -37,7 +37,7 @@ All of the configuration options available for chat models are available to use
"tabAutocompleteModel": {
"title": "Tab Autocomplete Model",
"provider": "ollama",
"model": "qwen2.5-coder:1.5b",
"model": "qwen2.5-coder:1.5b-base",
"apiBase": "https://<my endpoint>"
},
...
@ -76,7 +76,7 @@ This object allows you to customize the behavior of tab-autocomplete. The availa
"tabAutocompleteModel": {
"title": "Tab Autocomplete Model",
"provider": "ollama",
"model": "qwen2.5-coder:1.5b",
"model": "qwen2.5-coder:1.5b-base",
"apiBase": "https://<my endpoint>"
},
"tabAutocompleteOptions": {
@ -91,7 +91,7 @@ This object allows you to customize the behavior of tab-autocomplete. The availa
### I want better completions, should I use GPT-4?
Perhaps surprisingly, the answer is no. The models that we suggest for autocomplete are trained with a highly specific prompt format, which allows them to respond to requests for completing code (see examples of these prompts [here](https://github.com/continuedev/continue/blob/main/core/autocomplete/templates.ts)). Some of the best commercial models like GPT-4 or Claude are not trained with this prompt format, which means that they won't generate useful completions. Luckily, a huge model is not required for great autocomplete. Most of the state-of-the-art autocomplete models are no more than 10b parameters, and increasing beyond this does not significantly improve performance.
Perhaps surprisingly, the answer is no. The models that we suggest for autocomplete are trained with a highly specific prompt format, which allows them to respond to requests for completing code (see examples of these prompts [here](https://github.com/continuedev/continue/blob/main/core/autocomplete/templating/AutocompleteTemplate.ts)). Some of the best commercial models like GPT-4 or Claude are not trained with this prompt format, which means that they won't generate useful completions. Luckily, a huge model is not required for great autocomplete. Most of the state-of-the-art autocomplete models are no more than 10b parameters, and increasing beyond this does not significantly improve performance.
### I'm not seeing any completions
@ -99,7 +99,7 @@ Follow these steps to ensure that everything is set up correctly:
1. Make sure you have the "Enable Tab Autocomplete" setting checked (in VS Code, you can toggle by clicking the "Continue" button in the status bar, and in JetBrains by going to Settings -> Tools -> Continue).
2. Make sure you have downloaded Ollama.
3. Run `ollama run qwen2.5-coder:1.5b` to verify that the model is downloaded.
3. Run `ollama run qwen2.5-coder:1.5b-base` to verify that the model is downloaded.
4. Make sure that any other completion providers are disabled (e.g. Copilot), as they may interfere.
5. Check the output of the logs to find any potential errors: <kbd>cmd/ctrl</kbd> + <kbd>shift</kbd> + <kbd>P</kbd> -> "Toggle Developer Tools" -> "Console" tab in VS Code, ~/.continue/logs/core.log in JetBrains.
6. Check VS Code settings to make sure that `"editor.inlineSuggest.enabled"` is set to `true` (use <kbd>cmd/ctrl</kbd> + <kbd>,</kbd> then search for this and check the box)

View file

@ -46,7 +46,7 @@ We recommend configuring **rerank-english-v3.0** as your reranking model.
```json title="config.json"
{
"reranker": {
"provider": "cohere",
"name": "cohere",
"params": {
"model": "rerank-english-v3.0",
"apiKey": "<COHERE_API_KEY>"

View file

@ -1,6 +1,6 @@
# Kindo
Kindo offers centralized control over your organization's AI operations, ensuring data protection and compliance with internal policies while supporting various commercial and open-source models. To get started, sign up [here](https://app.kindo.ai/), create your API key on the [API keys page](https://app.kindo.ai/settings/api), and choose a model from the list of supported models in the [plugins tab](https://app.kindo.ai/plugins).
Kindo offers centralized control over your organization's AI operations, ensuring data protection and compliance with internal policies while supporting various commercial and open-source models. To get started, sign up [here](https://app.kindo.ai/), create an API key in [Settings > API > API Keys](https://app.kindo.ai/settings/api), and choose a model from the list of supported models in the "Available Models" tab or copy and paste the config in [Plugins > Your Configuration](https://app.kindo.ai/plugins).
## Config Example
@ -10,7 +10,7 @@ Kindo offers centralized control over your organization's AI operations, ensurin
{
"title": "Claude 3.5 Sonnet",
"provider": "kindo",
"model": "claude-3-5-sonnet-20240620",
"model": "claude-3-5-sonnet",
"apiKey": "<KINDO_API_KEY>"
}
]
@ -26,13 +26,8 @@ Kindo offers centralized control over your organization's AI operations, ensurin
"title": "WhiteRabbitNeo",
"provider": "kindo",
"model": "/models/WhiteRabbitNeo-33B-DeepSeekCoder",
"apiKey": "<KINDO_API_KEY>"
},
{
"title": "DeepSeek",
"provider": "kindo",
"model": "deepseek-ai/deepseek-coder-33b-instruct",
"apiKey": "<KINDO_API_KEY>"
"apiKey": "<KINDO_API_KEY>",
"template": "none"
}
]
}

View file

@ -0,0 +1,18 @@
# Novita
[Novita AI](https://novita.ai?utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link) offers an affordable, reliable, and simple inference platform with scalable [LLM API](https://novita.ai/docs/model-api/reference/introduction.html), empowering developers to build AI applications. Try the [Novita AI Llama 3 API Demo](https://novita.ai/model-api/product/llm-api/playground/meta-llama-llama-3.1-70b-instruct?utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link) today!. You can sign up [here](https://novita.ai/user/login?&redirect=/&utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link), copy your API key on the [Key Management](https://novita.ai/settings/key-management?utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link), and then hit the play button on any model from the [Novita AI Models list](https://novita.ai/llm-api?utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link). Change `~/.continue/config.json` to look like this:
```json title="config.json"
{
"models": [
{
"title": "Llama 3.1 8B",
"provider": "novita",
"model": "meta-llama/llama-3.1-8b-instruct",
"apiKey": "YOUR_API_KEY"
}
]
}
```
[View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/Novita.ts)

View file

@ -1,22 +1,59 @@
# vLLM
Run the OpenAI-compatible server by vLLM using `vllm serve`. See their [server documentation](https://docs.vllm.ai/en/latest/serving/openai_compatible_server.html) and the [engine arguments documentation](https://docs.vllm.ai/en/latest/models/engine_args.html).
vLLM is an open-source library for fast LLM inference which typically is used to serve multiple users at the same. It can also be used to run a large model on multiple GPU:s (e.g. when it doesn´t fit in a single GPU). Run their OpenAI-compatible server using `vllm serve`. See their [server documentation](https://docs.vllm.ai/en/latest/serving/openai_compatible_server.html) and the [engine arguments documentation](https://docs.vllm.ai/en/latest/usage/engine_args.html).
```shell
vllm serve NousResearch/Meta-Llama-3-8B-Instruct --max-model-len 1024
vllm serve meta-llama/Meta-Llama-3.1-8B-Instruct
```
## Chat model
The continue implementation uses [OpenAI](../top-level/openai.md) under the hood and automatically selects the available model. You only need to set the `apiBase` like this:
We recommend configuring **Llama3.1 8B** as your chat model.
```json title="config.json"
{
"models": [
{
"title": "My vLLM OpenAI-compatible server",
"apiBase": "http://localhost:8000/v1"
"title": "Llama3.1 8B Instruct",
"provider": "vllm",
"model": "meta-llama/Meta-Llama-3.1-8B-Instruct"
"apiBase": "http://<vllm chat endpoint>/v1"
}
]
}
```
[View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/Vllm.ts)
## Autocomplete model
We recommend configuring **Qwen2.5-Coder 1.5B** as your autocomplete model.
```json title="config.json"
{
"tabAutocompleteModel": {
"title": "Qwen2.5-Coder 1.5B",
"provider": "vllm",
"model": "Qwen/Qwen2.5-Coder-1.5B"
"apiBase": "http://<vllm autocomplete endpoint>/v1"
}
}
```
## Embeddings model
We recommend configuring **Nomic Embed Text** as your embeddings model.
```json title="config.json"
{
"embeddingsProvider": {
"provider": "vllm",
"model": "nomic-ai/nomic-embed-text-v1"
"apiBase": "http://<vllm embed endpoint>/v1"
}
}
```
## Reranking model
[Click here](../../model-types/reranking.md) to see a list of reranking model providers.
The continue implementation uses [OpenAI](../top-level/openai.md) under the hood. [View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/Vllm.ts)

View file

@ -22,6 +22,22 @@ We recommend configuring **Claude 3.5 Sonnet** as your chat model.
]
}
```
> If you run into the following error when connecting to the new Claude 3.5 Sonnet 2 models from AWS - `400 Invocation of model ID anthropic.claude-3-5-sonnet-20241022-v2:0 with on-demand throughput isn’t supported. Retry your request with the ID or ARN of an inference profile that contains this model.`
> You can fix this using the following config.json
```json title="config.json"
{
"models": [
{
"title": "Claude 3.5 Sonnet",
"provider": "bedrock",
"model": "us.anthropic.claude-3-5-sonnet-20241022-v2:0",
"region": "us-east-1",
"profile": "bedrock"
}
]
}
```
## Autocomplete model

View file

@ -30,7 +30,7 @@ We recommend configuring **Qwen2.5-Coder 1.5B** as your autocomplete model.
"tabAutocompleteModel": {
"title": "Qwen2.5-Coder 1.5B",
"provider": "ollama",
"model": "qwen2.5-coder:1.5b"
"model": "qwen2.5-coder:1.5b-base"
}
}
```
@ -53,3 +53,20 @@ We recommend configuring **Nomic Embed Text** as your embeddings model.
Ollama currently does not offer any reranking models.
[Click here](../../model-types/reranking.md) to see a list of reranking model providers.
## Using a remote instance
To configure a remote instance of Ollama, add the `"apiBase"` property to your model in config.json:
```json title="config.json"
{
"models": [
{
"title": "Llama3.1 8B",
"provider": "ollama",
"model": "llama3.1:8b"
"apiBase": "http://<my endpoint>:11434"
}
]
}
```

View file

@ -1,7 +1,7 @@
---
title: Using Llama 3.1 with Continue
description: How to use Llama 3.1 with Continue
keywords: [llama, meta, togetherai, ollama, replicate]
keywords: [llama, meta, togetherai, novita, ollama, replicate]
---
Continue makes it easy to code with the latest open-source models, including the entire Llama 3.1 family of models. Llama 3.2 models are also supported but not recommended for chat, because they are specifically designed to be small or multi-modal.
@ -71,6 +71,28 @@ Together AI provides fast and reliable inference of open-source models. You'll b
}
```
## Novita AI
[Novita AI](https://novita.ai?utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link) offers an affordable, reliable, and simple inference platform with scalable [LLM API](https://novita.ai/docs/model-api/reference/introduction.html), empowering developers to build AI applications. Try the [Novita AI Llama 3 API Demo](https://novita.ai/model-api/product/llm-api/playground/meta-llama-llama-3.1-70b-instruct?utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link) today!
1. Create an account [here](https://novita.ai/user/login?&redirect=/&utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link)
2. Copy your API key that appears on the welcome screen
3. Update your Continue config file like this:
```json title="config.json"
{
"models": [
{
"title": "Llama 3.1 405b",
"provider": "novita",
"model": "meta-llama/llama-3.1-405b-instruct",
"apiKey": "<API_KEY>"
}
]
}
```
## Replicate
Replicate makes it easy to host and run open-source AI with an API.

View file

@ -18,7 +18,7 @@ If you have any problems, see the [troubleshooting guide](troubleshooting.md) or
## JetBrains
1. Open your JetBrains IDE and open **Settings** using <kbd>Ctrl</kbd> + <kbd>+Alt</kbd> + <kbd>S</kbd>
1. Open your JetBrains IDE and open **Settings** using <kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>S</kbd>
2. Select **Plugins** on the sidebar and search for "Continue" in the marketplace
3. Click `Install`, which will cause the Continue logo to show up on the right toolbar

View file

@ -88,7 +88,7 @@ Specifies options for tab autocompletion behavior.
- `debounceDelay`: Delay (in ms) before triggering autocomplete.
- `maxSuffixPercentage`: Maximum percentage of prompt for suffix.
- `prefixPercentage`: Percentage of input for prefix.
- `template`: Template string for autocomplete, using Mustache templating.
- `template`: Template string for autocomplete, using Mustache templating. You can use the `{{{ prefix }}}`, `{{{ suffix }}}`, `{{{ filename }}}`, `{{{ reponame }}}`, and `{{{ language }}}` variables.
- `multilineCompletions`: Controls multiline completions (`"always"`, `"never"`, or `"auto"`).
- `useCache`: If `true`, caches completions.
- `onlyMyCode`: If `true`, only includes code within the repository.

View file

@ -388,7 +388,11 @@ const config = {
},
{
to: "/customize/model-providers/more/together",
from: "/reference/Model Providers/togetherllm",
from: "/reference/Model Providers/together",
},
{
to: "/customize/model-providers/more/novita",
from: "/reference/Model Providers/novita",
},
{
to: "/customize/model-providers/more/vllm",

View file

@ -33,7 +33,7 @@ import TabItem from "@theme/TabItem";
### 来自 Meta 的 Llama 3.1 405B
如果你倾向于使用开放权重模型,那么来自 Meta 的 Llama 3.1 405B 是你当前的最好选择。你需要决定,通过 SaaS 模型提供者使用它(比如 [Together](../customize/model-providers/more/together.md) 或 [Groq](../customize/model-providers/more/groq.md))或者自托管使用它(比如使用 [vLLM](../customize/model-providers//more/vllm.md) 或 [Ollama](../customize/model-providers/top-level/ollama.md)) 。
如果你倾向于使用开放权重模型,那么来自 Meta 的 Llama 3.1 405B 是你当前的最好选择。你需要决定,通过 SaaS 模型提供者使用它(比如 [Together](../customize/model-providers/more/together.md) 、[Novita AI](../customize/model-providers/more/novita.md)或 [Groq](../customize/model-providers/more/groq.md))或者自托管使用它(比如使用 [vLLM](../customize/model-providers//more/vllm.md) 或 [Ollama](../customize/model-providers/top-level/ollama.md)) 。
<Tabs groupId="providers">
<TabItem value="Together">
@ -48,6 +48,18 @@ import TabItem from "@theme/TabItem";
]
```
</TabItem>
<TabItem value="Novita">
```json title="config.json"
"models": [
{
"title": "Llama 3.1 405B",
"provider": "novita",
"model": "meta-llama/llama-3.1-405b-instruct",
"apiKey": "[NOVITA_API_KEY]"
}
]
```
</TabItem>
<TabItem value="Groq">
```json title="config.json"
"models": [

View file

@ -0,0 +1,18 @@
# Novita
[Novita AI](https://novita.ai?utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link) 提供了一个经济实惠、可靠且简单的推理平台。你可以在 [这里](https://novita.ai/user/login?&redirect=/&utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link) 注册,在 [Key Management](https://novita.ai/settings/key-management?utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link)复制你的 API key ,然后在 [Novita 模型列表](https://novita.ai/llm-api?utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link) 的任何模型上点击 Try it now 按钮。修改 `~/.continue/config.json` 像这样:
```json title="config.json"
{
"models": [
{
"title": "Llama 3.1 8b",
"provider": "Novita",
"model": "meta-llama/llama-3.1-8b-instruct",
"apiKey": "YOUR_API_KEY"
}
]
}
```
[查看代码](https://github.com/continuedev/continue/blob/main/core/llm/llms/Novita.ts)

View file

@ -1,7 +1,7 @@
---
title: Continue 使用 Llama 3.1
description: Continue 如何使用 Llama 3.1
keywords: [llama, meta, togetherai, ollama, replicate]
keywords: [llama, meta, togetherai, novita, ollama, replicate]
---
Continue 让使用最新的开元模型编码变得简单,包括整个 Llama 3.1 家族模型。
@ -71,6 +71,27 @@ Together AI 提供开源模型的快速和可信任的推理。你可以以良
}
```
## Novita AI
[Novita AI](https://novita.ai?utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link) 提供了一个经济实惠、可靠且简单的推理平台。你可以以良好的速度运行 405b 模型。
1. 创建账号 [在这里](https://novita.ai/user/login?&redirect=/&utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link)
2. 复制[Key Management](https://novita.ai/settings/key-management?utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link)中的你的 API key
3. 更新你的 Continue 配置文件,像这样:
```json title="config.json"
{
"models": [
{
"title": "Llama 3.1 405b",
"provider": "novita",
"model": "meta-llama/llama-3.1-405b-instruct",
"apiKey": "<API_KEY>"
}
]
}
```
## Replicate
Replicate 让使用 API 托管和运行开源 AI 变得简单。

View file

@ -3,4 +3,6 @@ src/main/resources/webview
src/main/resources/bin
src/main/resources/config_schema.json
src/main/resources/continue_rc_schema.json
video
video
src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/test-continue/*
!src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/test-continue/config.json

View file

@ -1,25 +0,0 @@
<!--<component name="ProjectRunConfigurationManager">-->
<!-- <configuration default="false" name="Run IDE for UI Tests" type="GradleRunConfiguration" factoryName="Gradle">-->
<!-- <log_file alias="idea.log" path="$PROJECT_DIR$/build/idea-sandbox/system/log/idea.log" />-->
<!-- <ExternalSystemSettings>-->
<!-- <option name="executionName" />-->
<!-- <option name="externalProjectPath" value="$PROJECT_DIR$" />-->
<!-- <option name="externalSystemIdString" value="GRADLE" />-->
<!-- <option name="scriptParameters" value="" />-->
<!-- <option name="taskDescriptions">-->
<!-- <list />-->
<!-- </option>-->
<!-- <option name="taskNames">-->
<!-- <list>-->
<!-- <option value="runIdeForUiTests" />-->
<!-- </list>-->
<!-- </option>-->
<!-- <option name="vmOptions" />-->
<!-- </ExternalSystemSettings>-->
<!-- <ExternalSystemDebugServerProcess>true</ExternalSystemDebugServerProcess>-->
<!-- <ExternalSystemReattachDebugProcess>true</ExternalSystemReattachDebugProcess>-->
<!-- <DebugAllEnabled>false</DebugAllEnabled>-->
<!-- <RunAsTest>false</RunAsTest>-->
<!-- <method v="2" />-->
<!-- </configuration>-->
<!--</component>-->

View file

@ -0,0 +1,27 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Run Test IDE" type="GradleRunConfiguration" factoryName="Gradle">
<ExternalSystemSettings>
<option name="executionName"/>
<option name="externalProjectPath" value="$PROJECT_DIR$/extensions/intellij"/>
<option name="externalSystemIdString" value="GRADLE"/>
<option name="scriptParameters" value=""/>
<option name="taskDescriptions">
<list/>
</option>
<option name="taskNames">
<list>
<option value="runIdeForUiTests"/>
</list>
</option>
<option name="vmOptions"/>
</ExternalSystemSettings>
<ExternalSystemDebugServerProcess>true</ExternalSystemDebugServerProcess>
<ExternalSystemReattachDebugProcess>true</ExternalSystemReattachDebugProcess>
<DebugAllEnabled>false</DebugAllEnabled>
<RunAsTest>false</RunAsTest>
<method v="2">
<option name="Gradle.BeforeRunTask" enabled="true" tasks="clean"
externalProjectPath="$PROJECT_DIR$/extensions/intellij" vmOptions="" scriptParameters=""/>
</method>
</configuration>
</component>

View file

@ -0,0 +1,24 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Run Tests" type="GradleRunConfiguration" factoryName="Gradle" focusToolWindowBeforeRun="true">
<ExternalSystemSettings>
<option name="executionName" />
<option name="externalProjectPath" value="$PROJECT_DIR$/extensions/intellij" />
<option name="externalSystemIdString" value="GRADLE" />
<option name="scriptParameters" value="" />
<option name="taskDescriptions">
<list />
</option>
<option name="taskNames">
<list>
<option value="test" />
</list>
</option>
<option name="vmOptions" />
</ExternalSystemSettings>
<ExternalSystemDebugServerProcess>true</ExternalSystemDebugServerProcess>
<ExternalSystemReattachDebugProcess>true</ExternalSystemReattachDebugProcess>
<DebugAllEnabled>false</DebugAllEnabled>
<RunAsTest>false</RunAsTest>
<method v="2" />
</configuration>
</component>

View file

@ -0,0 +1,7 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Run e2e tests" type="CompoundRunConfigurationType">
<toRun name="Run Test IDE" type="GradleRunConfiguration" />
<toRun name="Run Tests" type="GradleRunConfiguration" />
<method v="2" />
</configuration>
</component>

View file

@ -101,7 +101,9 @@ toolbar.
_Run | Debugging Actions | Reload Changed Classes`_
- This will often fail on new imports, schema changes etc. In that case, you need to stop and restart the extension
- `gui`: Changes will be reloaded automatically
- `core`: Run `npm run build` from the `binary` directory (requires restarting the `Start Core Dev Server` task)
- `core`: Run `npm run build -- --os [darwin | linux | win32]` from the `binary` directory (requires
restarting the
`Start Core Dev Server` task)
### Setting breakpoints

View file

@ -130,7 +130,10 @@ tasks {
// Configure UI tests plugin
// Read more: https://github.com/JetBrains/intellij-ui-test-robot
runIdeForUiTests {
environment("CONTINUE_GLOBAL_DIR", "src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/test-continue")
environment(
"CONTINUE_GLOBAL_DIR",
"${rootProject.projectDir}/src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/test-continue"
)
systemProperty("robot-server.port", "8082")
systemProperty("ide.mac.message.dialogs.as.sheets", "false")
systemProperty("jb.privacy.policy.text", "<!--999.999-->")
@ -141,6 +144,7 @@ tasks {
systemProperty("idea.trust.all.projects", "true")
systemProperty("ide.show.tips.on.startup.default.value", "false")
systemProperty("ide.browser.jcef.jsQueryPoolSize", "10000")
systemProperty("ide.browser.jcef.contextMenu.devTools.enabled", "true")
// This is to ensure we load the GUI with OSR enabled. We have logic that
// renders with OSR disabled below a particular IDE version.
@ -180,6 +184,5 @@ tasks {
test {
useJUnitPlatform()
environment("CONTINUE_GLOBAL_DIR", "src/test/kotlin/com/github/continuedev/continueintellijextension/e2e/test-continue")
}
}

View file

@ -120,6 +120,10 @@ class AutocompleteService(private val project: Project) {
return ApplicationManager.getApplication().runReadAction<String> {
val document = editor.document
val caretOffset = editor.caretModel.offset
// Don't care about it if it's at the end of the document
if (caretOffset == document.textLength) return@runReadAction completion
val N = 10
var textAfterCursor = if (caretOffset + N <= document.textLength) {
document.getText(com.intellij.openapi.util.TextRange(caretOffset, caretOffset + N))
@ -127,6 +131,9 @@ class AutocompleteService(private val project: Project) {
document.getText(com.intellij.openapi.util.TextRange(caretOffset, document.textLength))
}
// Avoid truncating the completion text when the text after the cursor is blank
if (textAfterCursor.isBlank()) return@runReadAction completion
// Determine the index of a newline character within the text following the cursor.
val newlineIndex = textAfterCursor.indexOf("\r\n").takeIf { it >= 0 } ?: textAfterCursor.indexOf('\n')
// If a newline character is found and the current line is not empty, truncate the text at that point.
@ -287,12 +294,13 @@ class AutocompleteService(private val project: Project) {
}
private fun isInjectedFile(editor: Editor): Boolean {
val psiFile = runReadAction { PsiDocumentManager.getInstance(project).getPsiFile(editor.document) }
if (psiFile == null) {
return false
}
val response = runReadAction { psiFile.isInjectedText() }
return response
return ApplicationManager.getApplication().executeOnPooledThread<Boolean> {
ApplicationManager.getApplication().runReadAction<Boolean> {
val psiFile =
PsiDocumentManager.getInstance(project).getPsiFile(editor.document) ?: return@runReadAction false
return@runReadAction psiFile.isInjectedText()
}
}.get()
}
fun hideCompletions(editor: Editor) {

View file

@ -39,7 +39,7 @@ class MessageTypes {
"getRepoName",
"listDir",
"getGitRootPath",
"getLastModified",
"getFileStats",
"insertAtCursor",
"applyToFile",
"getGitHubAuthToken",
@ -50,13 +50,78 @@ class MessageTypes {
"showToast",
)
// Note: If updating these values, make a corresponding update in
// core/protocol/passThrough.ts
val PASS_THROUGH_TO_WEBVIEW = listOf(
"configUpdate",
"getDefaultModelTitle",
"indexProgress",
"indexProgress", // Codebase
"indexing/statusUpdate", // Docs, etc.
"addContextItem",
"refreshSubmenuItems",
"isContinueInputFocused",
"didChangeAvailableProfiles",
"addContextItem"
"setTTSActive",
"getWebviewHistoryLength",
"getCurrentSessionId",
"signInToControlPlane",
"openDialogMessage",
"docs/suggestions",
)
// Note: If updating these values, make a corresponding update in
// core/protocol/passThrough.ts
val PASS_THROUGH_TO_CORE = listOf(
"abort",
"history/list",
"history/delete",
"history/load",
"history/save",
"devdata/log",
"config/addModel",
"config/addContextProvider",
"config/newPromptFile",
"config/ideSettingsUpdate",
"config/getSerializedProfileInfo",
"config/deleteModel",
"config/listProfiles",
"config/openProfile",
"context/getContextItems",
"context/getSymbolsForFiles",
"context/loadSubmenuItems",
"context/addDocs",
"context/removeDocs",
"context/indexDocs",
"autocomplete/complete",
"autocomplete/cancel",
"autocomplete/accept",
"command/run",
"tts/kill",
"llm/complete",
"llm/streamComplete",
"llm/streamChat",
"llm/listModels",
"streamDiffLines",
"chatDescriber/describe",
"stats/getTokensPerDay",
"stats/getTokensPerModel",
// Codebase
"index/setPaused",
"index/forceReIndex",
"index/forceReIndexFiles",
"index/indexingProgressBarInitialized",
// Docs, etc.
"indexing/reindex",
"indexing/abort",
"indexing/setPaused",
"docs/getSuggestedDocs",
"docs/initStatuses",
//
"completeOnboarding",
"addAutocompleteModel",
"profiles/switch",
"didChangeSelectedProfile",
"tools/call",
)
}
}

View file

@ -215,13 +215,13 @@ class IdeProtocolClient(
respond(null)
}
"getLastModified" -> {
"getFileStats" -> {
val params = Gson().fromJson(
dataElement.toString(),
GetLastModifiedParams::class.java
GetFileStatsParams::class.java
)
val lastModifiedMap = ide.getLastModified(params.files)
respond(lastModifiedMap)
val fileStatsMap = ide.getFileStats(params.files)
respond(fileStatsMap)
}
"listDir" -> {
@ -469,6 +469,10 @@ class IdeProtocolClient(
}
val diffStreamService = project.service<DiffStreamService>()
// Clear all diff blocks before running the diff stream
diffStreamService.reject(editor)
val llmTitle = (llm as? Map<*, *>)?.get("title") as? String ?: ""
val prompt =
@ -501,7 +505,6 @@ class IdeProtocolClient(
rif?.range?.end?.line ?: (editor.document.lineCount - 1),
{}, {})
val diffStreamService = project.service<DiffStreamService>()
diffStreamService.register(diffStreamHandler, editor)
diffStreamHandler.streamDiffLinesToEditor(

View file

@ -513,15 +513,15 @@ class IntelliJIDE(
override suspend fun listDir(dir: String): List<List<Any>> {
val files = File(URI(dir)).listFiles()?.map {
listOf(it.name, if (it.isDirectory) FileType.DIRECTORY else FileType.FILE)
listOf(it.name, if (it.isDirectory) FileType.DIRECTORY.value else FileType.FILE.value)
} ?: emptyList()
return files
}
override suspend fun getLastModified(files: List<String>): Map<String, Long> {
override suspend fun getFileStats(files: List<String>): Map<String, FileStats> {
return files.associateWith { file ->
File(URI(file)).lastModified()
FileStats(File(URI(file)).lastModified(), File(URI(file)).length())
}
}

View file

@ -125,7 +125,9 @@ class DiffStreamHandler(
diffBlocks.remove(diffBlock)
if (!didAccept) {
if (didAccept) {
updatePositionsOnAccept(diffBlock.startLine)
} else {
updatePositionsOnReject(diffBlock.startLine, diffBlock.addedLines.size, diffBlock.deletedLines.size)
}
@ -186,10 +188,16 @@ class DiffStreamHandler(
}
}
private fun updatePositionsOnAccept(startLine: Int) {
updatePositions(startLine, 0)
}
private fun updatePositionsOnReject(startLine: Int, numAdditions: Int, numDeletions: Int) {
val offset = -numAdditions + numDeletions
updatePositions(startLine, offset)
}
private fun updatePositions(startLine: Int, offset: Int) {
diffBlocks.forEach { block ->
if (block.startLine > startLine) {
block.updatePosition(block.startLine + offset)

View file

@ -3,6 +3,7 @@ package com.github.continuedev.continueintellijextension.editor
import com.github.continuedev.continueintellijextension.utils.getAltKeyLabel
import com.github.continuedev.continueintellijextension.utils.getShiftKeyLabel
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.invokeLater
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.LogicalPosition
@ -11,6 +12,7 @@ import com.intellij.openapi.editor.markup.HighlighterLayer
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import com.intellij.ui.JBColor
import com.intellij.util.application
import java.awt.*
import javax.swing.BorderFactory
import javax.swing.JButton
@ -41,7 +43,14 @@ class VerticalDiffBlock(
}
fun clearEditorUI() {
deletionInlay?.dispose()
deletionInlay?.let {
// Ensure that dispose is executed on EDT
if (application.isDispatchThread) {
it.dispose()
} else {
invokeLater { it.dispose() }
}
}
removeGreenHighlighters()
removeButtons()
}

View file

@ -28,6 +28,10 @@ class ContinuePluginSelectionListener(
private var lastActiveEditor: Editor? = null
override fun selectionChanged(e: SelectionEvent) {
if (e.editor.isDisposed || e.editor.project?.isDisposed == true) {
return
}
debouncer.debounce { handleSelection(e) }
}
@ -106,6 +110,19 @@ class ContinuePluginSelectionListener(
ApplicationManager.getApplication().invokeLater {
val document = editor.document
val (startLine, endLine, isFullLineSelection) = getSelectionInfo(model, document)
// Check if entire file is selected
val isEntireFileSelected = model.selectionStart == 0 &&
model.selectionEnd == document.textLength
// Scroll to top if entire file selected so that the user can see the input
if (isEntireFileSelected) {
editor.scrollingModel.scrollTo(
LogicalPosition(0, 0),
com.intellij.openapi.editor.ScrollType.CENTER
)
}
val selectionTopY = calculateSelectionTopY(editor, startLine, endLine, isFullLineSelection)
val tooltipX = calculateTooltipX(editor, document, startLine, endLine, isFullLineSelection)

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