diff --git a/.github/workflows/pr_checks.yaml b/.github/workflows/pr_checks.yaml index c41c57f72..f629f9331 100644 --- a/.github/workflows/pr_checks.yaml +++ b/.github/workflows/pr_checks.yaml @@ -5,6 +5,7 @@ on: branches: - main paths: + - "extensions/intellij/**" - "extensions/vscode/**" - "core/**" - "gui/**" @@ -274,6 +275,11 @@ jobs: run: | cd core npm test + env: + OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }} + MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }} vscode-get-test-file-matrix: runs-on: ubuntu-latest @@ -370,7 +376,7 @@ jobs: path: extensions/vscode/e2e/storage vscode-e2e-tests: - name: ${{ matrix.test_file }}" + name: ${{ matrix.test_file }} (${{ matrix.command }}) needs: [ vscode-download-e2e-dependencies, @@ -384,6 +390,7 @@ jobs: fail-fast: false matrix: test_file: ${{ fromJson(needs.vscode-get-test-file-matrix.outputs.test_file_matrix) }} + command: [ "e2e:ci:run", "e2e:ci:run-yaml" ] steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 @@ -432,8 +439,7 @@ jobs: - name: Run e2e tests run: | cd extensions/vscode - TEST_FILE="${{ matrix.test_file }}" npm run e2e:ci:run - + TEST_FILE="${{ matrix.test_file }}" npm run ${{ matrix.command }} env: DISPLAY: :99 @@ -546,7 +552,7 @@ jobs: with: url: http://127.0.0.1:8082 max-attempts: 15 - retry-delay: 5s + retry-delay: 30s - name: Run tests run: | @@ -572,6 +578,4 @@ jobs: with: name: jb-failure-report path: | - ${{ github.workspace }}/extensions/intellij/build/reports - - + ${{ github.workspace }}/extensions/intellij/build/reports \ No newline at end of file diff --git a/.vscode/launch.json b/.vscode/launch.json index dfe474f40..cdb502c8c 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -20,10 +20,10 @@ "outFiles": ["${workspaceFolder}/extensions/vscode/out/extension.js"], "preLaunchTask": "vscode-extension:build", "env": { + // "CONTROL_PLANE_ENV": "local", "CONTINUE_GLOBAL_DIR": "${workspaceFolder}/extensions/.continue-debug" // "staging" for the preview deployment "CONTINUE_GLOBAL_DIR": "${workspaceFolder}/extensions/.continue-debug" // "local" for entirely local development of control plane/proxy - // "CONTROL_PLANE_ENV": "staging" } }, { diff --git a/binary/build.js b/binary/build.js index 045fb64f2..11aaf5c59 100644 --- a/binary/build.js +++ b/binary/build.js @@ -118,6 +118,22 @@ 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 at build time + 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]) { @@ -263,9 +279,12 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) { // 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`, ""); + // fs.writeFileSync(`${targetDir}/package.json`, ""); } + // Cleanup - this is needed when running locally + fs.rmSync("out/package.json"); + const pathsToVerify = []; for (const target of targets) { const exe = target.startsWith("win") ? ".exe" : ""; diff --git a/binary/package-lock.json b/binary/package-lock.json index 158342e0b..89ecc53cc 100644 --- a/binary/package-lock.json +++ b/binary/package-lock.json @@ -48,7 +48,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.621.0", "@aws-sdk/credential-providers": "^3.620.1", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.0", + "@continuedev/config-yaml": "^1.0.10", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.2", "@continuedev/openai-adapters": "^1.0.10", diff --git a/core/autocomplete/README.md b/core/autocomplete/README.md deleted file mode 100644 index ab6e9adfb..000000000 --- a/core/autocomplete/README.md +++ /dev/null @@ -1,158 +0,0 @@ -# Tab Autocomplete (beta) - -Continue now provides support for tab autocomplete in [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue) and [JetBrains IDEs](https://plugins.jetbrains.com/plugin/22707-continue/edit). We will be greatly improving the experience over the next few releases, and it is always helpful to hear feedback. If you have any problems or suggestions, please let us know in our [Discord](https://discord.gg/vapESyrFmJ). - -## Setting up with Ollama (default) - -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-base -``` - -Once it has been downloaded, you should begin to see completions in VS Code. - -## Setting up with LM Studio - -You can also set up tab-autocomplete with a local LM Studio instance by following these steps: - -1. Download the latest version of LM Studio from [here](https://lmstudio.ai/) -2. Download a model (e.g. search for `Qwen/Qwen2.5-Coder-1.5B-Instruct-GGUF` and choose one of the options there) -3. Go to the server section (button is on the left), select your model from the dropdown at the top, and click "Start Server" -4. Go to the "My Models" section (button is on the left), find your selected model, and copy the name the path (example: `Qwen/Qwen2.5-Coder-1.5B-Instruct-GGUF/qwen2.5-coder-1.5b-instruct-q4_k_m.gguf`); this will be used as the "model" attribute in Continue -5. Go to Continue and modify the configurations for a [custom model](#setting-up-a-custom-model) -6. Set the "provider" to `lmstudio` and the "model" to the path copied earlier - -Example: - -```json title="config.json" -{ - "tabAutocompleteModel": { - "title": "Qwen2.5-Coder 1.5b", - "model": "Qwen/Qwen2.5-Coder-1.5B-Instruct-GGUF", - "provider": "lmstudio" - } -} -``` - -## Setting up a custom model - -All of the configuration options available for chat models are available to use for tab-autocomplete. For example, if you wanted to use a remote vLLM instance you would edit your `config.json` like this (note that it is not inside the models array), filling in the correct model name and vLLM endpoint: - -```json title="config.json" -{ - "tabAutocompleteModel": { - "title": "Tab Autocomplete Model", - "provider": "openai", - "model": "", - "apiBase": "" - }, - ... -} -``` - -As another example, say you want to use a different model, `deepseek-coder:6.7b-base`, with Ollama: - -```json title="config.json" -{ - "tabAutocompleteModel": { - "title": "Tab Autocomplete Model", - "provider": "ollama", - "model": "deepseek-coder:6.7b-base" - }, - ... -} -``` - -If you aren't yet familiar with the available options, you can learn more in our [overview](../setup/overview.md). - -### What model should I use? - -If you are running the model locally, we recommend `qwen2.5-coder:1.5b`. - -If you have a bit more compute, or are running a model in the cloud, you can upgrade to `qwen2.5-coder:7b`. - -Regardless of what you are willing to spend, we do not recommend using GPT or Claude for autocomplete. Learn why [below](#i-want-better-completions-should-i-use-gpt-4). - -## Configuration Options - -The following can be configured in `config.json`: - -### `tabAutocompleteModel` - -This is just another object like the ones in the `"models"` array of `config.json`. You can choose and configure any model you would like, but we strongly suggest using a small model made for tab-autocomplete, such as `deepseek-1b`, `qwen2.5-coder:1.5b`, or `starcoder-3b`. - -### `tabAutocompleteOptions` - -This object allows you to customize the behavior of tab-autocomplete. The available options are: - -- `useFileSuffix`: Determines whether to use the file suffix in the prompt. (Boolean) -- `maxPromptTokens`: The maximum number of prompt tokens to use. A smaller number will yield faster completions, but less context. (Number) -- `debounceDelay`: The delay in milliseconds before triggering autocomplete after a keystroke. (Number) -- `maxSuffixPercentage`: The maximum percentage of the prompt that can be dedicated to the suffix. (Number) -- `prefixPercentage`: The percentage of the input that should be dedicated to the prefix. (Number) -- `template`: An optional template string to be used for autocomplete. It will be rendered with the Mustache templating language, and is passed the 'prefix' and 'suffix' variables. (String) -- `multilineCompletions`: Whether to enable multiline completions ("always", "never", or "auto"). Defaults to "auto". - -### Full example - -```json title="config.json" -{ - "tabAutocompleteModel": { - "title": "Tab Autocomplete Model", - "provider": "ollama", - "model": "qwen2.5-coder:1.5b-base", - "apiBase": "https://" - }, - "tabAutocompleteOptions": { - "maxPromptTokens": 400, - "prefixPercentage": 0.5 - } -} -``` - -## Troubleshooting - -### 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. - -### I'm not seeing any completions - -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-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. 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. - -### Completions are slow - -Depending on your hardware, you may want to try a smaller, faster model. If 3b isn't working for you we recommend trying `deepseek-coder:1.3b-base`. - -### Completions don't know about my code - -We are working on this! Right now Continue uses the Language Server Protocol to add definitions to the prompt, as well as using similarity search over recently edited files. We will be improving the accuracy of this system greatly over the next few weeks. - -### Completions contain formatting errors - -If you're seeing a common pattern of mistake that might be helpful to report, please share in Discord. We will do our best to fix it as soon as possible. - -## How to turn off autocomplete - -### VS Code - -Click the "Continue" button in the status panel at the bottom right of the screen. The checkmark will become a "cancel" symbol and you will no longer see completions. You can click again to turn it back on. - -Alternatively, open VS Code settings, search for "Continue" and uncheck the box for "Enable Tab Autocomplete". - -### JetBrains - -Open Settings -> Tools -> Continue and uncheck the box for "Enable Tab Autocomplete". - -### Feedback - -If you're turning off autocomplete, we'd love to hear how we can improve! Please let us know in our [Discord](https://discord.gg/vapESyrFmJ) or file an issue on GitHub. diff --git a/core/config/ConfigHandler.test.ts b/core/config/ConfigHandler.test.ts index 5a25e71fc..deb1deded 100644 --- a/core/config/ConfigHandler.test.ts +++ b/core/config/ConfigHandler.test.ts @@ -14,7 +14,7 @@ describe.skip("Test the ConfigHandler and E2E config loading", () => { expect(profiles[0].id).toBe("local"); const currentProfile = testConfigHandler.currentProfile; - expect(currentProfile.profileId).toBe("local"); + expect(currentProfile.profileDescription.id).toBe("local"); }); test("should load the default config successfully", async () => { diff --git a/core/config/ConfigHandler.ts b/core/config/ConfigHandler.ts index 2c91148ba..626e237db 100644 --- a/core/config/ConfigHandler.ts +++ b/core/config/ConfigHandler.ts @@ -14,18 +14,21 @@ import Ollama from "../llm/llms/Ollama.js"; import { GlobalContext } from "../util/GlobalContext.js"; import { getConfigJsonPath } from "../util/paths.js"; -import { ConfigResult } from "./load.js"; +import { ConfigResult } from "@continuedev/config-yaml"; +import { controlPlaneEnv } from "../control-plane/env.js"; +import { usePlatform } from "../control-plane/flags.js"; import { LOCAL_ONBOARDING_CHAT_MODEL, ONBOARDING_LOCAL_MODEL_TITLE, } from "./onboarding.js"; import ControlPlaneProfileLoader from "./profile/ControlPlaneProfileLoader.js"; import LocalProfileLoader from "./profile/LocalProfileLoader.js"; +import PlatformProfileLoader from "./profile/PlatformProfileLoader.js"; import { ProfileDescription, ProfileLifecycleManager, } from "./ProfileLifecycleManager.js"; -import { pathToFileURL } from "url"; +import { localPathToUri } from "../util/pathToUri.js"; export type { ProfileDescription }; @@ -57,7 +60,7 @@ export class ConfigHandler { writeLog, ); this.profiles = [new ProfileLifecycleManager(localProfileLoader)]; - this.selectedProfileId = localProfileLoader.profileId; + this.selectedProfileId = localProfileLoader.description.id; // Always load local profile immediately in case control plane doesn't load try { @@ -77,39 +80,40 @@ export class ConfigHandler { get currentProfile() { return ( - this.profiles.find((p) => p.profileId === this.selectedProfileId) ?? - this.fallbackProfile + this.profiles.find( + (p) => p.profileDescription.id === this.selectedProfileId, + ) ?? this.fallbackProfile ); } get inactiveProfiles() { - return this.profiles.filter((p) => p.profileId !== this.selectedProfileId); + return this.profiles.filter( + (p) => p.profileDescription.id !== this.selectedProfileId, + ); } async openConfigProfile(profileId?: string) { let openProfileId = profileId || this.selectedProfileId; if (openProfileId === "local") { - await this.ide.openFile(pathToFileURL(getConfigJsonPath()).toString()); + await this.ide.openFile(localPathToUri(getConfigJsonPath())); } else { - await this.ide.openUrl( - "https://app.continue.dev/", - // `https://app.continue.dev/workspaces/${openProfileId}/chat`, - ); + await this.ide.openUrl(`${controlPlaneEnv.APP_URL}${openProfileId}`); } } - private async fetchControlPlaneProfiles() { + private async loadPlatformProfiles() { // Get the profiles and create their lifecycle managers this.controlPlaneClient - .listWorkspaces() - .then(async (workspaces) => { + .listAssistants() + .then(async (assistants) => { this.profiles = this.profiles.filter( - (profile) => profile.profileId === "local", + (profile) => profile.profileDescription.id === "local", ); - workspaces.forEach((workspace) => { - const profileLoader = new ControlPlaneProfileLoader( - workspace.id, - workspace.name, + assistants.forEach((assistant) => { + const profileLoader = new PlatformProfileLoader( + assistant.configResult, + assistant.ownerSlug, + assistant.packageSlug, this.controlPlaneClient, this.ide, this.ideSettingsPromise, @@ -141,10 +145,67 @@ export class ConfigHandler { } }) .catch((e) => { - console.error(e); + console.error("Failed to list assistants: ", e); }); } + private platformProfilesRefreshInterval: NodeJS.Timeout | undefined; + + private async fetchControlPlaneProfiles() { + if (usePlatform()) { + clearInterval(this.platformProfilesRefreshInterval); + await this.loadPlatformProfiles(); + this.platformProfilesRefreshInterval = setInterval( + this.loadPlatformProfiles.bind(this), + PlatformProfileLoader.RELOAD_INTERVAL, + ); + } else { + this.controlPlaneClient + .listWorkspaces() + .then(async (workspaces) => { + this.profiles = this.profiles.filter( + (profile) => profile.profileDescription.id === "local", + ); + workspaces.forEach((workspace) => { + const profileLoader = new ControlPlaneProfileLoader( + workspace.id, + workspace.name, + this.controlPlaneClient, + this.ide, + this.ideSettingsPromise, + this.writeLog, + this.reloadConfig.bind(this), + ); + this.profiles.push(new ProfileLifecycleManager(profileLoader)); + }); + + this.notifyProfileListeners( + this.profiles.map((profile) => profile.profileDescription), + ); + + // Check the last selected workspace, and reload if it isn't local + const workspaceId = await this.getWorkspaceId(); + const lastSelectedWorkspaceIds = + this.globalContext.get("lastSelectedProfileForWorkspace") ?? {}; + const selectedWorkspaceId = lastSelectedWorkspaceIds[workspaceId]; + if (selectedWorkspaceId) { + this.selectedProfileId = selectedWorkspaceId; + await this.loadConfig(); + } else { + // Otherwise we stick with local profile, and record choice + lastSelectedWorkspaceIds[workspaceId] = this.selectedProfileId; + this.globalContext.update( + "lastSelectedProfileForWorkspace", + lastSelectedWorkspaceIds, + ); + } + }) + .catch((e) => { + console.error(e); + }); + } + } + async setSelectedProfile(profileId: string) { this.selectedProfileId = profileId; const result = await this.loadConfig(); diff --git a/core/config/ProfileLifecycleManager.ts b/core/config/ProfileLifecycleManager.ts index c5ae16f91..88fc387c5 100644 --- a/core/config/ProfileLifecycleManager.ts +++ b/core/config/ProfileLifecycleManager.ts @@ -1,15 +1,17 @@ +import { ConfigResult, ConfigValidationError } from "@continuedev/config-yaml"; import { BrowserSerializedContinueConfig, ContinueConfig, IContextProvider, } from "../index.js"; -import { ConfigResult, finalToBrowserConfig } from "./load.js"; +import { finalToBrowserConfig } from "./load.js"; import { IProfileLoader } from "./profile/IProfileLoader.js"; export interface ProfileDescription { title: string; id: string; + errors: ConfigValidationError[] | undefined; } export class ProfileLifecycleManager { @@ -19,19 +21,8 @@ export class ProfileLifecycleManager { constructor(private readonly profileLoader: IProfileLoader) {} - get profileId() { - return this.profileLoader.profileId; - } - - get profileTitle() { - return this.profileLoader.profileTitle; - } - get profileDescription(): ProfileDescription { - return { - title: this.profileTitle, - id: this.profileId, - }; + return this.profileLoader.description; } clearConfig() { @@ -71,14 +62,10 @@ export class ProfileLifecycleManager { result.config.contextProviders = ( result.config.contextProviders ?? [] ).concat(additionalContextProviders); - - this.savedConfigResult = result; - resolve(result); - } else if (result.errors) { - reject( - `Error in config.json: ${result.errors.map((item) => item.message).join(" | ")}`, - ); } + + this.savedConfigResult = result; + resolve(result); }); // Wait for the config promise to resolve diff --git a/core/config/load.ts b/core/config/load.ts index 9a6599608..689f53ca5 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -62,6 +62,8 @@ import { getEsbuildBinaryPath, } from "../util/paths"; +import { ConfigResult, ConfigValidationError } from "@continuedev/config-yaml"; +import { usePlatform } from "../control-plane/flags"; import { defaultContextProvidersJetBrains, defaultContextProvidersVsCode, @@ -70,13 +72,8 @@ import { } from "./default"; import { getSystemPromptDotFile } from "./getSystemPromptDotFile"; // import { isSupportedLanceDbCpuTarget } from "./util"; -import { ConfigValidationError, validateConfig } from "./validation.js"; - -export interface ConfigResult { - config: T | undefined; - errors: ConfigValidationError[] | undefined; - configLoadInterrupted: boolean; -} +import { validateConfig } from "./validation.js"; +import { localPathToUri } from "../util/pathToUri"; function resolveSerializedConfig(filepath: string): SerializedContinueConfig { let content = fs.readFileSync(filepath, "utf8"); @@ -229,7 +226,7 @@ function isModelDescription( return (llm as ModelDescription).title !== undefined; } -function isContextProviderWithParams( +export function isContextProviderWithParams( contextProvider: CustomContextProvider | ContextProviderWithParams, ): contextProvider is ContextProviderWithParams { return (contextProvider as ContextProviderWithParams).name !== undefined; @@ -582,6 +579,7 @@ function finalToBrowserConfig( experimental: final.experimental, docs: final.docs, tools: final.tools, + usePlatform: usePlatform(), }; } @@ -816,7 +814,7 @@ async function loadFullConfigNode( "Could not load config.ts as absolute path, retrying as file url ...", ); try { - module = await import(`file://${configJsPath}`); + module = await import(localPathToUri(configJsPath)); } catch (e) { throw new Error("Could not load config.ts as file url either", { cause: e, diff --git a/core/config/profile/ControlPlaneProfileLoader.ts b/core/config/profile/ControlPlaneProfileLoader.ts index 448dbdb42..38c7fb389 100644 --- a/core/config/profile/ControlPlaneProfileLoader.ts +++ b/core/config/profile/ControlPlaneProfileLoader.ts @@ -7,16 +7,16 @@ import { IdeSettings, SerializedContinueConfig, } from "../../index.js"; -import { ConfigResult } from "../load.js"; +import { ConfigResult } from "@continuedev/config-yaml"; +import { ProfileDescription } from "../ProfileLifecycleManager.js"; import doLoadConfig from "./doLoadConfig.js"; import { IProfileLoader } from "./IProfileLoader.js"; export default class ControlPlaneProfileLoader implements IProfileLoader { private static RELOAD_INTERVAL = 1000 * 60 * 15; // every 15 minutes - readonly profileId: string; - profileTitle: string; + description: ProfileDescription; workspaceSettings: ConfigJson | undefined; @@ -29,12 +29,17 @@ export default class ControlPlaneProfileLoader implements IProfileLoader { private writeLog: (message: string) => Promise, private readonly onReload: () => void, ) { - this.profileId = workspaceId; - this.profileTitle = workspaceTitle; + this.description = { + id: workspaceId, + title: workspaceTitle, + errors: undefined, + }; setInterval(async () => { this.workspaceSettings = - await this.controlPlaneClient.getSettingsForWorkspace(this.profileId); + await this.controlPlaneClient.getSettingsForWorkspace( + this.description.id, + ); this.onReload(); }, ControlPlaneProfileLoader.RELOAD_INTERVAL); } @@ -43,7 +48,7 @@ export default class ControlPlaneProfileLoader implements IProfileLoader { const settings = this.workspaceSettings ?? ((await this.controlPlaneClient.getSettingsForWorkspace( - this.profileId, + this.description.id, )) as any); const serializedConfig: SerializedContinueConfig = settings; @@ -53,6 +58,8 @@ export default class ControlPlaneProfileLoader implements IProfileLoader { this.controlPlaneClient, this.writeLog, serializedConfig, + undefined, + undefined, this.workspaceId, ); diff --git a/core/config/profile/IProfileLoader.ts b/core/config/profile/IProfileLoader.ts index 2d22a821e..5d0717252 100644 --- a/core/config/profile/IProfileLoader.ts +++ b/core/config/profile/IProfileLoader.ts @@ -1,12 +1,12 @@ // ProfileHandlers manage the loading of a config, allowing us to abstract over different ways of getting to a ContinueConfig +import { ConfigResult } from "@continuedev/config-yaml"; import { ContinueConfig } from "../../index.js"; -import { ConfigResult } from "../load.js"; +import { ProfileDescription } from "../ProfileLifecycleManager.js"; // After we have the ContinueConfig, the ConfigHandler takes care of everything else (loading models, lifecycle, etc.) export interface IProfileLoader { - profileTitle: string; - profileId: string; + description: ProfileDescription; doLoadConfig(): Promise>; setIsActive(isActive: boolean): void; } diff --git a/core/config/profile/LocalProfileLoader.ts b/core/config/profile/LocalProfileLoader.ts index 0705c8745..644e97069 100644 --- a/core/config/profile/LocalProfileLoader.ts +++ b/core/config/profile/LocalProfileLoader.ts @@ -1,14 +1,18 @@ +import { ConfigResult } from "@continuedev/config-yaml"; import { ControlPlaneClient } from "../../control-plane/client.js"; import { ContinueConfig, IDE, IdeSettings } from "../../index.js"; -import { ConfigResult } from "../load.js"; +import { ProfileDescription } from "../ProfileLifecycleManager.js"; import doLoadConfig from "./doLoadConfig.js"; import { IProfileLoader } from "./IProfileLoader.js"; export default class LocalProfileLoader implements IProfileLoader { static ID = "local"; - profileId = LocalProfileLoader.ID; - profileTitle = "Local Config"; + description: ProfileDescription = { + id: LocalProfileLoader.ID, + title: "Local Config", + errors: undefined, + }; constructor( private ide: IDE, @@ -18,13 +22,19 @@ export default class LocalProfileLoader implements IProfileLoader { ) {} async doLoadConfig(): Promise> { - return doLoadConfig( + const result = await doLoadConfig( this.ide, this.ideSettingsPromise, this.controlPlaneClient, this.writeLog, undefined, + undefined, + undefined, ); + + this.description.errors = result.errors; + + return result; } setIsActive(isActive: boolean): void {} diff --git a/core/config/profile/PlatformProfileLoader.ts b/core/config/profile/PlatformProfileLoader.ts new file mode 100644 index 000000000..d0f7d6f80 --- /dev/null +++ b/core/config/profile/PlatformProfileLoader.ts @@ -0,0 +1,90 @@ +import { ClientConfigYaml } from "@continuedev/config-yaml/dist/schemas/index.js"; + +import { ControlPlaneClient } from "../../control-plane/client.js"; +import { ContinueConfig, IDE, IdeSettings } from "../../index.js"; + +import { ConfigResult } from "@continuedev/config-yaml"; +import { ProfileDescription } from "../ProfileLifecycleManager.js"; +import doLoadConfig from "./doLoadConfig.js"; +import { IProfileLoader } from "./IProfileLoader.js"; + +/** + * Metadata about the package that is currently being loaded + * If this is `undefined`, it's not a config from the platform, + * could be local for example. + */ +export interface PlatformConfigMetadata { + ownerSlug: string; + packageSlug: string; +} + +export default class PlatformProfileLoader implements IProfileLoader { + static RELOAD_INTERVAL = 1000 * 60 * 15; // every 15 minutes + + description: ProfileDescription; + + constructor( + private configResult: ConfigResult, + private readonly ownerSlug: string, + private readonly packageSlug: string, + private readonly controlPlaneClient: ControlPlaneClient, + private readonly ide: IDE, + private ideSettingsPromise: Promise, + private writeLog: (message: string) => Promise, + private readonly onReload: () => void, + ) { + this.description = { + id: `${ownerSlug}/${packageSlug}`, + title: `${ownerSlug}/${packageSlug}`, + errors: configResult.errors, + }; + + setInterval(async () => { + const assistants = await this.controlPlaneClient.listAssistants(); + const newConfigResult = assistants.find( + (assistant) => + assistant.packageSlug === this.packageSlug && + assistant.ownerSlug === this.ownerSlug, + )?.configResult; + if (!newConfigResult) { + return; + } + this.configResult = { + config: newConfigResult.config, + errors: newConfigResult.errors, + configLoadInterrupted: false, + }; + this.onReload(); + }, PlatformProfileLoader.RELOAD_INTERVAL); + } + + async doLoadConfig(): Promise> { + if (this.configResult.errors?.length) { + return { + config: undefined, + errors: this.configResult.errors, + configLoadInterrupted: false, + }; + } + + const results = await doLoadConfig( + this.ide, + this.ideSettingsPromise, + this.controlPlaneClient, + this.writeLog, + undefined, + this.configResult.config, + { + ownerSlug: this.ownerSlug, + packageSlug: this.packageSlug, + }, + ); + + return { + ...results, + errors: [], // Don't do config validation here, it happens in admin panel + }; + } + + setIsActive(isActive: boolean): void {} +} diff --git a/core/config/profile/doLoadConfig.ts b/core/config/profile/doLoadConfig.ts index a82dd896d..5f20ac7e2 100644 --- a/core/config/profile/doLoadConfig.ts +++ b/core/config/profile/doLoadConfig.ts @@ -1,5 +1,7 @@ import fs from "fs"; +import { ConfigResult, ConfigValidationError } from "@continuedev/config-yaml"; +import { ClientConfigYaml } from "@continuedev/config-yaml/dist/schemas"; import { ContinueConfig, ContinueRcJson, @@ -15,9 +17,9 @@ import ContinueProxy from "../../llm/llms/stubs/ContinueProxy"; import { getConfigYamlPath } from "../../util/paths"; import { Telemetry } from "../../util/posthog"; import { TTS } from "../../util/tts"; -import { ConfigResult, loadFullConfigNode } from "../load"; -import { ConfigValidationError } from "../validation"; +import { loadFullConfigNode } from "../load"; import { loadContinueConfigFromYaml } from "../yaml/loadYaml"; +import { PlatformConfigMetadata } from "./PlatformProfileLoader"; export default async function doLoadConfig( ide: IDE, @@ -25,6 +27,8 @@ export default async function doLoadConfig( controlPlaneClient: ControlPlaneClient, writeLog: (message: string) => Promise, overrideConfigJson: SerializedContinueConfig | undefined, + overrideConfigYaml: ClientConfigYaml | undefined, + platformConfigMetadata: PlatformConfigMetadata | undefined, workspaceId?: string, ): Promise> { const workspaceConfigs = await getWorkspaceConfigs(ide); @@ -39,7 +43,7 @@ export default async function doLoadConfig( let errors: ConfigValidationError[] | undefined; let configLoadInterrupted = false; - if (fs.existsSync(configYamlPath)) { + if (fs.existsSync(configYamlPath) || overrideConfigYaml) { const result = await loadContinueConfigFromYaml( ide, workspaceConfigs.map((c) => JSON.stringify(c)), @@ -48,8 +52,9 @@ export default async function doLoadConfig( uniqueId, writeLog, workOsAccessToken, - undefined, - // overrideConfigYaml, TODO + overrideConfigYaml, + platformConfigMetadata, + controlPlaneClient, ); newConfig = result.config; errors = result.errors; diff --git a/core/config/validation.ts b/core/config/validation.ts index e10b3f523..d28bb7809 100644 --- a/core/config/validation.ts +++ b/core/config/validation.ts @@ -1,11 +1,7 @@ +import { ConfigValidationError } from "@continuedev/config-yaml"; import { ModelDescription, SerializedContinueConfig } from "../"; import { Telemetry } from "../util/posthog"; -export interface ConfigValidationError { - fatal: boolean; - message: string; -} - /** * Validates a SerializedContinueConfig object to ensure all properties are correctly formed. * @param config The configuration object to validate. diff --git a/core/config/yaml/convertFromJson.ts b/core/config/yaml/convertFromJson.ts index 59482b5c3..4109d7d37 100644 --- a/core/config/yaml/convertFromJson.ts +++ b/core/config/yaml/convertFromJson.ts @@ -8,6 +8,7 @@ export function convertConfigJsonToConfigYaml( ): ConfigYaml { return { name: "Local Config", + version: "1.0.0", models: [ ...configJson.models.map( (model): ModelConfig => ({ diff --git a/core/config/yaml/default.ts b/core/config/yaml/default.ts index f991561df..cfdffc12d 100644 --- a/core/config/yaml/default.ts +++ b/core/config/yaml/default.ts @@ -5,10 +5,12 @@ export const defaultConfigYaml: ConfigYaml = { models: [], context: [], name: "Local Config", + version: "1.0.0", }; export const defaultConfigYamlJetBrains: ConfigYaml = { models: [], context: [], name: "Local Config", + version: "1.0.0", }; diff --git a/core/config/yaml/loadYaml.ts b/core/config/yaml/loadYaml.ts index ad33ea4d8..5e0161ad8 100644 --- a/core/config/yaml/loadYaml.ts +++ b/core/config/yaml/loadYaml.ts @@ -1,13 +1,12 @@ import fs from "node:fs"; -import path from "path"; import { - extendConfig, + ConfigResult, fillTemplateVariables, + resolveSecretsOnClient, validateConfigYaml, } from "@continuedev/config-yaml"; -import { ConfigYaml } from "@continuedev/config-yaml/dist/schemas"; -import { ValidationLevel } from "@continuedev/config-yaml/dist/validation"; +import { ClientConfigYaml } from "@continuedev/config-yaml/dist/schemas"; import { fetchwithRequestOptions } from "@continuedev/fetch"; import * as YAML from "yaml"; @@ -26,23 +25,17 @@ import { contextProviderClassFromName } from "../../context/providers/index"; import { allEmbeddingsProviders } from "../../indexing/allEmbeddingsProviders"; import FreeTrial from "../../llm/llms/FreeTrial"; import TransformersJsEmbeddingsProvider from "../../llm/llms/TransformersJsEmbeddingsProvider"; -import { - getConfigYamlPath, - getContinueDotEnv, - readAllGlobalPromptFiles, -} from "../../util/paths"; -import { getSystemPromptDotFile } from "../getSystemPromptDotFile"; -import { ConfigValidationError } from "../validation.js"; - -import { llmsFromModelConfig } from "./models"; -import { getAllPromptFiles } from "../../promptFiles/v2/getPromptFiles"; import { slashCommandFromPromptFileV1 } from "../../promptFiles/v1/slashCommandFromPromptFile"; +import { getAllPromptFiles } from "../../promptFiles/v2/getPromptFiles"; +import { getConfigYamlPath, getContinueDotEnv } from "../../util/paths"; +import { getSystemPromptDotFile } from "../getSystemPromptDotFile"; +import { PlatformConfigMetadata } from "../profile/PlatformProfileLoader"; -export interface ConfigResult { - config: T | undefined; - errors: ConfigValidationError[] | undefined; - configLoadInterrupted: boolean; -} +import CodebaseContextProvider from "../../context/providers/CodebaseContextProvider"; +import FileContextProvider from "../../context/providers/FileContextProvider"; +import PromptFilesContextProvider from "../../context/providers/PromptFilesContextProvider"; +import { ControlPlaneClient } from "../../control-plane/client"; +import { llmsFromModelConfig } from "./models"; function renderTemplateVars(configYaml: string): string { const data: Record = {}; @@ -60,36 +53,28 @@ function renderTemplateVars(configYaml: string): string { function loadConfigYaml( workspaceConfigs: string[], - ideSettings: IdeSettings, - ideType: IdeType, rawYaml: string, -): ConfigResult { - const renderedYaml = renderTemplateVars(rawYaml); - let config = YAML.parse(renderedYaml) as ConfigYaml; + overrideConfigYaml: ClientConfigYaml | undefined, +): ConfigResult { + let config = + overrideConfigYaml ?? + (YAML.parse(renderTemplateVars(rawYaml)) as ClientConfigYaml); const errors = validateConfigYaml(config); - if (errors?.some((error) => error.level === ValidationLevel.Error)) { + if (errors?.some((error) => error.fatal)) { return { - errors: errors.map((error) => ({ - message: error.message, - fatal: error.level === ValidationLevel.Error, - })), + errors, config: undefined, configLoadInterrupted: true, }; } - for (const workspaceConfig of workspaceConfigs) { - const rendered = renderTemplateVars(workspaceConfig); - config = extendConfig(config, YAML.parse(rendered) as ConfigYaml); - } - // Set defaults if undefined (this lets us keep config.json uncluttered for new users) return { config, errors: errors.map((error) => ({ message: error.message, - fatal: error.level === ValidationLevel.Error, + fatal: error.fatal, })), configLoadInterrupted: false, }; @@ -113,12 +98,13 @@ async function slashCommandsFromV1PromptFiles( } async function configYamlToContinueConfig( - config: ConfigYaml, + config: ClientConfigYaml, ide: IDE, ideSettings: IdeSettings, uniqueId: string, writeLog: (log: string) => Promise, workOsAccessToken: string | undefined, + platformConfigMetadata: PlatformConfigMetadata | undefined, allowFreeTrial: boolean = true, ): Promise { const continueConfig: ContinueConfig = { @@ -126,10 +112,24 @@ async function configYamlToContinueConfig( models: [], tabAutocompleteModels: [], tools: [], + systemMessage: config.rules?.join("\n"), embeddingsProvider: new TransformersJsEmbeddingsProvider(), experimental: { - modelContextProtocolServers: [], + modelContextProtocolServers: config.mcpServers?.map((mcpServer) => ({ + transport: { + type: "stdio", + command: mcpServer.command, + args: mcpServer.args ?? [], + env: mcpServer.env, + }, + })), }, + docs: config.docs?.map((doc) => ({ + title: doc.name, + startUrl: doc.startUrl, + rootUrl: doc.rootUrl, + faviconUrl: doc.faviconUrl, + })), }; // Models @@ -146,9 +146,13 @@ async function configYamlToContinueConfig( uniqueId, ideSettings, writeLog, + platformConfigMetadata, + continueConfig.systemMessage, ); continueConfig.models.push(...llms); - } else if (model.roles?.includes("autocomplete")) { + } + + if (model.roles?.includes("autocomplete")) { // Autocomplete models array const llms = await llmsFromModelConfig( model, @@ -156,6 +160,8 @@ async function configYamlToContinueConfig( uniqueId, ideSettings, writeLog, + platformConfigMetadata, + continueConfig.systemMessage, ); continueConfig.tabAutocompleteModels?.push(...llms); } @@ -181,18 +187,33 @@ async function configYamlToContinueConfig( // TODO: Split into model roles. - // Context + // Context providers + const codebaseContextParams: IContextProvider[] = + (config.context || []).find((cp) => cp.uses === "codebase")?.with || {}; + const DEFAULT_CONTEXT_PROVIDERS = [ + new FileContextProvider({}), + new CodebaseContextProvider(codebaseContextParams), + new PromptFilesContextProvider({}), + ]; + + const DEFAULT_CONTEXT_PROVIDERS_TITLES = DEFAULT_CONTEXT_PROVIDERS.map( + ({ description: { title } }) => title, + ); + continueConfig.contextProviders = config.context ?.map((context) => { const cls = contextProviderClassFromName(context.uses) as any; if (!cls) { - console.warn(`Unknown context provider ${context.uses}`); + if (!DEFAULT_CONTEXT_PROVIDERS_TITLES.includes(context.uses)) { + console.warn(`Unknown context provider ${context.uses}`); + } return undefined; } const instance: IContextProvider = new cls(context.with ?? {}); return instance; }) .filter((p) => !!p) as IContextProvider[]; + continueConfig.contextProviders.push(...DEFAULT_CONTEXT_PROVIDERS); // Embeddings Provider const embedConfig = config.models?.find((model) => @@ -283,16 +304,20 @@ export async function loadContinueConfigFromYaml( uniqueId: string, writeLog: (log: string) => Promise, workOsAccessToken: string | undefined, - overrideConfigYaml: string | undefined, + overrideConfigYaml: ClientConfigYaml | undefined, + platformConfigMetadata: PlatformConfigMetadata | undefined, + controlPlaneClient: ControlPlaneClient, ): Promise> { const configYamlPath = getConfigYamlPath(ideType); - const rawYaml = fs.readFileSync(configYamlPath, "utf-8"); + const rawYaml = + overrideConfigYaml === undefined + ? fs.readFileSync(configYamlPath, "utf-8") + : ""; - const configYamlResult = await loadConfigYaml( + const configYamlResult = loadConfigYaml( workspaceConfigs, - ideSettings, - ideType, - overrideConfigYaml ?? rawYaml, + rawYaml, + overrideConfigYaml, ); if (!configYamlResult.config || configYamlResult.configLoadInterrupted) { @@ -303,13 +328,24 @@ export async function loadContinueConfigFromYaml( }; } - const continueConfig = await configYamlToContinueConfig( + const configYaml = await resolveSecretsOnClient( configYamlResult.config, + ide.readSecrets.bind(ide), + async (secretNames: string[]) => { + const secretValues = await controlPlaneClient.syncSecrets(secretNames); + await ide.writeSecrets(secretValues); + return secretValues; + }, + ); + + const continueConfig = await configYamlToContinueConfig( + configYaml, ide, ideSettings, uniqueId, writeLog, workOsAccessToken, + platformConfigMetadata, ); const systemPromptDotFile = await getSystemPromptDotFile(ide); diff --git a/core/config/yaml/models.ts b/core/config/yaml/models.ts index d6eb6d3e0..309e061d1 100644 --- a/core/config/yaml/models.ts +++ b/core/config/yaml/models.ts @@ -3,21 +3,59 @@ import { ModelConfig } from "@continuedev/config-yaml"; import { IDE, IdeSettings, LLMOptions } from "../.."; import { BaseLLM } from "../../llm"; import { LLMClasses } from "../../llm/llms"; +import ContinueProxy from "../../llm/llms/stubs/ContinueProxy"; +import { PlatformConfigMetadata } from "../profile/PlatformProfileLoader"; const AUTODETECT = "AUTODETECT"; +function useContinueProxy( + model: ModelConfig, + platformConfigMetadata: PlatformConfigMetadata | undefined, +): boolean { + return !!platformConfigMetadata && model.apiKeySecret !== undefined; +} + +function getModelClass( + model: ModelConfig, + platformConfigMetadata: PlatformConfigMetadata | undefined, +): (typeof LLMClasses)[number] | undefined { + if (useContinueProxy(model, platformConfigMetadata)) { + return ContinueProxy; + } + return LLMClasses.find((llm) => llm.providerName === model.provider); +} + +function getContinueProxyModelName( + ownerSlug: string, + packageSlug: string, + model: ModelConfig, +): string { + return `${ownerSlug}/${packageSlug}/${model.provider}/${model.model}`; +} + async function modelConfigToBaseLLM( model: ModelConfig, uniqueId: string, ideSettings: IdeSettings, writeLog: (log: string) => Promise, + platformConfigMetadata: PlatformConfigMetadata | undefined, + systemMessage: string | undefined, ): Promise { - const cls = LLMClasses.find((llm) => llm.providerName === model.provider); + const cls = getModelClass(model, platformConfigMetadata); if (!cls) { return undefined; } + const usingContinueProxy = useContinueProxy(model, platformConfigMetadata); + const modelName = usingContinueProxy + ? getContinueProxyModelName( + platformConfigMetadata!.ownerSlug, + platformConfigMetadata!.packageSlug, + model, + ) + : model.model; + let options: LLMOptions = { ...model, completionOptions: { @@ -30,6 +68,8 @@ async function modelConfigToBaseLLM( writeLog, uniqueId, title: model.name, + model: modelName, + systemMessage, }; const llm = new cls(options); @@ -43,6 +83,8 @@ async function autodetectModels( uniqueId: string, ideSettings: IdeSettings, writeLog: (log: string) => Promise, + platformConfigMetadata: PlatformConfigMetadata | undefined, + systemMessage: string | undefined, ): Promise { try { const modelNames = await llm.listModels(); @@ -62,6 +104,8 @@ async function autodetectModels( uniqueId, ideSettings, writeLog, + platformConfigMetadata, + systemMessage, ); }), ); @@ -78,12 +122,16 @@ export async function llmsFromModelConfig( uniqueId: string, ideSettings: IdeSettings, writeLog: (log: string) => Promise, + platformConfigMetadata: PlatformConfigMetadata | undefined, + systemMessage: string | undefined, ): Promise { const baseLlm = await modelConfigToBaseLLM( model, uniqueId, ideSettings, writeLog, + platformConfigMetadata, + systemMessage, ); if (!baseLlm) { return []; @@ -97,6 +145,8 @@ export async function llmsFromModelConfig( uniqueId, ideSettings, writeLog, + platformConfigMetadata, + systemMessage, ); return models; } else { diff --git a/core/context/mcp/index.ts b/core/context/mcp/index.ts index 26be2f471..304c2a8c4 100644 --- a/core/context/mcp/index.ts +++ b/core/context/mcp/index.ts @@ -4,9 +4,9 @@ import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js" import { WebSocketClientTransport } from "@modelcontextprotocol/sdk/client/websocket.js"; import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js"; +import { ConfigValidationError } from "@continuedev/config-yaml"; 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"; diff --git a/core/context/providers/RepoMapContextProvider.ts b/core/context/providers/RepoMapContextProvider.ts index 0805d341e..deabfe590 100644 --- a/core/context/providers/RepoMapContextProvider.ts +++ b/core/context/providers/RepoMapContextProvider.ts @@ -41,7 +41,7 @@ class RepoMapContextProvider extends BaseContextProvider { // Doesn't ALWAYS depend on indexing, so not setting dependsOnIndexing = true, just checking for it includeSignatures: extras.config.disableIndexing ? false - : (this.options?.includeSignatures ?? false), + : (this.options?.includeSignatures ?? true), }), }, ]; diff --git a/core/control-plane/auth/index.ts b/core/control-plane/auth/index.ts index ecb6221c7..c1a6f881d 100644 --- a/core/control-plane/auth/index.ts +++ b/core/control-plane/auth/index.ts @@ -1,5 +1,7 @@ import { v4 as uuidv4 } from "uuid"; +import { controlPlaneEnv } from "../env"; + const CLIENT_ID = "client_01J0FW6XN8N2XJAECF7NE0Y65J"; // const CLIENT_ID = "client_01J0FW6XCPMJMQ3CG51RB4HBZQ"; // Staging @@ -8,7 +10,7 @@ export async function getAuthUrlForTokenPage(): Promise { const params = { response_type: "code", client_id: CLIENT_ID, - redirect_uri: "https://app.continue.dev/tokens/callback", + redirect_uri: `${controlPlaneEnv.APP_URL}tokens/callback`, // redirect_uri: "http://localhost:3000/tokens/callback", state: uuidv4(), provider: "authkit", diff --git a/core/control-plane/client.ts b/core/control-plane/client.ts index b84e24570..3a29b3fee 100644 --- a/core/control-plane/client.ts +++ b/core/control-plane/client.ts @@ -1,8 +1,10 @@ import { ConfigJson } from "@continuedev/config-types"; +import { ClientConfigYaml } from "@continuedev/config-yaml/dist/schemas/index.js"; import fetch, { RequestInit, Response } from "node-fetch"; import { ModelDescription } from "../index.js"; +import { ConfigResult } from "@continuedev/config-yaml"; import { controlPlaneEnv } from "./env.js"; export interface ControlPlaneSessionInfo { @@ -85,6 +87,29 @@ export class ControlPlaneClient { } } + public async listAssistants(): Promise< + { + configResult: ConfigResult; + ownerSlug: string; + packageSlug: string; + iconUrl: string; + }[] + > { + const userId = await this.userId; + if (!userId) { + return []; + } + + try { + const resp = await this.request("ide/list-assistants", { + method: "GET", + }); + return (await resp.json()) as any; + } catch (e) { + return []; + } + } + async getSettingsForWorkspace(workspaceId: string): Promise { const userId = await this.userId; if (!userId) { @@ -96,4 +121,21 @@ export class ControlPlaneClient { }); return ((await resp.json()) as any).settings; } + + async syncSecrets(secretNames: string[]): Promise> { + const userId = await this.userId; + if (!userId) { + throw new Error("No user id"); + } + + try { + const resp = await this.request("ide/sync-secrets", { + method: "POST", + body: JSON.stringify({ secretNames }), + }); + return (await resp.json()) as any; + } catch (e) { + return {}; + } + } } diff --git a/core/control-plane/env.ts b/core/control-plane/env.ts index 4556ce90f..16adf0990 100644 --- a/core/control-plane/env.ts +++ b/core/control-plane/env.ts @@ -1,3 +1,6 @@ +import { readUsePlatform } from "../util/paths"; +import { usePlatform } from "./flags"; + interface ControlPlaneEnv { DEFAULT_CONTROL_PLANE_PROXY_URL: string; CONTROL_PLANE_URL: string; @@ -21,7 +24,7 @@ const PRODUCTION_ENV: ControlPlaneEnv = { "https://control-plane-api-service-i3dqylpbqa-uc.a.run.app/", AUTH_TYPE: WORKOS_ENV_ID_PRODUCTION, WORKOS_CLIENT_ID: WORKOS_CLIENT_ID_PRODUCTION, - APP_URL: "https://app.continue.dev", + APP_URL: "https://app.continue.dev/", }; const STAGING_ENV: ControlPlaneEnv = { @@ -31,7 +34,15 @@ const STAGING_ENV: ControlPlaneEnv = { "https://control-plane-api-service-537175798139.us-central1.run.app/", AUTH_TYPE: WORKOS_CLIENT_ID_STAGING, WORKOS_CLIENT_ID: WORKOS_CLIENT_ID_STAGING, - APP_URL: "https://app-preview.continue.dev", + APP_URL: "https://app-preview.continue.dev/", +}; + +const TEST_ENV: ControlPlaneEnv = { + DEFAULT_CONTROL_PLANE_PROXY_URL: "https://api-test.continue.dev/", + CONTROL_PLANE_URL: "https://api-test.continue.dev/", + AUTH_TYPE: WORKOS_ENV_ID_STAGING, + WORKOS_CLIENT_ID: WORKOS_CLIENT_ID_STAGING, + APP_URL: "https://app-test.continue.dev/", }; const LOCAL_ENV: ControlPlaneEnv = { @@ -39,12 +50,20 @@ const LOCAL_ENV: ControlPlaneEnv = { CONTROL_PLANE_URL: "http://localhost:3001/", AUTH_TYPE: WORKOS_ENV_ID_STAGING, WORKOS_CLIENT_ID: WORKOS_CLIENT_ID_STAGING, - APP_URL: "http://localhost:3000", + APP_URL: "http://localhost:3000/", }; -export const controlPlaneEnv = - process.env.CONTROL_PLANE_ENV === "local" +function getControlPlaneEnv(): ControlPlaneEnv { + const usePlatformFileEnv = readUsePlatform(); + const env = usePlatformFileEnv || process.env.CONTROL_PLANE_ENV; + + return env === "local" ? LOCAL_ENV - : process.env.CONTROL_PLANE_ENV === "staging" + : env === "staging" ? STAGING_ENV - : PRODUCTION_ENV; + : env === "test" || usePlatform() + ? TEST_ENV + : PRODUCTION_ENV; +} + +export const controlPlaneEnv = getControlPlaneEnv(); diff --git a/core/control-plane/flags.ts b/core/control-plane/flags.ts new file mode 100644 index 000000000..7b8ff6799 --- /dev/null +++ b/core/control-plane/flags.ts @@ -0,0 +1,13 @@ +import { readUsePlatform, usePlatformPathExists } from "../util/paths"; + +export function usePlatform(): boolean { + return usePlatformPathExists(); +} + +export function getEnvFromUsePlatformFile(): string | undefined { + const contents = readUsePlatform(); + if (contents && contents.trim().length > 0) { + return contents.trim(); + } + return undefined; +} diff --git a/core/core.ts b/core/core.ts index 454af68ee..c74f2e539 100644 --- a/core/core.ts +++ b/core/core.ts @@ -52,6 +52,7 @@ import { type IndexingProgressUpdate, } from "."; +import { usePlatform } from "./control-plane/flags"; import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; import type { IMessenger, Message } from "./protocol/messenger"; @@ -110,6 +111,7 @@ export class Core { const ideSettingsPromise = messenger.request("getIdeSettings", undefined); const sessionInfoPromise = messenger.request("getControlPlaneSessionInfo", { silent: true, + useOnboarding: usePlatform(), }); this.controlPlaneClient = new ControlPlaneClient(sessionInfoPromise); @@ -131,7 +133,7 @@ export class Core { const serializedResult = await this.configHandler.getSerializedConfig(); this.messenger.send("configUpdate", { result: serializedResult, - profileId: this.configHandler.currentProfile.profileId, + profileId: this.configHandler.currentProfile.profileDescription.id, }); }); @@ -385,7 +387,7 @@ export class Core { on("config/getSerializedProfileInfo", async (msg) => { return { result: await this.configHandler.getSerializedConfig(), - profileId: this.configHandler.currentProfile.profileId, + profileId: this.configHandler.currentProfile.profileDescription.id, }; }); diff --git a/core/index.d.ts b/core/index.d.ts index cd6510f19..518e301d9 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -460,6 +460,7 @@ export interface LLMOptions { writeLog?: (str: string) => Promise; llmRequestHook?: (model: string, prompt: string) => any; apiKey?: string; + apiKeySecret?: string; aiGatewaySlug?: string; apiBase?: string; cacheBehavior?: CacheBehavior; @@ -683,6 +684,11 @@ export interface IDE { getGitHubAuthToken(args: GetGhTokenArgs): Promise; + // Secret Storage + readSecrets(keys: string[]): Promise>; + + writeSecrets(secrets: { [key: string]: string }): Promise; + // LSP gotoDefinition(location: Location): Promise; @@ -854,6 +860,13 @@ export interface Tool { uri?: string; } +interface ToolChoice { + type: "function"; + function: { + name: string; + }; +} + export interface BaseCompletionOptions { temperature?: number; topP?: number; @@ -871,6 +884,7 @@ export interface BaseCompletionOptions { stream?: boolean; prediction?: Prediction; tools?: Tool[]; + toolChoice?: ToolChoice; } export interface ModelCapability { @@ -882,6 +896,7 @@ export interface ModelDescription { provider: string; model: string; apiKey?: string; + apiKeySecret?: string; apiBase?: string; contextLength?: number; maxStopWords?: number; @@ -1198,6 +1213,7 @@ export interface BrowserSerializedContinueConfig { analytics?: AnalyticsConfig; docs?: SiteIndexingConfig[]; tools: Tool[]; + usePlatform: boolean; } // DOCS SUGGESTIONS AND PACKAGE INFO @@ -1235,9 +1251,9 @@ export type PackageDocsResult = { } & ( | { error: string; details?: never } | { details: PackageDetailsSuccess; error?: never } - ); +); export interface TerminalOptions { - reuseTerminal?: boolean, - terminalName?: string, + reuseTerminal?: boolean; + terminalName?: string; } diff --git a/core/indexing/CodebaseIndexer.test.ts b/core/indexing/CodebaseIndexer.test.ts index 211bc3732..517298597 100644 --- a/core/indexing/CodebaseIndexer.test.ts +++ b/core/indexing/CodebaseIndexer.test.ts @@ -14,12 +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 { localPathToUri } from "../util/pathToUri.js"; jest.useFakeTimers(); @@ -159,7 +159,7 @@ describe("CodebaseIndexer", () => { test("should have created index folder with all necessary files", async () => { const exists = await testIde.fileExists( - pathToFileURL(getIndexSqlitePath()).toString(), + localPathToUri(getIndexSqlitePath()), ); expect(exists).toBe(true); }); diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index 105d24b9e..cab6c35da 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -25,7 +25,7 @@ import { } from "../../util/paths"; import { Telemetry } from "../../util/posthog"; -import { ConfigResult } from "../../config/load"; +import { ConfigResult } from "@continuedev/config-yaml"; import { Article, chunkArticle, pageToArticle } from "./article"; import DocsCrawler from "./DocsCrawler"; import { runLanceMigrations, runSqliteMigrations } from "./migrations"; diff --git a/core/llm/index.ts b/core/llm/index.ts index 0b48d867c..5ecfa33ff 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -25,6 +25,7 @@ import { logDevData } from "../util/devdata.js"; import { DevDataSqliteDb } from "../util/devdataSqlite.js"; import mergeJson from "../util/merge.js"; import { renderChatMessage } from "../util/messageContent.js"; +import { isOllamaInstalled } from "../util/ollamaHelper.js"; import { Telemetry } from "../util/posthog.js"; import { withExponentialBackoff } from "../util/withExponentialBackoff.js"; @@ -55,7 +56,6 @@ import { toCompleteBody, toFimBody, } from "./openaiTypeConverters.js"; -import { isOllamaInstalled } from "../util/ollamaHelper.js"; export abstract class BaseLLM implements ILLM { static providerName: string; @@ -117,6 +117,7 @@ export abstract class BaseLLM implements ILLM { writeLog?: (str: string) => Promise; llmRequestHook?: (model: string, prompt: string) => any; apiKey?: string; + apiKeySecret?: string; apiBase?: string; cacheBehavior?: CacheBehavior; capabilities?: ModelCapability; @@ -194,6 +195,7 @@ export abstract class BaseLLM implements ILLM { this.writeLog = options.writeLog; this.llmRequestHook = options.llmRequestHook; this.apiKey = options.apiKey; + this.apiKeySecret = options.apiKeySecret; this.aiGatewaySlug = options.aiGatewaySlug; this.apiBase = options.apiBase; this.cacheBehavior = options.cacheBehavior; @@ -415,10 +417,9 @@ export abstract class BaseLLM implements ILLM { e.code === "ECONNREFUSED" && e.message.includes("http://127.0.0.1:11434") ) { - const message = (await isOllamaInstalled()) ? - "Unable to connect to local Ollama instance. Ollama may not be running." : - "Unable to connect to local Ollama instance. Ollama may not be installed or may not running." - ; + const message = (await isOllamaInstalled()) + ? "Unable to connect to local Ollama instance. Ollama may not be running." + : "Unable to connect to local Ollama instance. Ollama may not be installed or may not running."; throw new Error(message); } } @@ -693,13 +694,28 @@ export abstract class BaseLLM implements ILLM { return body; } + private _modifyCompletionOptions( + completionOptions: CompletionOptions, + ): CompletionOptions { + // As of 01/14/25 streaming is currently not available with o1 + // See these threads: + // - https://github.com/continuedev/continue/issues/3698 + // - https://community.openai.com/t/streaming-support-for-o1-o1-2024-12-17-resulting-in-400-unsupported-value/1085043 + if (completionOptions.model === "o1") { + completionOptions.stream = false; + } + + return completionOptions; + } + async *streamChat( _messages: ChatMessage[], signal: AbortSignal, options: LLMFullCompletionOptions = {}, ): AsyncGenerator { - const { completionOptions, log, raw } = - this._parseCompletionOptions(options); + let { completionOptions, log } = this._parseCompletionOptions(options); + + completionOptions = this._modifyCompletionOptions(completionOptions); const messages = this._compileChatMessages(completionOptions, _messages); diff --git a/core/llm/llm.test.ts b/core/llm/llm.test.ts index cb2218d1d..09777dae0 100644 --- a/core/llm/llm.test.ts +++ b/core/llm/llm.test.ts @@ -1,13 +1,17 @@ import * as dotenv from "dotenv"; -import { CompletionOptions } from ".."; +import { AssistantChatMessage, CompletionOptions } from ".."; + import { BaseLLM } from "."; +import Anthropic from "./llms/Anthropic"; +import Gemini from "./llms/Gemini"; +import Mistral from "./llms/Mistral"; import OpenAI from "./llms/OpenAI"; dotenv.config(); const COMPLETION_OPTIONS: Partial = { - temperature: 0.5, + // temperature: 0.5, topP: 1, topK: 40, presencePenalty: 0, @@ -16,12 +20,23 @@ const COMPLETION_OPTIONS: Partial = { // maxTokens: 5, }; -function testLLM(llm: BaseLLM) { +function testLLM( + llm: BaseLLM, + { + skip, + testFim, + testToolCall, + }: { skip?: boolean; testFim?: boolean; testToolCall?: boolean }, +) { + if (skip) { + return; + } + beforeAll(() => { llm.completionOptions = { ...llm.completionOptions, ...COMPLETION_OPTIONS }; }); - describe(llm.providerName, () => { + describe(llm.providerName + "/" + llm.model, () => { test("Stream Chat works", async () => { let total = ""; for await (const chunk of llm.streamChat( @@ -54,62 +69,119 @@ function testLLM(llm: BaseLLM) { expect(completion.length).toBeGreaterThan(0); return; }); + + if (testFim) { + test("FIM works", async () => { + let total = ""; + for await (const chunk of llm.streamFim( + "Hi", + "name is ChatGPT.", + new AbortController().signal, + )) { + total += chunk; + } + + expect(total.length).toBeGreaterThan(0); + return; + }); + } + + if (testToolCall) { + test("Tool Call works", async () => { + let args = ""; + let isFirstChunk = true; + for await (const chunk of llm.streamChat( + [{ role: "user", content: "Hi, my name is Nate." }], + new AbortController().signal, + { + tools: [ + { + displayTitle: "Say Hello", + function: { + name: "say_hello", + description: "Say Hello", + parameters: { + type: "object", + properties: { + name: { + type: "string", + description: "The name of the person to greet", + }, + }, + }, + }, + type: "function", + wouldLikeTo: "Say hello", + readonly: true, + }, + ], + toolChoice: { + type: "function", + function: { + name: "say_hello", + }, + }, + }, + )) { + const typedChunk = chunk as AssistantChatMessage; + if (!typedChunk.toolCalls) { + continue; + } + const toolCall = typedChunk.toolCalls[0]; + args += toolCall.function?.arguments ?? ""; + + expect(chunk.role).toBe("assistant"); + expect(chunk.content).toBe(""); + expect(typedChunk.toolCalls).toHaveLength(1); + + if (isFirstChunk) { + isFirstChunk = false; + expect(toolCall.id).toBeDefined(); + expect(toolCall.function!.name).toBe("say_hello"); + } + } + + const parsedArgs = JSON.parse(args); + expect(parsedArgs.name).toBe("Nate"); + }); + } }); } -describe.skip("LLM", () => { - // testLLM( - // new FreeTrial({ - // model: "gpt-3.5-turbo", - // }), - // ); - // testLLM( - // new Anthropic({ - // model: "claude-2", - // apiKey: process.env.ANTHROPIC_API_KEY, - // }), - // ); +describe("LLM", () => { testLLM( - new OpenAI({ apiKey: process.env.OPENAI_API_KEY, model: "gpt-3.5-turbo" }), + new Anthropic({ + model: "claude-3-5-sonnet-latest", + apiKey: process.env.ANTHROPIC_API_KEY, + }), + { + skip: false, + testToolCall: true, + }, + ); + testLLM(new OpenAI({ apiKey: process.env.OPENAI_API_KEY, model: "gpt-4o" }), { + skip: false, + testToolCall: true, + }); + testLLM( + new OpenAI({ apiKey: process.env.OPENAI_API_KEY, model: "o1-preview" }), + { skip: false }, + ); + testLLM(new OpenAI({ apiKey: process.env.OPENAI_API_KEY, model: "o1" }), { + skip: false, + }); + testLLM( + new Gemini({ + model: "gemini-2.0-flash-exp", + apiKey: process.env.GEMINI_API_KEY, + }), + { skip: false }, + ); + testLLM( + new Mistral({ + apiKey: process.env.MISTRAL_API_KEY, + model: "codestral-latest", + }), + { testFim: true, skip: false }, ); - // TODO: Fix Replicate - // testLLM( - // new Replicate({ - // apiKey: process.env.REPLICATE_API_KEY, - // model: "codellama-7b", - // }) - // ); - // testLLM(new LMStudio({ model: "codellama-7b" })); - // testLLM(new Ollama({ model: "codellama-7b" })); - // testLLM( - // new Together({ - // apiKey: process.env.TOGETHER_API_KEY, - // model: "codellama-7b", - // }) - // ); - // testLLM(new LlamaCpp({ model: "deepseek-7b" })); - // testLLM(new Llamafile({ model: "mistral-7b" })); - // TODO: Test these - // testLLM(new TextGenWebUI({ model: "codellama-7b" })); - // testLLM(new HuggingFaceTGI({ model: "codellama-7b" })); - // testLLM(new HuggingFaceInferenceAPI({ model: "codellama-7b" })); - // testLLM( - // new Gemini({ - // model: "gemini-pro", - // // model: "chat-bison-001", - // apiKey: process.env.GOOGLE_PALM_API_KEY, - // }) - // ); - // testLLM( - // new Gemini({ model: "gemini-pro", apiKey: process.env.GOOGLE_PALM_API_KEY }) - // ); - // testLLM( - // new Mistral({ apiKey: process.env.MISTRAL_API_KEY, model: "mistral-small" }) - // ); - // testLLM( - // new Flowise({ apiKey: process.env.FLOWISE_API_KEY, model: "gpt-3.5-turbo" }) - // ); - // testLLM( - // new Nebius({ apiKey: process.env.NEBIUS_API_KEY, model: "llama3.1-8b" }) - // ); }); diff --git a/core/llm/llms/Anthropic.ts b/core/llm/llms/Anthropic.ts index 234c16860..df527d579 100644 --- a/core/llm/llms/Anthropic.ts +++ b/core/llm/llms/Anthropic.ts @@ -30,6 +30,12 @@ class Anthropic extends BaseLLM { description: tool.function.description, input_schema: tool.function.parameters, })), + tool_choice: options.toolChoice + ? { + type: "tool", + name: options.toolChoice.function.name, + } + : undefined, }; return finalOptions; diff --git a/core/llm/llms/Mock.ts b/core/llm/llms/Mock.ts index 236af9824..03e268074 100644 --- a/core/llm/llms/Mock.ts +++ b/core/llm/llms/Mock.ts @@ -1,7 +1,7 @@ import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js"; import { BaseLLM } from "../index.js"; -type MockMessage = ChatMessage | "REPEAT_LAST_MSG"; +type MockMessage = ChatMessage | "REPEAT_LAST_MSG" | "REPEAT_SYSTEM_MSG"; class MockLLM extends BaseLLM { public completion: string = "Test Completion"; @@ -42,6 +42,13 @@ class MockLLM extends BaseLLM { content: messages[messages.length - 1].content, }; break; + case "REPEAT_SYSTEM_MSG": + yield { + role: "assistant", + content: + messages.find((m) => m.role === "system")?.content || "", + }; + break; default: yield message; } diff --git a/core/llm/llms/OpenAI.ts b/core/llm/llms/OpenAI.ts index 1cf1bc44e..41b3c755b 100644 --- a/core/llm/llms/OpenAI.ts +++ b/core/llm/llms/OpenAI.ts @@ -113,6 +113,10 @@ class OpenAI extends BaseLLM { }; } + protected extraBodyProperties(): Record { + return {}; + } + protected getMaxStopWords(): number { const url = new URL(this.apiBase!); @@ -150,6 +154,10 @@ class OpenAI extends BaseLLM { finalOptions.messages = formatMessageForO1(finalOptions.messages); } + if (options.model === "o1") { + finalOptions.stream = false; + } + if (options.prediction && this.supportsPrediction(options.model)) { if (finalOptions.presence_penalty) { // prediction doesn't support > 0 @@ -241,6 +249,11 @@ class OpenAI extends BaseLLM { body.messages = formatMessageForO1(body.messages); } + if (body.model === "o1") { + // o1 doesn't support streaming + body.stream = false; + } + if (body.prediction && this.supportsPrediction(body.model)) { if (body.presence_penalty) { // prediction doesn't support > 0 @@ -278,6 +291,7 @@ class OpenAI extends BaseLLM { body: JSON.stringify({ ...args, stream: true, + ...this.extraBodyProperties(), }), signal, }); @@ -319,7 +333,10 @@ class OpenAI extends BaseLLM { const response = await this.fetch(this._getEndpoint("chat/completions"), { method: "POST", headers: this._getHeaders(), - body: JSON.stringify(body), + body: JSON.stringify({ + ...body, + ...this.extraBodyProperties(), + }), signal, }); @@ -358,6 +375,7 @@ class OpenAI extends BaseLLM { presence_penalty: options.presencePenalty, stop: options.stop, stream: true, + ...this.extraBodyProperties(), }), headers: { "Content-Type": "application/json", @@ -404,6 +422,7 @@ class OpenAI extends BaseLLM { body: JSON.stringify({ input: chunks, model: this.model, + ...this.extraBodyProperties(), }), headers: { Authorization: `Bearer ${this.apiKey}`, diff --git a/core/llm/llms/stubs/ContinueProxy.ts b/core/llm/llms/stubs/ContinueProxy.ts index c037ebd61..59d05b115 100644 --- a/core/llm/llms/stubs/ContinueProxy.ts +++ b/core/llm/llms/stubs/ContinueProxy.ts @@ -10,11 +10,33 @@ class ContinueProxy extends OpenAI { this.apiBase = new URL("openai/v1/", value.controlPlaneProxyUrl).toString(); } + // The apiKey and apiBase are set to the values for the proxy, + // but we need to keep track of the actual values that the proxy will use + // to call whatever LLM API is chosen + private actualApiBase?: string; + private actualApiKey?: string; + + constructor(options: LLMOptions) { + super(options); + this.actualApiBase = options.apiBase; + this.actualApiKey = options.apiKey; + } + static providerName = "continue-proxy"; static defaultOptions: Partial = { useLegacyCompletionsEndpoint: false, }; + protected extraBodyProperties(): Record { + return { + continueProperties: { + apiKey: this.actualApiKey, + apiBase: this.actualApiBase, + apiKeySecret: this.apiKeySecret, + }, + }; + } + protected _getHeaders() { const headers: any = super._getHeaders(); headers["x-continue-unique-id"] = Telemetry.uniqueId; diff --git a/core/llm/openaiTypeConverters.ts b/core/llm/openaiTypeConverters.ts index 057219beb..839efda4e 100644 --- a/core/llm/openaiTypeConverters.ts +++ b/core/llm/openaiTypeConverters.ts @@ -80,6 +80,7 @@ export function toChatBody( stream: options.stream ?? true, stop: options.stop, prediction: options.prediction, + tool_choice: options.toolChoice, }; if (options.tools?.length) { diff --git a/core/package-lock.json b/core/package-lock.json index 18a318596..350607e4d 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -13,7 +13,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.621.0", "@aws-sdk/credential-providers": "^3.620.1", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.0", + "@continuedev/config-yaml": "^1.0.11", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.2", "@continuedev/openai-adapters": "^1.0.10", @@ -3030,18 +3030,19 @@ } }, "node_modules/@continuedev/config-types": { - "version": "1.0.13", - "resolved": "https://registry.npmjs.org/@continuedev/config-types/-/config-types-1.0.13.tgz", - "integrity": "sha512-5Qmy2x58uhW1GYknypFT/7iwxEJSbt8gMgfQReV7d6xjbJ09ISOTki3hIfCilKrTCo0gIY6pzKEfCoQkUTEi6Q==", + "version": "1.0.14", + "resolved": "https://registry.npmjs.org/@continuedev/config-types/-/config-types-1.0.14.tgz", + "integrity": "sha512-PVHyHPyRXd2QsaNgnCpiKYU3uHFTlyuQSkqE8OwrBmQqO6/TXUVIr/2EGtyIZGrml4Y+rGMSH40WU4/0t4SGpQ==", "dependencies": { "zod": "^3.23.8" } }, "node_modules/@continuedev/config-yaml": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.0.tgz", - "integrity": "sha512-NwagzzpnPLbMC3delzFSjWiFv5fp8ReFjdMQF0ko0Xg+U0Myja90k/J7JWGegF/SZMABxc/OJchElJFr58TwGA==", + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.11.tgz", + "integrity": "sha512-E3RBQfNEPBGBmlnAbCXgeAasDzTjo4ON/HH0hr5g292i+WdAN3i/omjQ6Iusx00L1Fz7klZGJePZ3GVQKOGEUg==", "dependencies": { + "@continuedev/config-types": "^1.0.14", "yaml": "^2.6.1", "zod": "^3.23.8" } diff --git a/core/package.json b/core/package.json index e865e0ddb..0e107f991 100644 --- a/core/package.json +++ b/core/package.json @@ -46,7 +46,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.621.0", "@aws-sdk/credential-providers": "^3.620.1", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.0", + "@continuedev/config-yaml": "^1.0.11", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.2", "@continuedev/openai-adapters": "^1.0.10", diff --git a/core/promptFiles/v2/getPromptFiles.ts b/core/promptFiles/v2/getPromptFiles.ts index 2998b5f8f..d991d140a 100644 --- a/core/promptFiles/v2/getPromptFiles.ts +++ b/core/promptFiles/v2/getPromptFiles.ts @@ -16,11 +16,11 @@ export async function getPromptFilesFromDir( return []; } - const paths = await walkDir(dir, ide, { ignoreFiles: [] }); - const promptFilePaths = paths.filter((p) => p.endsWith(".prompt")); - const results = promptFilePaths.map(async (path) => { - const content = await ide.readFile(path); // make a try catch - return { path, content }; + const uris = await walkDir(dir, ide, { ignoreFiles: [] }); + const promptFilePaths = uris.filter((p) => p.endsWith(".prompt")); + const results = promptFilePaths.map(async (uri) => { + const content = await ide.readFile(uri); // make a try catch + return { path: uri, content }; }); return Promise.all(results); } catch (e) { diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 5fa84456a..b48b11398 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -1,7 +1,4 @@ -import { AutocompleteInput } from "../autocomplete/util/types"; -import { ProfileDescription } from "../config/ConfigHandler"; -import { ConfigResult } from "../config/load"; - +import { ConfigResult } from "@continuedev/config-yaml"; import type { BrowserSerializedContinueConfig, ChatMessage, @@ -23,6 +20,8 @@ import type { SiteIndexingConfig, ToolCall, } from "../"; +import { AutocompleteInput } from "../autocomplete/util/types"; +import { ProfileDescription } from "../config/ConfigHandler"; export type OnboardingModes = | "Local" diff --git a/core/protocol/ide.ts b/core/protocol/ide.ts index 8c0d2557c..5b2a7ab1f 100644 --- a/core/protocol/ide.ts +++ b/core/protocol/ide.ts @@ -13,8 +13,8 @@ import type { Problem, Range, RangeInFile, + TerminalOptions, Thread, - TerminalOptions } from "../"; export interface GetGhTokenArgs { @@ -29,7 +29,7 @@ export type ToIdeFromWebviewOrCoreProtocol = { showVirtualFile: [{ name: string; content: string }, void]; openFile: [{ path: string }, void]; openUrl: [string, void]; - runCommand: [{ command: string, options?: TerminalOptions }, void]; + runCommand: [{ command: string; options?: TerminalOptions }, void]; getSearchResults: [{ query: string }, string]; subprocess: [{ command: string; cwd?: string }, [string, string]]; saveFile: [{ filepath: string }, void]; @@ -72,6 +72,8 @@ export type ToIdeFromWebviewOrCoreProtocol = { isTelemetryEnabled: [undefined, boolean]; getUniqueId: [undefined, string]; getTags: [string, IndexTag[]]; + readSecrets: [{ keys: string[] }, Record]; + writeSecrets: [{ secrets: Record }, void]; // end methods from IDE type getIdeSettings: [undefined, IdeSettings]; @@ -92,7 +94,7 @@ export type ToIdeFromWebviewOrCoreProtocol = { getGitHubAuthToken: [GetGhTokenArgs, string | undefined]; getControlPlaneSessionInfo: [ - { silent: boolean }, + { silent: boolean; useOnboarding: boolean }, ControlPlaneSessionInfo | undefined, ]; logoutOfControlPlane: [undefined, void]; diff --git a/core/protocol/messenger/messageIde.ts b/core/protocol/messenger/messageIde.ts index aaa567f39..4bb78e0ed 100644 --- a/core/protocol/messenger/messageIde.ts +++ b/core/protocol/messenger/messageIde.ts @@ -29,6 +29,14 @@ export class MessageIde implements IDE { ) => void, ) {} + async readSecrets(keys: string[]): Promise> { + return this.request("readSecrets", { keys }); + } + + async writeSecrets(secrets: { [key: string]: string }): Promise { + return this.request("writeSecrets", { secrets }); + } + fileExists(fileUri: string): Promise { return this.request("fileExists", { filepath: fileUri }); } @@ -152,7 +160,7 @@ export class MessageIde implements IDE { await this.request("openUrl", url); } - async runCommand(command: string, options?: TerminalOptions): Promise { + async runCommand(command: string, options?: TerminalOptions): Promise { await this.request("runCommand", { command, options }); } diff --git a/core/protocol/webview.ts b/core/protocol/webview.ts index 5e22faae6..822d9b532 100644 --- a/core/protocol/webview.ts +++ b/core/protocol/webview.ts @@ -1,11 +1,8 @@ -import { ConfigResult } from "../config/load.js"; -import { ConfigValidationError } from "../config/validation.js"; - +import { ConfigResult, ConfigValidationError } from "@continuedev/config-yaml"; import type { BrowserSerializedContinueConfig, ContextItemWithId, ContextProviderName, - ContextSubmenuItem, IndexingProgressUpdate, IndexingStatus, PackageDocsResult, diff --git a/core/util/filesystem.ts b/core/util/filesystem.ts index b4297f7bc..ccb550ec9 100644 --- a/core/util/filesystem.ts +++ b/core/util/filesystem.ts @@ -21,6 +21,13 @@ import { GetGhTokenArgs } from "../protocol/ide.js"; class FileSystemIde implements IDE { constructor(private readonly workspaceDir: string) {} + + async readSecrets(keys: string[]): Promise> { + return {}; + } + + async writeSecrets(secrets: { [key: string]: string }): Promise {} + showToast( type: ToastType, message: string, diff --git a/core/util/pathToUri.ts b/core/util/pathToUri.ts index 804b4fa99..67a249d74 100644 --- a/core/util/pathToUri.ts +++ b/core/util/pathToUri.ts @@ -4,7 +4,7 @@ import * as URI from "uri-js"; // CAN ONLY BE USED IN CORE -// Converts a local path to a file:// URI +// Converts a local path to a file:/// URI export function localPathToUri(path: string) { const url = pathToFileURL(path); return URI.normalize(url.toString()); diff --git a/core/util/paths.ts b/core/util/paths.ts index 8dd0cf84f..562d2e819 100644 --- a/core/util/paths.ts +++ b/core/util/paths.ts @@ -301,11 +301,18 @@ export function getPathToRemoteConfig(remoteConfigServerUrl: string): string { return dir; } -export function internalBetaPathExists(): boolean { - const sPath = path.join(getContinueGlobalPath(), ".internal_beta"); +export function usePlatformPathExists(): boolean { + const sPath = path.join(getContinueGlobalPath(), ".use_platform"); return fs.existsSync(sPath); } +export function readUsePlatform(): string | undefined { + const sPath = path.join(getContinueGlobalPath(), ".use_platform"); + if (fs.existsSync(sPath)) { + return fs.readFileSync(sPath, "utf8"); + } +} + export function getConfigJsonPathForRemote( remoteConfigServerUrl: string, ): string { diff --git a/docs/docs/customize/context-providers.md b/docs/docs/customize/context-providers.md index 23d8c2253..d49b38c93 100644 --- a/docs/docs/customize/context-providers.md +++ b/docs/docs/customize/context-providers.md @@ -261,9 +261,9 @@ Uses the top _n_ levels (defaulting to 3) of the call stack for that thread. ### `@Repository Map` -Reference the outline of your codebase. +Reference the outline of your codebase. By default, signatures are included along with file in the repo map. -`includeSignatures` params can be used to include signatures for all files in the repo. Use with caution as will increase context size significantly. `includeSignatures` will not work if indexing is disabled. +`includeSignatures` params can be set to false to exclude signatures. This could be necessary for large codebases and/or to reduce context size significantly. Signatures will not be included if indexing is disabled. ```json title="config.json" { @@ -271,7 +271,7 @@ Reference the outline of your codebase. { "name": "repo-map", "params": { - "includeSignatures": false + "includeSignatures": false // default true } } ] diff --git a/docs/docs/customize/model-providers/more/vllm.md b/docs/docs/customize/model-providers/more/vllm.md index d54baeb88..fe6932cc5 100644 --- a/docs/docs/customize/model-providers/more/vllm.md +++ b/docs/docs/customize/model-providers/more/vllm.md @@ -15,7 +15,7 @@ We recommend configuring **Llama3.1 8B** as your chat model. { "title": "Llama3.1 8B Instruct", "provider": "vllm", - "model": "meta-llama/Meta-Llama-3.1-8B-Instruct" + "model": "meta-llama/Meta-Llama-3.1-8B-Instruct", "apiBase": "http:///v1" } ] diff --git a/docs/docs/customize/model-providers/top-level/ollama.md b/docs/docs/customize/model-providers/top-level/ollama.md index d2a4749c0..611c3dad8 100644 --- a/docs/docs/customize/model-providers/top-level/ollama.md +++ b/docs/docs/customize/model-providers/top-level/ollama.md @@ -64,7 +64,7 @@ To configure a remote instance of Ollama, add the `"apiBase"` property to your m { "title": "Llama3.1 8B", "provider": "ollama", - "model": "llama3.1:8b" + "model": "llama3.1:8b", "apiBase": "http://:11434" } ] diff --git a/docs/docs/yaml-migration.md b/docs/docs/yaml-migration.md index 1e43ac738..ad62efaa7 100644 --- a/docs/docs/yaml-migration.md +++ b/docs/docs/yaml-migration.md @@ -14,7 +14,7 @@ See also - [JSON Continue Config Reference](/reference) - [YAML Continue Config Reference](/yaml-reference) -### 1. Create YAML file +## Create YAML file Create a `config.yaml` file in your Continue Global Directory (`~/.continue` on Mac, `%USERPROFILE%\.continue`) alongside your current `config.json` file. If a `config.yaml` file is present, it will be loaded instead of `config.json`. @@ -25,14 +25,14 @@ name: my-configuration version: 0.0.1 ``` -### 2. Map Models +### Models Add all model configurations in `config.json`, including models in `models`, `tabAutocompleteModel`, `embeddingsProvider`, and `reranker`, to the `models` section of your new YAML config file. A new `roles` YAML field specifies which roles a model can be used for, with possible values `chat`, `autocomplete`, `embed`, `rerank`, `edit`, `apply`, `summarize`. -- `models` in config should have `roles: chat` -- `tabAutocompleteModel`(s) in config should have `roles: autocomplete` -- `embeddingsProvider` in config should have `roles: embed` -- `reranker` in config should have `roles: rerank` +- `models` in config should have `roles: [chat]` +- `tabAutocompleteModel`(s) in config should have `roles: [autocomplete]` +- `embeddingsProvider` in config should have `roles: [embed]` +- `reranker` in config should have `roles: [rerank]` - `experimental.modelRoles` is replaced by simply adding roles to the model - `inlineEdit` -> e.g. `roles: [chat, edit]` - `applyCodeBlock` -> e.g. `roles: [chat, apply]` @@ -103,46 +103,56 @@ models: - name: GPT-4 provider: openai model: gpt-4 + apiKey: defaultCompletionOptions: temperature: 0.5 - maxTokens: 2000' - roles: [chat, edit] - apiKey: + maxTokens: 2000 + roles: + - chat + - edit + - name: My Voyage Reranker provider: voyage - roles: rerank apiKey: + roles: + - rerank + - name: My Starcoder provider: ollama model: starcoder2:3b - roles: autocomplete + roles: + - autocomplete + - name: My Ada Embedder provider: openai - roles: embed apiKey: + roles: + - embed + - name: Ollama Autodetect provider: ollama model: AUTODETECT + - name: My Open AI Compatible Model - Apply provider: openai - apiBase: http://3.3.3.3/v1 model: my-openai-compatible-model + apiBase: http://3.3.3.3/v1 requestOptions: headers: X-Auth-Token: - roles: [chat, apply] + roles: + - chat + - apply ``` Note that the `repoMapFileSelection` experimental model role has been deprecated. -### 3. Map Context Providers +### Context Providers -The JSON `contextProviders` and `docs` fields are replaced by the YAML `context` array. +The JSON `contextProviders` field is replaced by the YAML `context` array. - JSON `name` maps to `uses` - JSON `params` map to `with` -- Use multiple `docs` entries rather than the array of docs in the JSON format - **Before** @@ -150,10 +160,7 @@ The JSON `contextProviders` and `docs` fields are replaced by the YAML `context` { "contextProviders": [ { - "name": "docs", - "params": { - "startUrl": "https://docs.continue.dev/intro" - } + "name": "docs" }, { "name": "codebase", @@ -166,7 +173,86 @@ The JSON `contextProviders` and `docs` fields are replaced by the YAML `context` "name": "diff", "params": {} } - ], + ] +} +``` + +**After** + +```yaml title="config.yaml" +context: + - uses: docs + + - uses: codebase + with: + nRetrieve: 30 + nFinal: 3 + + - uses: diff +``` + +### System Message + +The `systemMessage` property has been replaced with a `rules` property that takes an array of strings. + +**Before** + +```json title="config.json" +{ + "systemMessage": "Always give concise responses" +} +``` + +**After** + +```yaml title="config.yaml" +rules: + - Always give concise responses +``` + +### Prompts + +Rather than with `customCommands`, you can now use the `prompts` field to define custom prompts. + +**Before** + +```json title="config.json" +{ + "customCommands": [ + { + "name": "check", + "description": "Check for mistakes in my code", + "prompt": "{{{ input }}}\n\nPlease read the highlighted code and check for any mistakes. You should look for the following, and be extremely vigilant:\n- Syntax errors\n- Logic errors\n- Security vulnerabilities\n- Performance issues\n- Anything else that looks wrong\n\nOnce you find an error, please explain it as clearly as possible, but without using extra words. For example, instead of saying 'I think there is a syntax error on line 5', you should say 'Syntax error on line 5'. Give your answer as one bullet point per mistake found." + } + ] +} +``` + +**After** + +```yaml title="config.yaml" +prompts: + - name: check + description: Check for mistakes in my code + prompt: | + Please read the highlighted code and check for any mistakes. You should look for the following, and be extremely vigilant: + - Syntax errors + - Logic errors + - Security vulnerabilities + - Performance issues + - Anything else that looks wrong + + Once you find an error, please explain it as clearly as possible, but without using extra words. For example, instead of saying 'I think there is a syntax error on line 5', you should say 'Syntax error on line 5'. Give your answer as one bullet point per mistake found. +``` + +### Documentation + +Documentation is largely the same, but the `title` property has been replaced with `name`. The `startUrl`, `rootUrl`, and `faviconUrl` properties remain. + +**Before** + +```json title="config.json" +{ "docs": [ { "startUrl": "https://docs.nestjs.com/", @@ -183,23 +269,15 @@ The JSON `contextProviders` and `docs` fields are replaced by the YAML `context` **After** ```yaml title="config.yaml" -context: - - uses: docs - with: - startUrl: https://docs.nestjs.com/ - title: nest.js - - uses: docs - with: - startUrl: https://mysite.com/docs/ - title: My Site - - uses: codebase - with: - nRetrieve: 30 - nFinal: 3 - - uses: diff +docs: + - name: nest.js + startUrl: https://docs.nestjs.com/ + + - name: My site + startUrl: https://mysite.com/docs/ ``` -## Map MCP Servers +### MCP Servers @@ -220,7 +298,10 @@ context: "transport": { "type": "stdio", "command": "uvx", - "args": ["mcp-server-sqlite", "--db-path", "/Users/NAME/test.db"] + "args": ["mcp-server-sqlite", "--db-path", "/Users/NAME/test.db"], + "env": { + "KEY": "" + } } } ] @@ -238,13 +319,15 @@ mcpServers: - mcp-server-sqlite - --db-path - /Users/NAME/test.db + env: + KEY: ``` --- ## Deprecated configuration options -The following top-level fields from `config.json` have been deprecated +The following top-level fields from `config.json` have been deprecated. Most UI-related and user-specific options will move into a settings page in the UI - Slash commands (JSON `slashCommands`) - top-level `requestOptions` @@ -257,7 +340,6 @@ The following top-level fields from `config.json` have been deprecated - `allowAnonymousTelemetry` (moved to user/IDE level) - `ui` (moved to user/IDE level) - `userToken` -- `systemMessage` - `disableIndexing` (moved to user/IDE level) ## New Configuration options diff --git a/docs/docs/yaml-reference.md b/docs/docs/yaml-reference.md index bcf8a7504..4b3372f0c 100644 --- a/docs/docs/yaml-reference.md +++ b/docs/docs/yaml-reference.md @@ -28,6 +28,7 @@ The top-level properties in the `config.yaml` configuration file are: - [`models`](#models) - [`context`](#context) - [`rules`](#rules) +- [`prompts`](#prompts) - [`docs`](#docs) @@ -153,6 +154,23 @@ rules: --- +### `prompts` + +A list of custom prompts that can be invoked from the chat window. Each prompt has a name, description, and the actual prompt text. + +```yaml title="config.yaml" +prompts: + - name: check + description: Check for mistakes in my code + prompt: | + Please read the highlighted code and check for any mistakes. You should look for the following, and be extremely vigilant: + - Syntax errors + - Logic errors + - Security vulnerabilities +``` + +--- + ### `docs` List of documentation sites to index. @@ -176,9 +194,7 @@ docs: --- -### `tools` - - + ### `mcpServers` @@ -247,6 +263,7 @@ Putting it all together, here's a complete example of a `config.yaml` configurat ```yaml title="config.yaml" name: MyProject +version: 0.0.1 models: - name: GPT-4 @@ -261,6 +278,7 @@ models: requestOptions: headers: Authorization: Bearer YOUR_OPENAI_API_KEY + - name: Ollama Starcoder provider: ollama model: starcoder @@ -271,18 +289,27 @@ models: stop: - "\n" +rules: + - Give concise responses + - Always assume TypeScript rather than JavaScript + +prompts: + - name: test + description: Unit test a function + prompt: | + Please write a complete suite of unit tests for this function. You should use the Jest testing framework. The tests should cover all possible edge cases and should be as thorough as possible. You should also include a description of each test case. + context: - uses: diff + - uses: file + - uses: codebase + - uses: code - uses: docs with: startUrl: https://docs.example.com/introduction rootUrl: https://docs.example.com maxDepth: 3 -tools: - - url: https://api.exampletool.com - apiKey: YOUR_TOOL_API_KEY - mcpServers: - name: DevServer command: npm diff --git a/extensions/intellij/.run/Start Core Dev Server (CE).run.xml b/extensions/intellij/.run/Start Core Dev Server (CE).run.xml index 7469eb5e8..11b362c2f 100644 --- a/extensions/intellij/.run/Start Core Dev Server (CE).run.xml +++ b/extensions/intellij/.run/Start Core Dev Server (CE).run.xml @@ -5,7 +5,7 @@