diff --git a/.continueignore b/.continueignore index 79e924012..50684c187 100644 --- a/.continueignore +++ b/.continueignore @@ -5,4 +5,5 @@ docs/docs/languages .vscode/ .archive/ **/*.scm -**/*.diff \ No newline at end of file +**/*.diff +.continue/ \ No newline at end of file diff --git a/.github/workflows/pr_checks.yaml b/.github/workflows/pr_checks.yaml index 258ec33e2..6dbae92a6 100644 --- a/.github/workflows/pr_checks.yaml +++ b/.github/workflows/pr_checks.yaml @@ -275,7 +275,7 @@ jobs: cd core npm test env: - IGNORE_API_KEY_TESTS: ${{ github.event.pull_request.head.repo.fork }} + IGNORE_API_KEY_TESTS: ${{ github.event.pull_request.head.repo.fork == true || github.actor == 'dependabot[bot]' }} OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }} @@ -303,7 +303,13 @@ jobs: cd extensions/vscode npm ci npm run e2e:compile - FILES=$(ls -1 e2e/_output/tests/*.test.js | jq -R . | jq -s .) + if [[ "${{ github.event.pull_request.head.repo.fork }}" == "true" || "${{ github.actor }}" == "dependabot[bot]" ]]; then + # Exclude SSH tests for forks + FILES=$(ls -1 e2e/_output/tests/*.test.js | grep -v "SSH" | jq -R . | jq -s .) + else + # Include all tests for non-forks + FILES=$(ls -1 e2e/_output/tests/*.test.js | jq -R . | jq -s .) + fi echo "test_file_matrix<> $GITHUB_OUTPUT echo "$FILES" >> $GITHUB_OUTPUT echo "EOF" >> $GITHUB_OUTPUT @@ -409,6 +415,14 @@ jobs: path: extensions/vscode/node_modules key: ${{ runner.os }}-vscode-node-modules-${{ hashFiles('extensions/vscode/package-lock.json') }} + # We don't want to cache the Continue extension, so it is deleted at the end of the job + - uses: actions/cache@v4 + id: test-extensions-cache + with: + path: extensions/vscode/e2e/.test-extensions + # package.json used as the key because that's where the download script is defined + key: vscode-test-extensions-${{ hashFiles('extensions/vscode/package.json') }} + - name: Download build artifact uses: actions/download-artifact@v4 with: @@ -436,7 +450,7 @@ jobs: chmod 600 ~/.ssh/id_rsa ssh-keyscan -H "$SSH_HOST" >> ~/.ssh/known_hosts echo -e "Host ssh-test-container\n\tHostName $SSH_HOST\n\tUser ec2-user\n\tIdentityFile ~/.ssh/id_rsa" >> ~/.ssh/config - if: ${{ github.event.pull_request.head.repo.fork == false }} + if: ${{ github.event.pull_request.head.repo.fork == false && github.actor != 'dependabot[bot]' }} - name: Set up Xvfb run: | @@ -446,10 +460,15 @@ jobs: - name: Run e2e tests run: | cd extensions/vscode - IGNORE_SSH_TESTS="${{ github.event.pull_request.head.repo.fork }}" TEST_FILE="${{ matrix.test_file }}" npm run ${{ matrix.command }} + IGNORE_SSH_TESTS="${{ github.event.pull_request.head.repo.fork == true || github.actor == 'dependabot[bot]' }}" TEST_FILE="${{ matrix.test_file }}" npm run ${{ matrix.command }} env: DISPLAY: :99 + - name: Delete continue from test extensions + run: | + cd extensions/vscode + rm -rf e2e/.test-extensions/continue* + - name: Upload e2e test screenshots if: failure() uses: actions/upload-artifact@v4 diff --git a/.github/workflows/stale-issue-helper.yaml b/.github/workflows/stale-issue-helper.yaml new file mode 100644 index 000000000..067f4c60f --- /dev/null +++ b/.github/workflows/stale-issue-helper.yaml @@ -0,0 +1,25 @@ +name: "Label / close stale issues" +on: + schedule: + - cron: "30 1 * * *" + +jobs: + stale: + permissions: + issues: write + pull-requests: write + runs-on: ubuntu-latest + steps: + - uses: actions/stale@v9 + with: + close-issue-message: "This issue was closed because it wasn't updated for 10 days after being marked stale. If it's still important, please reopen + comment and we'll gladly take another look!" + stale-issue-message: "This issue hasn't been updated in 90 days and will be closed after an additional 10 days without activity. If it's still important, please leave a comment and share any new information that would help us address the issue." + days-before-stale: 90 + days-before-close: 10 + days-before-pr-stale: -1 + days-before-pr-close: -1 + operations-per-run: 1000 + stale-issue-label: "stale" + stale-pr-label: "stale" + exempt-issue-labels: "needs-triage,no-stale,high,highest" + exempt-pr-labels: "no-stale" diff --git a/.gitignore b/.gitignore index f331ec68c..b24d52983 100644 --- a/.gitignore +++ b/.gitignore @@ -168,4 +168,5 @@ extensions/.continue-debug/ *.vsix -.continuerules \ No newline at end of file +.continuerules +.continue/assistants/ \ No newline at end of file diff --git a/binary/core-dev-server.js b/binary/core-dev-server.js new file mode 100644 index 000000000..506c79e68 --- /dev/null +++ b/binary/core-dev-server.js @@ -0,0 +1,6 @@ +const path = require('path'); +process.env.CONTINUE_DEVELOPMENT = true; + +process.env.CONTINUE_GLOBAL_DIR = path.join(process.env.PROJECT_DIR, 'extensions', '.continue-debug'); + +require('./out/index.js'); \ No newline at end of file diff --git a/binary/prompt-logs.js b/binary/prompt-logs.js new file mode 100644 index 000000000..68ee996f7 --- /dev/null +++ b/binary/prompt-logs.js @@ -0,0 +1,20 @@ +const fs = require('fs'); +const path = require('path'); + +const logDirPath = path.join(__dirname, '..', 'extensions', '.continue-debug', 'logs'); +const logFilePath = path.join(logDirPath, "prompt.log"); + +if (!fs.existsSync(logDirPath)) { + fs.mkdirSync(logDirPath, { recursive: true }); +} + +if (!fs.existsSync(logFilePath)) { + fs.createWriteStream(logFilePath).end(); +} + +console.log("Watching logs at " + logFilePath) + +fs.watch(logFilePath, () => { + // console.clear(); + fs.createReadStream(logFilePath).pipe(process.stdout); +}); \ No newline at end of file diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts index 32e8a4127..b56d153dc 100644 --- a/core/autocomplete/CompletionProvider.ts +++ b/core/autocomplete/CompletionProvider.ts @@ -134,6 +134,13 @@ export class CompletionProvider { token: AbortSignal | undefined, ): Promise { try { + // Create abort signal if not given + if (!token) { + const controller = this.loggingService.createAbortController( + input.completionId, + ); + token = controller.signal; + } const startTime = Date.now(); const options = await this._getAutocompleteOptions(); @@ -158,14 +165,6 @@ export class CompletionProvider { return undefined; } - // Create abort signal if not given - if (!token) { - const controller = this.loggingService.createAbortController( - input.completionId, - ); - token = controller.signal; - } - const [snippetPayload, workspaceDirs] = await Promise.all([ getAllSnippets({ helper, diff --git a/core/commands/slash/onboard.ts b/core/commands/slash/onboard.ts index d6fedcafb..b53c8d3a9 100644 --- a/core/commands/slash/onboard.ts +++ b/core/commands/slash/onboard.ts @@ -2,8 +2,7 @@ import ignore from "ignore"; import type { FileType, IDE, SlashCommand } from "../.."; import { - defaultIgnoreDir, - defaultIgnoreFile, + DEFAULT_IGNORE, getGlobalContinueIgArray, gitIgArrayFromFile, } from "../../indexing/ignore"; @@ -58,10 +57,7 @@ const OnboardSlashCommand: SlashCommand = { }; async function getEntriesFilteredByIgnore(dir: string, ide: IDE) { - const ig = ignore() - .add(defaultIgnoreDir) - .add(defaultIgnoreFile) - .add(getGlobalContinueIgArray()); + const ig = ignore().add(DEFAULT_IGNORE).add(getGlobalContinueIgArray()); const entries = await ide.listDir(dir); const ignoreUri = joinPathsToUri(dir, ".gitignore"); diff --git a/core/config/ConfigHandler.ts b/core/config/ConfigHandler.ts index b9a0f0896..d50e63235 100644 --- a/core/config/ConfigHandler.ts +++ b/core/config/ConfigHandler.ts @@ -1,5 +1,3 @@ -import * as fs from "node:fs"; - import { ConfigResult, FullSlug } from "@continuedev/config-yaml"; import { @@ -17,9 +15,8 @@ import { } from "../index.js"; import Ollama from "../llm/llms/Ollama.js"; import { GlobalContext } from "../util/GlobalContext.js"; -import { getConfigJsonPath, getConfigYamlPath } from "../util/paths.js"; -import { localPathToUri } from "../util/pathToUri.js"; +import { getAllAssistantFiles } from "./getSystemPromptDotFile.js"; import { LOCAL_ONBOARDING_CHAT_MODEL, LOCAL_ONBOARDING_PROVIDER_TITLE, @@ -86,6 +83,25 @@ export class ConfigHandler { }); } + /** + * Users can define as many local assistants as they want in a `.continue/assistants` folder + */ + private async getLocalAssistantProfiles() { + const assistantFiles = await getAllAssistantFiles(this.ide); + const profiles = assistantFiles.map((assistant) => { + return new LocalProfileLoader( + this.ide, + this.ideSettingsPromise, + this.controlPlaneClient, + this.writeLog, + assistant, + ); + }); + return profiles.map( + (profile) => new ProfileLifecycleManager(profile, this.ide), + ); + } + /** * Retrieves the titles of additional context providers that are of type "submenu". * @@ -98,13 +114,20 @@ export class ConfigHandler { } private async init() { + try { + await this.loadLocalProfilesOnly(); + } catch (e) { + console.error("Failed to load local assistants: ", e); + } + try { await this.fetchControlPlaneProfiles(); } catch (e) { // If this fails, make sure at least local profile is loaded console.error("Failed to fetch control plane profiles in init: ", e); - await this.updateAvailableProfiles([this.localProfileManager]); + await this.loadLocalProfilesOnly(); } + try { const configResult = await this.loadConfig(); this.notifyConfigListeners(configResult); @@ -135,14 +158,12 @@ export class ConfigHandler { async openConfigProfile(profileId?: string) { let openProfileId = profileId || this.selectedProfileId; - if (openProfileId === "local") { + const profile = this.profiles?.find( + (p) => p.profileDescription.id === openProfileId, + ); + if (profile?.profileDescription.profileType === "local") { const ideInfo = await this.ide.getIdeInfo(); - const configYamlPath = getConfigYamlPath(ideInfo.ideType); - if (fs.existsSync(configYamlPath)) { - await this.ide.openFile(localPathToUri(configYamlPath)); - } else { - await this.ide.openFile(localPathToUri(getConfigJsonPath())); - } + await this.ide.openFile(profile.profileDescription.uri); } else { const env = await getControlPlaneEnv(this.ide.getIdeSettings()); await this.ide.openUrl(`${env.APP_URL}${openProfileId}`); @@ -167,29 +188,32 @@ export class ConfigHandler { const assistants = await this.controlPlaneClient.listAssistants(selectedOrgId); - const hubProfiles = assistants.map((assistant) => { - const profileLoader = new PlatformProfileLoader( - { - ...assistant.configResult, - config: assistant.configResult.config, - }, - assistant.ownerSlug, - assistant.packageSlug, - assistant.iconUrl, - assistant.configResult.config?.version ?? "latest", - this.controlPlaneClient, - this.ide, - this.ideSettingsPromise, - this.writeLog, - this.reloadConfig.bind(this), - ); + const hubProfiles = await Promise.all( + assistants.map(async (assistant) => { + const profileLoader = await PlatformProfileLoader.create( + { + ...assistant.configResult, + config: assistant.configResult.config, + }, + assistant.ownerSlug, + assistant.packageSlug, + assistant.iconUrl, + assistant.configResult.config?.version ?? "latest", + this.controlPlaneClient, + this.ide, + this.ideSettingsPromise, + this.writeLog, + this.reloadConfig.bind(this), + ); - return new ProfileLifecycleManager(profileLoader, this.ide); - }); + return new ProfileLifecycleManager(profileLoader, this.ide); + }), + ); if (selectedOrgId === null) { // Personal - profiles = [...hubProfiles, this.localProfileManager]; + const allLocalProfiles = await this.getAllLocalProfiles(); + profiles = [...hubProfiles, ...allLocalProfiles]; } else { // Organization profiles = hubProfiles; @@ -199,6 +223,16 @@ export class ConfigHandler { await this.updateAvailableProfiles(profiles); } + private async getAllLocalProfiles() { + const localAssistantProfiles = await this.getLocalAssistantProfiles(); + return [this.localProfileManager, ...localAssistantProfiles]; + } + + private async loadLocalProfilesOnly() { + const allLocalProfiles = await this.getAllLocalProfiles(); + await this.updateAvailableProfiles(allLocalProfiles); + } + private async updateAvailableProfiles(profiles: ProfileLifecycleManager[]) { this.profiles = profiles; @@ -278,7 +312,7 @@ export class ConfigHandler { } else { try { const workspaces = await this.controlPlaneClient.listWorkspaces(); - const profiles = [this.localProfileManager]; + const profiles = await this.getAllLocalProfiles(); workspaces.forEach((workspace) => { const profileLoader = new ControlPlaneProfileLoader( workspace.id, @@ -296,7 +330,7 @@ export class ConfigHandler { await this.updateAvailableProfiles(profiles); } catch (e: any) { console.error("Failed to load profiles: ", e); - await this.updateAvailableProfiles([this.localProfileManager]); + await this.loadLocalProfilesOnly(); } } } @@ -355,7 +389,7 @@ export class ConfigHandler { ); this.fetchControlPlaneProfiles().catch(async (e) => { console.error("Failed to fetch control plane profiles: ", e); - await this.updateAvailableProfiles([this.localProfileManager]); + await this.loadLocalProfilesOnly(); await this.reloadConfig(); }); } diff --git a/core/config/ProfileLifecycleManager.ts b/core/config/ProfileLifecycleManager.ts index deaf5f40e..b7946ed7d 100644 --- a/core/config/ProfileLifecycleManager.ts +++ b/core/config/ProfileLifecycleManager.ts @@ -21,6 +21,7 @@ export interface ProfileDescription { id: string; iconUrl: string; errors: ConfigValidationError[] | undefined; + uri: string; } export interface OrganizationDescription { diff --git a/core/config/getSystemPromptDotFile.ts b/core/config/getSystemPromptDotFile.ts index 550144cd8..de2c25db8 100644 --- a/core/config/getSystemPromptDotFile.ts +++ b/core/config/getSystemPromptDotFile.ts @@ -1,4 +1,7 @@ import { IDE } from ".."; +import { walkDir } from "../indexing/walkDir"; +import { getGlobalAssistantsPath } from "../util/paths"; +import { localPathToUri } from "../util/pathToUri"; import { joinPathsToUri } from "../util/uri"; export const SYSTEM_PROMPT_DOT_FILE = ".continuerules"; @@ -24,3 +27,56 @@ export async function getSystemPromptDotFile(ide: IDE): Promise { return prompts.join("\n\n"); } + +export const ASSISTANTS_FOLDER = ".continue/assistants"; + +export async function getAssistantFilesFromDir( + ide: IDE, + dir: string, +): Promise<{ path: string; content: string }[]> { + try { + const exists = await ide.fileExists(localPathToUri(dir)); + + if (!exists) { + return []; + } + + const uris = await walkDir(dir, ide); + const assistantFilePaths = uris.filter( + (p) => p.endsWith(".yaml") || p.endsWith(".yml"), + ); + const results = assistantFilePaths.map(async (uri) => { + const content = await ide.readFile(uri); // make a try catch + return { path: uri, content }; + }); + return Promise.all(results); + } catch (e) { + console.error(e); + return []; + } +} + +export async function getAllAssistantFiles( + ide: IDE, +): Promise<{ path: string; content: string }[]> { + const workspaceDirs = await ide.getWorkspaceDirs(); + let assistantFiles: { path: string; content: string }[] = []; + + let dirsToCheck = [ASSISTANTS_FOLDER]; + const fullDirs = workspaceDirs + .map((dir) => dirsToCheck.map((d) => joinPathsToUri(dir, d))) + .flat(); + + fullDirs.push(getGlobalAssistantsPath()); + + assistantFiles = ( + await Promise.all(fullDirs.map((dir) => getAssistantFilesFromDir(ide, dir))) + ).flat(); + + return await Promise.all( + assistantFiles.map(async (file) => { + const content = await ide.readFile(file.path); + return { path: file.path, content }; + }), + ); +} diff --git a/core/config/load.ts b/core/config/load.ts index 1d29124d6..3636b4bf8 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -3,6 +3,11 @@ import * as fs from "fs"; import os from "os"; import path from "path"; +import { + ConfigResult, + ConfigValidationError, + ModelRole, +} from "@continuedev/config-yaml"; import { fetchwithRequestOptions } from "@continuedev/fetch"; import * as JSONC from "comment-json"; import * as tar from "tar"; @@ -31,14 +36,16 @@ import { import { slashCommandFromDescription, slashFromCustomCommand, -} from "../commands/index.js"; +} from "../commands/index"; import { AllRerankers } from "../context/allRerankers"; import { MCPManagerSingleton } from "../context/mcp"; +import CodebaseContextProvider from "../context/providers/CodebaseContextProvider"; import ContinueProxyContextProvider from "../context/providers/ContinueProxyContextProvider"; import CustomContextProviderClass from "../context/providers/CustomContextProvider"; import FileContextProvider from "../context/providers/FileContextProvider"; import { contextProviderClassFromName } from "../context/providers/index"; import PromptFilesContextProvider from "../context/providers/PromptFilesContextProvider"; +import { useHub } from "../control-plane/env"; import { allEmbeddingsProviders } from "../indexing/allEmbeddingsProviders"; import { BaseLLM } from "../llm"; import { llmFromDescription } from "../llm/llms"; @@ -62,14 +69,8 @@ import { getContinueDotEnv, getEsbuildBinaryPath, } from "../util/paths"; - -import { - ConfigResult, - ConfigValidationError, - ModelRole, -} from "@continuedev/config-yaml"; -import { useHub } from "../control-plane/env"; import { localPathToUri } from "../util/pathToUri"; + import { defaultContextProvidersJetBrains, defaultContextProvidersVsCode, @@ -78,7 +79,7 @@ import { } from "./default"; import { getSystemPromptDotFile } from "./getSystemPromptDotFile"; import { modifyAnyConfigWithSharedConfig } from "./sharedConfig"; -import { getModelByRole } from "./util"; +import { getModelByRole, isSupportedLanceDbCpuTargetForLinux } from "./util"; import { validateConfig } from "./validation.js"; export function resolveSerializedConfig( @@ -172,10 +173,9 @@ function loadSerializedConfig( ? [...defaultSlashCommandsVscode] : [...defaultSlashCommandsJetBrains]; - // Temporarily disabling this check until we can verify the commands are accuarate - // if (!isSupportedLanceDbCpuTarget(ide)) { - // config.disableIndexing = true; - // } + if (os.platform() === "linux" && !isSupportedLanceDbCpuTargetForLinux(ide)) { + config.disableIndexing = true; + } return { config, errors, configLoadInterrupted: false }; } @@ -232,13 +232,6 @@ export function isContextProviderWithParams( return (contextProvider as ContextProviderWithParams).name !== undefined; } -const getCodebaseProvider = async (params: any) => { - const { default: CodebaseContextProvider } = await import( - "../context/providers/CodebaseContextProvider" - ); - return new CodebaseContextProvider(params); -}; - /** Only difference between intermediate and final configs is the `models` array */ async function intermediateToFinalConfig( config: Config, @@ -279,7 +272,7 @@ async function intermediateToFinalConfig( { ...desc, model: modelName, - title: `${llm.title} - ${modelName}`, + title: modelName, }, ide.readFile.bind(ide), uniqueId, @@ -405,7 +398,7 @@ async function intermediateToFinalConfig( new FileContextProvider({}), // Add codebase provider if indexing is enabled ...(!config.disableIndexing - ? [await getCodebaseProvider(codebaseContextParams)] + ? [new CodebaseContextProvider(codebaseContextParams)] : []), // Add prompt files provider if enabled ...(loadPromptFiles ? [new PromptFilesContextProvider({})] : []), diff --git a/core/config/profile/ControlPlaneProfileLoader.ts b/core/config/profile/ControlPlaneProfileLoader.ts index 6df837cf4..cce940ab7 100644 --- a/core/config/profile/ControlPlaneProfileLoader.ts +++ b/core/config/profile/ControlPlaneProfileLoader.ts @@ -10,6 +10,7 @@ import { } from "../../index.js"; import { ProfileDescription } from "../ProfileLifecycleManager.js"; +import { PRODUCTION_ENV } from "../../control-plane/env.js"; import doLoadConfig from "./doLoadConfig.js"; import { IProfileLoader } from "./IProfileLoader.js"; @@ -40,6 +41,7 @@ export default class ControlPlaneProfileLoader implements IProfileLoader { }, title: workspaceTitle, errors: undefined, + uri: `${PRODUCTION_ENV.APP_URL}workspaces/${workspaceId}`, }; setInterval(async () => { @@ -68,6 +70,7 @@ export default class ControlPlaneProfileLoader implements IProfileLoader { undefined, undefined, this.workspaceId, + undefined, ); return { diff --git a/core/config/profile/LocalProfileLoader.ts b/core/config/profile/LocalProfileLoader.ts index 9ccf5c812..13a1480c9 100644 --- a/core/config/profile/LocalProfileLoader.ts +++ b/core/config/profile/LocalProfileLoader.ts @@ -1,33 +1,54 @@ -import { ConfigResult } from "@continuedev/config-yaml"; +import { ConfigResult, parseConfigYaml } from "@continuedev/config-yaml"; import { ControlPlaneClient } from "../../control-plane/client.js"; import { ContinueConfig, IDE, IdeSettings } from "../../index.js"; import { ProfileDescription } from "../ProfileLifecycleManager.js"; +import { getPrimaryConfigFilePath } from "../../util/paths.js"; +import { localPathToUri } from "../../util/pathToUri.js"; import doLoadConfig from "./doLoadConfig.js"; import { IProfileLoader } from "./IProfileLoader.js"; export default class LocalProfileLoader implements IProfileLoader { static ID = "local"; - description: ProfileDescription = { - id: LocalProfileLoader.ID, - profileType: "local", - fullSlug: { - ownerSlug: "", - packageSlug: "", - versionSlug: "", - }, - iconUrl: "", - title: "Local Config", - errors: undefined, - }; constructor( private ide: IDE, private ideSettingsPromise: Promise, private controlPlaneClient: ControlPlaneClient, private writeLog: (message: string) => Promise, - ) {} + private overrideAssistantFile?: + | { path: string; content: string } + | undefined, + ) { + const description: ProfileDescription = { + id: overrideAssistantFile?.path ?? LocalProfileLoader.ID, + profileType: "local", + fullSlug: { + ownerSlug: "", + packageSlug: "", + versionSlug: "", + }, + iconUrl: "", + title: overrideAssistantFile?.path ?? "Local Config", + errors: undefined, + uri: + overrideAssistantFile?.path ?? + localPathToUri(getPrimaryConfigFilePath()), + }; + this.description = description; + if (overrideAssistantFile?.content) { + try { + const parsedAssistant = parseConfigYaml( + overrideAssistantFile?.content ?? "", + ); + this.description.title = parsedAssistant.name; + } catch (e) { + console.error("Failed to parse assistant file: ", e); + } + } + } + description: ProfileDescription; async doLoadConfig(): Promise> { const result = await doLoadConfig( @@ -39,6 +60,7 @@ export default class LocalProfileLoader implements IProfileLoader { undefined, undefined, this.description.id, + this.overrideAssistantFile?.path, ); this.description.errors = result.errors; diff --git a/core/config/profile/PlatformProfileLoader.ts b/core/config/profile/PlatformProfileLoader.ts index c0fa4c5cc..329a7a59e 100644 --- a/core/config/profile/PlatformProfileLoader.ts +++ b/core/config/profile/PlatformProfileLoader.ts @@ -5,6 +5,7 @@ import { ContinueConfig, IDE, IdeSettings } from "../../index.js"; import { ProfileDescription } from "../ProfileLifecycleManager.js"; +import { getControlPlaneEnv } from "../../control-plane/env.js"; import doLoadConfig from "./doLoadConfig.js"; import { IProfileLoader } from "./IProfileLoader.js"; @@ -21,21 +22,35 @@ export interface PlatformConfigMetadata { export default class PlatformProfileLoader implements IProfileLoader { static RELOAD_INTERVAL = 1000 * 5; // 5 seconds - description: ProfileDescription; - - constructor( + private constructor( private configResult: ConfigResult, private readonly ownerSlug: string, private readonly packageSlug: string, private readonly iconUrl: string, - versionSlug: string, + private readonly versionSlug: string, private readonly controlPlaneClient: ControlPlaneClient, private readonly ide: IDE, private ideSettingsPromise: Promise, private writeLog: (message: string) => Promise, private readonly onReload: () => void, - ) { - this.description = { + readonly description: ProfileDescription, + ) {} + + static async create( + configResult: ConfigResult, + ownerSlug: string, + packageSlug: string, + iconUrl: string, + versionSlug: string, + controlPlaneClient: ControlPlaneClient, + ide: IDE, + ideSettingsPromise: Promise, + writeLog: (message: string) => Promise, + onReload: () => void, + ): Promise { + const controlPlaneEnv = await getControlPlaneEnv(ideSettingsPromise); + + const description: ProfileDescription = { id: `${ownerSlug}/${packageSlug}`, profileType: "platform", fullSlug: { @@ -45,8 +60,23 @@ export default class PlatformProfileLoader implements IProfileLoader { }, title: configResult.config?.name ?? `${ownerSlug}/${packageSlug}`, errors: configResult.errors, - iconUrl: this.iconUrl, + iconUrl: iconUrl, + uri: `${controlPlaneEnv}${ownerSlug}/${packageSlug}`, }; + + return new PlatformProfileLoader( + configResult, + ownerSlug, + packageSlug, + iconUrl, + versionSlug, + controlPlaneClient, + ide, + ideSettingsPromise, + writeLog, + onReload, + description, + ); } async doLoadConfig(): Promise> { @@ -70,6 +100,7 @@ export default class PlatformProfileLoader implements IProfileLoader { packageSlug: this.packageSlug, }, this.description.id, + undefined, ); return { diff --git a/core/config/profile/doLoadConfig.ts b/core/config/profile/doLoadConfig.ts index 0ec9b4137..224b7b64e 100644 --- a/core/config/profile/doLoadConfig.ts +++ b/core/config/profile/doLoadConfig.ts @@ -19,13 +19,14 @@ import { getControlPlaneEnv } from "../../control-plane/env.js"; import { TeamAnalytics } from "../../control-plane/TeamAnalytics.js"; import ContinueProxy from "../../llm/llms/stubs/ContinueProxy"; import { getConfigJsonPath, getConfigYamlPath } from "../../util/paths"; +import { localPathOrUriToPath } from "../../util/pathToUri"; import { Telemetry } from "../../util/posthog"; import { TTS } from "../../util/tts"; import { loadContinueConfigFromJson } from "../load"; import { migrateJsonSharedConfig } from "../migrateSharedConfig"; +import { rectifySelectedModelsFromGlobalContext } from "../selectedModels"; import { loadContinueConfigFromYaml } from "../yaml/loadYaml"; import { PlatformConfigMetadata } from "./PlatformProfileLoader"; -import { rectifySelectedModelsFromGlobalContext } from "../selectedModels"; export default async function doLoadConfig( ide: IDE, @@ -36,6 +37,7 @@ export default async function doLoadConfig( overrideConfigYaml: AssistantUnrolled | undefined, platformConfigMetadata: PlatformConfigMetadata | undefined, profileId: string, + overrideConfigYamlByPath: string | undefined, ): Promise> { const workspaceConfigs = await getWorkspaceConfigs(ide); const ideInfo = await ide.getIdeInfo(); @@ -50,7 +52,9 @@ export default async function doLoadConfig( migrateJsonSharedConfig(configJsonPath, ide); } - const configYamlPath = getConfigYamlPath(ideInfo.ideType); + const configYamlPath = localPathOrUriToPath( + overrideConfigYamlByPath || getConfigYamlPath(ideInfo.ideType), + ); let newConfig: ContinueConfig | undefined; let errors: ConfigValidationError[] | undefined; @@ -68,6 +72,7 @@ export default async function doLoadConfig( overrideConfigYaml, platformConfigMetadata, controlPlaneClient, + configYamlPath, ); newConfig = result.config; errors = result.errors; diff --git a/core/config/util.ts b/core/config/util.ts index f55848586..8bfe6a84f 100644 --- a/core/config/util.ts +++ b/core/config/util.ts @@ -1,4 +1,4 @@ -import { execSync } from "child_process"; +import fs from "fs"; import os from "os"; import { @@ -121,11 +121,13 @@ export function getModelByRole( * * See here for details: https://github.com/continuedev/continue/issues/940 */ -export function isSupportedLanceDbCpuTarget(ide: IDE) { +export function isSupportedLanceDbCpuTargetForLinux(ide?: IDE) { const CPU_FEATURES_TO_CHECK = ["avx2", "fma"] as const; const globalContext = new GlobalContext(); - const globalContextVal = globalContext.get("isSupportedLanceDbCpuTarget"); + const globalContextVal = globalContext.get( + "isSupportedLanceDbCpuTargetForLinux", + ); // If we've already checked the CPU target, return the cached value if (globalContextVal !== undefined) { @@ -133,51 +135,35 @@ export function isSupportedLanceDbCpuTarget(ide: IDE) { } const arch = os.arch(); - const platform = os.platform(); // This check only applies to x64 //https://github.com/lancedb/lance/issues/2195#issuecomment-2057841311 if (arch !== "x64") { - globalContext.update("isSupportedLanceDbCpuTarget", true); + globalContext.update("isSupportedLanceDbCpuTargetForLinux", true); return true; } try { - const cpuFlags = (() => { - switch (platform) { - case "darwin": - return execSync("sysctl -n machdep.cpu.features") - .toString() - .toLowerCase(); - case "linux": - return execSync("cat /proc/cpuinfo").toString().toLowerCase(); - case "win32": - return execSync("wmic cpu get caption /format:list") - .toString() - .toLowerCase(); - default: - return ""; - } - })(); + const cpuFlags = fs.readFileSync("/proc/cpuinfo", "utf-8").toLowerCase(); - const isSupportedLanceDbCpuTarget = cpuFlags + const isSupportedLanceDbCpuTargetForLinux = cpuFlags ? CPU_FEATURES_TO_CHECK.every((feature) => cpuFlags.includes(feature)) : true; // If it's not a supported CPU target, and it's the first time we are checking, // show a toast to inform the user that we are going to disable indexing. - if (!isSupportedLanceDbCpuTarget) { + if (!isSupportedLanceDbCpuTargetForLinux && ide) { // We offload our async toast to `showUnsupportedCpuToast` to prevent making - // our config loading async upstream of `isSupportedLanceDbCpuTarget` + // our config loading async upstream of `isSupportedLanceDbCpuTargetForLinux` void showUnsupportedCpuToast(ide); } globalContext.update( - "isSupportedLanceDbCpuTarget", - isSupportedLanceDbCpuTarget, + "isSupportedLanceDbCpuTargetForLinux", + isSupportedLanceDbCpuTargetForLinux, ); - return isSupportedLanceDbCpuTarget; + return isSupportedLanceDbCpuTargetForLinux; } catch (error) { // If we can't determine CPU features, default to true return true; @@ -187,11 +173,13 @@ export function isSupportedLanceDbCpuTarget(ide: IDE) { async function showUnsupportedCpuToast(ide: IDE) { const shouldOpenLink = await ide.showToast( "warning", - "Codebase indexing is disabled due to CPU incompatibility", + "Codebase indexing disabled - Your Linux system lacks required CPU features (AVX2, FMA)", "Learn more", ); if (shouldOpenLink) { - void ide.openUrl("https://github.com/continuedev/continue/pull/3551"); + void ide.openUrl( + "https://docs.continue.dev/troubleshooting#i-received-a-codebase-indexing-disabled---your-linux-system-lacks-required-cpu-features-avx2-fma-notification", + ); } } diff --git a/core/config/yaml/loadYaml.ts b/core/config/yaml/loadYaml.ts index bf0515253..8d0ebf60a 100644 --- a/core/config/yaml/loadYaml.ts +++ b/core/config/yaml/loadYaml.ts @@ -366,10 +366,14 @@ export async function loadContinueConfigFromYaml( overrideConfigYaml: AssistantUnrolled | undefined, platformConfigMetadata: PlatformConfigMetadata | undefined, controlPlaneClient: ControlPlaneClient, + configYamlPath: string | undefined, ): Promise> { const rawYaml = overrideConfigYaml === undefined - ? fs.readFileSync(getConfigYamlPath(ideInfo.ideType), "utf-8") + ? fs.readFileSync( + configYamlPath ?? getConfigYamlPath(ideInfo.ideType), + "utf-8", + ) : ""; const configYamlResult = await loadConfigYaml( @@ -415,6 +419,9 @@ export async function loadContinueConfigFromYaml( continueConfig, sharedConfig, ); + if (withShared.allowAnonymousTelemetry === undefined) { + withShared.allowAnonymousTelemetry = true; + } return { config: withShared, diff --git a/core/config/yaml/models.ts b/core/config/yaml/models.ts index c6916b010..b4392d519 100644 --- a/core/config/yaml/models.ts +++ b/core/config/yaml/models.ts @@ -127,7 +127,7 @@ async function autodetectModels( { ...model, model: modelName, - name: `${llm.title} - ${modelName}`, + name: modelName, }, uniqueId, ideSettings, diff --git a/core/context/providers/GitLabMergeRequestContextProvider.ts b/core/context/providers/GitLabMergeRequestContextProvider.ts index 3e8f77a67..b4d3fe2ed 100644 --- a/core/context/providers/GitLabMergeRequestContextProvider.ts +++ b/core/context/providers/GitLabMergeRequestContextProvider.ts @@ -94,7 +94,7 @@ class GitLabMergeRequestContextProvider extends BaseContextProvider { }); } - private async getRemoteBranchName( + private async getRemoteBranchInfo( extras: ContextProviderExtras, ): Promise { const subprocess = await getSubprocess(extras); @@ -121,9 +121,16 @@ class GitLabMergeRequestContextProvider extends BaseContextProvider { const remoteUrl = await subprocess(`git remote get-url ${branchRemote}`); - const urlMatches = /:(?.*).git/.exec(remoteUrl); + let urlMatches: RegExpExecArray | null; + if (/https?.*/.test(remoteUrl)) { + const pathname = new URL(remoteUrl).pathname; + urlMatches = /\/(?.*?)(?:(?=\.git)|$)/.exec(pathname) + } else { + // ssh + urlMatches = /:(?.*).git/.exec(remoteUrl) + } - const project = urlMatches?.groups?.project ?? null; + const project = urlMatches?.groups?.projectPath ?? null; return { branch: remoteBranch, @@ -135,7 +142,7 @@ class GitLabMergeRequestContextProvider extends BaseContextProvider { query: string, extras: ContextProviderExtras, ): Promise { - const { branch, project } = await this.getRemoteBranchName(extras); + const { branch, project } = await this.getRemoteBranchInfo(extras); const api = await this.getApi(); diff --git a/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts b/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts index e341c681c..a3dcc0f7e 100644 --- a/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts +++ b/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts @@ -33,12 +33,21 @@ export interface IRetrievalPipeline { export default class BaseRetrievalPipeline implements IRetrievalPipeline { private ftsIndex = new FullTextSearchCodebaseIndex(); - private lanceDbIndex: LanceDbIndex; + private lanceDbIndex: LanceDbIndex | null = null; constructor(protected readonly options: RetrievalPipelineOptions) { - this.lanceDbIndex = new LanceDbIndex( - options.config.selectedModelByRole.embed, - (uri) => options.ide.readFile(uri), + void this.initLanceDb(); + } + + private async initLanceDb() { + const embedModel = this.options.config.selectedModelByRole.embed; + + if (!embedModel) { + return; + } + + this.lanceDbIndex = await LanceDbIndex.create(embedModel, (uri) => + this.options.ide.readFile(uri), ); } @@ -62,27 +71,28 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline { return trigrams; } + private escapeFtsQueryString(query: string): string { + const escapedDoubleQuotes = query.replace(/"/g, '""'); + return `"${escapedDoubleQuotes}"`; + } + protected async retrieveFts( args: RetrievalPipelineRunArguments, n: number, ): Promise { - try { - if (args.query.trim() === "") { - return []; - } - - const tokens = this.getCleanedTrigrams(args.query).join(" OR "); - - return await this.ftsIndex.retrieve({ - n, - text: tokens, - tags: args.tags, - directory: args.filterDirectory, - }); - } catch (e) { - console.warn("Error retrieving from FTS:", e); + if (args.query.trim() === "") { return []; } + + const tokensRaw = this.getCleanedTrigrams(args.query).join(" OR "); + const tokens = this.escapeFtsQueryString(tokensRaw); + + return await this.ftsIndex.retrieve({ + n, + text: tokens, + tags: args.tags, + directory: args.filterDirectory, + }); } protected async retrieveAndChunkRecentlyEditedFiles( @@ -111,7 +121,8 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline { filepath, contents, maxChunkSize: - this.options.config.selectedModelByRole.embed?.maxEmbeddingChunkSize ?? DEFAULT_CHUNK_SIZE, + this.options.config.selectedModelByRole.embed + ?.maxEmbeddingChunkSize ?? DEFAULT_CHUNK_SIZE, digest: filepath, }); @@ -127,6 +138,13 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline { input: string, n: number, ): Promise { + if (!this.lanceDbIndex) { + console.warn( + "LanceDB index not available, skipping embeddings retrieval", + ); + return []; + } + return this.lanceDbIndex.retrieve( input, n, diff --git a/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts b/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts index 889005414..f35809fed 100644 --- a/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts +++ b/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts @@ -19,22 +19,42 @@ export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline { let retrievalResults: Chunk[] = []; - const ftsChunks = await this.retrieveFts(args, ftsNFinal); + let ftsChunks: Chunk[] = []; + try { + ftsChunks = await this.retrieveFts(args, ftsNFinal); + } catch (error) { + console.error("Error retrieving FTS chunks:", error); + } - const embeddingsChunks = !!config.selectedModelByRole.embed - ? await this.retrieveEmbeddings(input, embeddingsNFinal) - : []; + let embeddingsChunks: Chunk[] = []; + try { + embeddingsChunks = !!config.selectedModelByRole.embed + ? await this.retrieveEmbeddings(input, embeddingsNFinal) + : []; + } catch (error) { + console.error("Error retrieving embeddings:", error); + } - const recentlyEditedFilesChunks = - await this.retrieveAndChunkRecentlyEditedFiles(recentlyEditedNFinal); + let recentlyEditedFilesChunks: Chunk[] = []; + try { + recentlyEditedFilesChunks = + await this.retrieveAndChunkRecentlyEditedFiles(recentlyEditedNFinal); + } catch (error) { + console.error("Error retrieving recently edited files:", error); + } - const repoMapChunks = await requestFilesFromRepoMap( - this.options.llm, - this.options.config, - this.options.ide, - input, - filterDirectory, - ); + let repoMapChunks: Chunk[] = []; + try { + repoMapChunks = await requestFilesFromRepoMap( + this.options.llm, + this.options.config, + this.options.ide, + input, + filterDirectory, + ); + } catch (error) { + console.error("Error retrieving repo map chunks:", error); + } retrievalResults.push( ...recentlyEditedFilesChunks, diff --git a/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts b/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts index 67f4bcd45..a3e4d830f 100644 --- a/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts +++ b/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts @@ -16,20 +16,42 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline { let retrievalResults: Chunk[] = []; - const ftsChunks = await this.retrieveFts(args, nRetrieve); - const embeddingsChunks = !!config.selectedModelByRole.embed - ? await this.retrieveEmbeddings(input, nRetrieve) - : []; - const recentlyEditedFilesChunks = - await this.retrieveAndChunkRecentlyEditedFiles(nRetrieve); + let ftsChunks: Chunk[] = []; + try { + ftsChunks = await this.retrieveFts(args, nRetrieve); + } catch (error) { + console.error("Error retrieving FTS chunks:", error); + } - const repoMapChunks = await requestFilesFromRepoMap( - this.options.llm, - this.options.config, - this.options.ide, - input, - filterDirectory, - ); + let embeddingsChunks: Chunk[] = []; + try { + embeddingsChunks = !!config.selectedModelByRole.embed + ? await this.retrieveEmbeddings(input, nRetrieve) + : []; + } catch (error) { + console.error("Error retrieving embeddings chunks:", error); + } + + let recentlyEditedFilesChunks: Chunk[] = []; + try { + recentlyEditedFilesChunks = + await this.retrieveAndChunkRecentlyEditedFiles(nRetrieve); + } catch (error) { + console.error("Error retrieving recently edited files chunks:", error); + } + + let repoMapChunks: Chunk[] = []; + try { + repoMapChunks = await requestFilesFromRepoMap( + this.options.llm, + this.options.config, + this.options.ide, + input, + filterDirectory, + ); + } catch (error) { + console.error("Error retrieving repo map chunks:", error); + } retrievalResults.push( ...recentlyEditedFilesChunks, @@ -41,7 +63,8 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline { if (filterDirectory) { // Backup if the individual retrieval methods don't listen retrievalResults = retrievalResults.filter( - (chunk) => !!findUriInDirs(chunk.filepath, [filterDirectory]), + (chunk) => + !!findUriInDirs(chunk.filepath, [filterDirectory]).foundInDir, ); } diff --git a/core/control-plane/env.ts b/core/control-plane/env.ts index 288901cab..8995dca7e 100644 --- a/core/control-plane/env.ts +++ b/core/control-plane/env.ts @@ -18,7 +18,7 @@ const WORKOS_CLIENT_ID_STAGING = "client_01J0FW6XCPMJMQ3CG51RB4HBZQ"; const WORKOS_ENV_ID_PRODUCTION = "continue"; const WORKOS_ENV_ID_STAGING = "continue-staging"; -const PRODUCTION_ENV: ControlPlaneEnv = { +export const PRODUCTION_ENV: ControlPlaneEnv = { DEFAULT_CONTROL_PLANE_PROXY_URL: "https://control-plane-api-service-i3dqylpbqa-uc.a.run.app/", CONTROL_PLANE_URL: diff --git a/core/core.ts b/core/core.ts index 6d78ca855..4861013bf 100644 --- a/core/core.ts +++ b/core/core.ts @@ -1,7 +1,4 @@ -import path from "path"; - import { fetchwithRequestOptions } from "@continuedev/fetch"; -import ignore from "ignore"; import * as URI from "uri-js"; import { v4 as uuidv4 } from "uuid"; @@ -26,7 +23,6 @@ import { streamDiffLines } from "./edit/streamDiffLines"; import { CodebaseIndexer, PauseToken } from "./indexing/CodebaseIndexer"; import DocsService from "./indexing/docs/DocsService"; import { getAllSuggestedDocs } from "./indexing/docs/suggestions"; -import { defaultIgnoreFile } from "./indexing/ignore.js"; import Ollama from "./llm/llms/Ollama"; import { createNewPromptFileV2 } from "./promptFiles/v2/createNewPromptFile"; import { callTool } from "./tools/callTool"; @@ -34,12 +30,7 @@ import { ChatDescriber } from "./util/chatDescriber"; import { clipboardCache } from "./util/clipboardCache"; import { GlobalContext } from "./util/GlobalContext"; import historyManager from "./util/history"; -import { - editConfigJson, - getConfigJsonPath, - migrateV1DevDataFiles, -} from "./util/paths"; -import { localPathToUri } from "./util/pathToUri"; +import { editConfigJson, migrateV1DevDataFiles } from "./util/paths"; import { Telemetry } from "./util/posthog"; import { getSymbolsForManyFiles } from "./util/treeSitter"; import { TTS } from "./util/tts"; @@ -53,6 +44,7 @@ import { type IndexingProgressUpdate, } from "."; +import { shouldIgnore } from "./indexing/shouldIgnore"; import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; import type { IMessenger, Message } from "./protocol/messenger"; @@ -829,6 +821,10 @@ export class Core { // Codebase indexing on("index/forceReIndex", async ({ data }) => { + const { config } = await this.configHandler.loadConfig(); + if (!config || config.disableIndexing) { + return; // TODO silent in case of commands? + } if (data?.shouldClearIndexes) { const codebaseIndexer = await this.codebaseIndexerPromise; await codebaseIndexer.clearIndexes(); @@ -859,7 +855,10 @@ export class Core { for (const uri of data.uris) { // Listen for file changes in the workspace // URI TODO is this equality statement valid? - if (URI.equal(uri, localPathToUri(getConfigJsonPath()))) { + const currentProfileUri = + this.configHandler.currentProfile?.profileDescription.uri ?? ""; + + if (URI.equal(uri, currentProfileUri)) { // Trigger a toast notification to provide UI feedback that config has been updated const showToast = this.globalContext.get("showConfigUpdateToast") ?? true; @@ -873,6 +872,8 @@ export class Core { this.globalContext.update("showConfigUpdateToast", false); } } + await this.configHandler.reloadConfig(); + continue; } if ( @@ -886,30 +887,51 @@ export class Core { uri.endsWith(".gitignore") ) { // Reindex the workspaces - this.invoke("index/forceReIndex", undefined); + this.invoke("index/forceReIndex", { + shouldClearIndexes: true, + }); } else { - // Reindex the file - await this.refreshCodebaseIndexFiles([uri]); + const { config } = await this.configHandler.loadConfig(); + if (config && !config.disableIndexing) { + // Reindex the file + const ignore = await shouldIgnore(uri, this.ide); + if (!ignore) { + await this.refreshCodebaseIndexFiles([uri]); + } + } } } } }); - on("files/created", async ({ data }) => { - if (data?.uris?.length) { + const refreshIfNotIgnored = async (uris: string[]) => { + const toRefresh: string[] = []; + for (const uri of uris) { + const ignore = await shouldIgnore(uri, ide); + if (!ignore) { + toRefresh.push(uri); + } + } + if (toRefresh.length > 0) { this.messenger.send("refreshSubmenuItems", { providers: ["file"], }); - await this.refreshCodebaseIndexFiles(data.uris); + const { config } = await this.configHandler.loadConfig(); + if (config && !config.disableIndexing) { + await this.refreshCodebaseIndexFiles(toRefresh); + } + } + }; + + on("files/created", async ({ data }) => { + if (data?.uris?.length) { + void refreshIfNotIgnored(data.uris); } }); on("files/deleted", async ({ data }) => { if (data?.uris?.length) { - this.messenger.send("refreshSubmenuItems", { - providers: ["file"], - }); - await this.refreshCodebaseIndexFiles(data.uris); + void refreshIfNotIgnored(data.uris); } }); on("files/opened", async ({ data }) => { @@ -950,15 +972,21 @@ export class Core { }); // - on("didChangeSelectedProfile", (msg) => { - void this.configHandler.setSelectedProfile(msg.data.id); - void this.configHandler.reloadConfig(); + on("didChangeSelectedProfile", async (msg) => { + await this.configHandler.setSelectedProfile(msg.data.id); + await this.configHandler.reloadConfig(); }); - on("didChangeSelectedOrg", (msg) => { - void this.configHandler.setSelectedOrgId(msg.data.id); - void this.configHandler.reloadConfig(); - void this.configHandler.loadAssistantsForSelectedOrg(); + on("didChangeSelectedOrg", async (msg) => { + await this.configHandler.setSelectedOrgId(msg.data.id); + await this.configHandler.loadAssistantsForSelectedOrg(); + if (msg.data.profileId) { + this.invoke("didChangeSelectedProfile", { + id: msg.data.profileId, + }); + } else { + await this.configHandler.reloadConfig(); + } }); on("didChangeControlPlaneSessionInfo", async (msg) => { @@ -975,19 +1003,15 @@ export class Core { }); on("didChangeActiveTextEditor", async ({ data: { filepath } }) => { - const ignoreInstance = ignore().add(defaultIgnoreFile); - let rootDirectory = await this.ide.getWorkspaceDirs(); - const relativeFilePath = path.relative(rootDirectory[0], filepath); try { - if (!ignoreInstance.ignores(relativeFilePath)) { + const ignore = shouldIgnore(filepath, this.ide); + if (!ignore) { recentlyEditedFilesCache.set(filepath, filepath); } } catch (e) { - if (e instanceof RangeError) { - // do nothing, this can happen when editing a file outside the workspace such as `../extensions/.continue-debug/config.json` - } else { - console.debug("unhandled ignores error", relativeFilePath, e); - } + console.error( + `didChangeActiveTextEditor: failed to update recentlyEditedFiles cache for ${filepath}`, + ); } }); @@ -1108,6 +1132,7 @@ export class Core { this.messenger.send("refreshSubmenuItems", { providers: "dependsOnIndexing", }); + this.indexingCancellationController = undefined; } // private diff --git a/core/index.d.ts b/core/index.d.ts index 8a86db6be..f0d6090e6 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -163,6 +163,10 @@ export interface ILLM extends LLMOptions { ): string | ChatMessage[]; } +export interface ModelInstaller { + installModel(modelName: string, signal: AbortSignal, progressReporter?: (task: string, increment: number, total: number) => void): Promise; +} + export type ContextProviderType = "normal" | "query" | "submenu"; export interface ContextProviderDescription { @@ -552,7 +556,7 @@ export interface CustomLLMWithOptionals { signal: AbortSignal, options: CompletionOptions, fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise, - ) => AsyncGenerator; + ) => AsyncGenerator; listModels?: ( fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise, ) => Promise; diff --git a/core/indexing/CodebaseIndexer.ts b/core/indexing/CodebaseIndexer.ts index 6f5a5e946..d59f0ded8 100644 --- a/core/indexing/CodebaseIndexer.ts +++ b/core/indexing/CodebaseIndexer.ts @@ -15,6 +15,7 @@ import { getComputeDeleteAddRemove } from "./refreshIndex.js"; import { CodebaseIndex, IndexResultType, + PathAndCacheKey, RefreshIndexResults, } from "./types.js"; import { walkDirAsync } from "./walkDir.js"; @@ -85,24 +86,61 @@ export class CodebaseIndexer { return []; } - const indexes = [ + const indexes: CodebaseIndex[] = [ new ChunkCodebaseIndex( this.ide.readFile.bind(this.ide), this.continueServerClient, embeddingsModel.maxEmbeddingChunkSize, ), // Chunking must come first - new LanceDbIndex( - embeddingsModel, - this.ide.readFile.bind(this.ide), - this.continueServerClient, - ), - new FullTextSearchCodebaseIndex(), - new CodeSnippetsCodebaseIndex(this.ide), ]; + const lanceDbIndex = await LanceDbIndex.create( + embeddingsModel, + this.ide.readFile.bind(this.ide), + this.continueServerClient, + ); + + if (lanceDbIndex) { + indexes.push(lanceDbIndex); + } + + indexes.push( + new FullTextSearchCodebaseIndex(), + new CodeSnippetsCodebaseIndex(this.ide), + ); + return indexes; } + private totalIndexOps(results: RefreshIndexResults): number { + return ( + results.compute.length + + results.del.length + + results.addTag.length + + results.removeTag.length + ); + } + + private singleFileIndexOps( + results: RefreshIndexResults, + lastUpdated: PathAndCacheKey[], + filePath: string, + ): [RefreshIndexResults, PathAndCacheKey[]] { + const filterFn = (item: PathAndCacheKey) => item.path === filePath; + const compute = results.compute.filter(filterFn); + const del = results.del.filter(filterFn); + const addTag = results.addTag.filter(filterFn); + const removeTag = results.removeTag.filter(filterFn); + const newResults = { + compute, + del, + addTag, + removeTag, + }; + const newLastUpdated = lastUpdated.filter(filterFn); + return [newResults, newLastUpdated]; + } + public async refreshFile( file: string, workspaceDirs: string[], @@ -120,26 +158,28 @@ export class CodebaseIndexer { const repoName = await this.ide.getRepoName(foundInDir); const indexesToBuild = await this.getIndexesToBuild(); const stats = await this.ide.getFileStats([file]); + const filePath = Object.keys(stats)[0]; for (const index of indexesToBuild) { const tag = { directory: foundInDir, branch, artifactId: index.artifactId, }; - const [results, lastUpdated, markComplete] = + const [fullResults, fullLastUpdated, markComplete] = await getComputeDeleteAddRemove( tag, { ...stats }, (filepath) => this.ide.readFile(filepath), repoName, ); - // since this is only a single file update / save we do not want to actualy remove anything, we just want to recompute for our single file - results.removeTag = []; - results.addTag = []; - results.del = []; + const [results, lastUpdated] = this.singleFileIndexOps( + fullResults, + fullLastUpdated, + filePath, + ); // Don't update if nothing to update. Some of the indices might do unnecessary setup work - if (results.compute.length === 0) { + if (this.totalIndexOps(results) + lastUpdated.length === 0) { continue; } @@ -420,11 +460,7 @@ export class CodebaseIndexer { (filepath) => this.ide.readFile(filepath), repoName, ); - const totalOps = - results.compute.length + - results.del.length + - results.addTag.length + - results.removeTag.length; + const totalOps = this.totalIndexOps(results); let completedOps = 0; // Don't update if nothing to update. Some of the indices might do unnecessary setup work diff --git a/core/indexing/FullTextSearchCodebaseIndex.ts b/core/indexing/FullTextSearchCodebaseIndex.ts index 7ff54781c..de183e158 100644 --- a/core/indexing/FullTextSearchCodebaseIndex.ts +++ b/core/indexing/FullTextSearchCodebaseIndex.ts @@ -97,13 +97,15 @@ export class FullTextSearchCodebaseIndex implements CodebaseIndex { // Delete for (const item of results.del) { + await db.run(` + DELETE FROM fts WHERE rowid IN ( + SELECT id FROM fts_metadata WHERE path = ? AND cacheKey = ? + ) + `,[item.path, item.cacheKey]); await db.run("DELETE FROM fts_metadata WHERE path = ? AND cacheKey = ?", [ item.path, item.cacheKey, ]); - - await db.run("DELETE FROM fts WHERE path = ?", [item.path]); - await markComplete([item], IndexResultType.Delete); } } diff --git a/core/indexing/LanceDbIndex.test.ts b/core/indexing/LanceDbIndex.test.ts index d8a7c9852..ac6ed3591 100644 --- a/core/indexing/LanceDbIndex.test.ts +++ b/core/indexing/LanceDbIndex.test.ts @@ -34,11 +34,11 @@ describe.skip("ChunkCodebaseIndex", () => { throw new Error("No embeddings model selected"); } - index = new LanceDbIndex( + index = (await LanceDbIndex.create( mockConfig.selectedModelByRole.embed, testIde.readFile.bind(testIde), testContinueServerClient, - ); + ))!; sqliteDb = await SqliteDb.get(); lanceDb = await lance.connect(getLanceDbPath()); diff --git a/core/indexing/LanceDbIndex.ts b/core/indexing/LanceDbIndex.ts index 077b2ace0..2b2f23a77 100644 --- a/core/indexing/LanceDbIndex.ts +++ b/core/indexing/LanceDbIndex.ts @@ -1,30 +1,31 @@ -// NOTE: vectordb requirement must be listed in extensions/vscode to avoid error import { RunResult } from "sqlite3"; import { v4 as uuidv4 } from "uuid"; -import lance, { Table } from "vectordb"; -import { IContinueServerClient } from "../continueServer/interface.js"; +import { isSupportedLanceDbCpuTargetForLinux } from "../config/util"; +import { IContinueServerClient } from "../continueServer/interface"; import { BranchAndDir, Chunk, ILLM, IndexTag, IndexingProgressUpdate, -} from "../index.js"; -import { getLanceDbPath, migrate } from "../util/paths.js"; +} from "../index"; +import { getLanceDbPath, migrate } from "../util/paths"; +import { getUriPathBasename } from "../util/uri"; -import { chunkDocument, shouldChunk } from "./chunk/chunk.js"; -import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex.js"; +import { chunkDocument, shouldChunk } from "./chunk/chunk"; +import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex"; import { CodebaseIndex, IndexResultType, MarkCompleteCallback, PathAndCacheKey, RefreshIndexResults, -} from "./types.js"; -import { getUriPathBasename } from "../util/uri.js"; +} from "./types"; + +import type * as LanceType from "vectordb"; +import { localPathToUri } from "../util/pathToUri"; -// LanceDB converts to lowercase, so names must all be lowercase interface LanceDbRow { uuid: string; path: string; @@ -38,16 +39,53 @@ type ItemWithChunks = { item: PathAndCacheKey; chunks: Chunk[] }; type ChunkMap = Map; export class LanceDbIndex implements CodebaseIndex { + private static lance: typeof LanceType | null = null; + relativeExpectedTime: number = 13; get artifactId(): string { return `vectordb::${this.embeddingsProvider?.embeddingId}`; } - constructor( - private readonly embeddingsProvider: ILLM | null, + /** + * Factory method for creating LanceDbIndex instances. + * + * We dynamically import LanceDB only when supported to avoid native module loading errors + * on incompatible platforms. LanceDB has CPU-specific native dependencies that can crash + * the application if loaded on unsupported architectures. + * + * See isSupportedLanceDbCpuTargetForLinux() for platform compatibility details. + */ + static async create( + embeddingsProvider: ILLM, + readFile: (filepath: string) => Promise, + continueServerClient?: IContinueServerClient, + ): Promise { + if (!isSupportedLanceDbCpuTargetForLinux()) { + return null; + } + + try { + this.lance = await import("vectordb"); + return new LanceDbIndex( + embeddingsProvider, + readFile, + continueServerClient, + ); + } catch (err) { + console.error("Failed to load LanceDB:", err); + return null; + } + } + + private constructor( + private readonly embeddingsProvider: ILLM, private readonly readFile: (filepath: string) => Promise, private readonly continueServerClient?: IContinueServerClient, - ) {} + ) { + if (!LanceDbIndex.lance) { + throw new Error("LanceDB not initialized"); + } + } tableNameForTag(tag: IndexTag) { return tagToString(tag).replace(/[^\w-_.]/g, ""); @@ -97,12 +135,10 @@ export class LanceDbIndex implements CodebaseIndex { ); const embeddings = await this.getEmbeddings(allChunks); - // Remove undefined embeddings and their corresponding chunks for (let i = embeddings.length - 1; i >= 0; i--) { if (embeddings[i] === undefined) { const chunk = allChunks[i]; const chunks = chunkMap.get(chunk.filepath)?.chunks; - if (chunks) { const index = chunks.findIndex((c) => c === chunk); if (index !== -1) { @@ -210,6 +246,7 @@ export class LanceDbIndex implements CodebaseIndex { markComplete: MarkCompleteCallback, repoName: string | undefined, ): AsyncGenerator { + const lance = LanceDbIndex.lance!; const sqliteDb = await SqliteDb.get(); await this.createSqliteCacheTable(sqliteDb); @@ -217,15 +254,13 @@ export class LanceDbIndex implements CodebaseIndex { const lanceDb = await lance.connect(getLanceDbPath()); const existingLanceTables = await lanceDb.tableNames(); - let lanceTable: Table | undefined = undefined; + let lanceTable: LanceType.Table | undefined = undefined; let needToCreateLanceTable = !existingLanceTables.includes(lanceTableName); - // Compute const addComputedLanceDbRows = async ( pathAndCacheKeys: PathAndCacheKey[], computedRows: LanceDbRow[], ) => { - // Create table if needed, add computed rows if (lanceTable) { if (computedRows.length > 0) { await lanceTable.add(computedRows); @@ -241,11 +276,9 @@ export class LanceDbIndex implements CodebaseIndex { needToCreateLanceTable = false; } - // Mark item complete await markComplete(pathAndCacheKeys, IndexResultType.Compute); }; - // Check remote cache if (this.continueServerClient?.connected) { try { const keys = results.compute.map(({ cacheKey }) => cacheKey); @@ -255,7 +288,6 @@ export class LanceDbIndex implements CodebaseIndex { repoName, ); for (const [cacheKey, chunks] of Object.entries(resp.files)) { - // Get path for cacheKey const path = results.compute.find( (item) => item.cacheKey === cacheKey, )?.path; @@ -267,7 +299,6 @@ export class LanceDbIndex implements CodebaseIndex { continue; } - // Build LanceDbRow objects const rows: LanceDbRow[] = []; for (const chunk of chunks) { const row = { @@ -294,7 +325,6 @@ export class LanceDbIndex implements CodebaseIndex { await addComputedLanceDbRows([{ cacheKey, path }], rows); } - // Remove items that don't need to be recomputed results.compute = results.compute.filter( (item) => !resp.files[item.cacheKey], ); @@ -316,12 +346,10 @@ export class LanceDbIndex implements CodebaseIndex { await addComputedLanceDbRows(results.compute, dbRows); let accumulatedProgress = 0; - // Add tag - retrieve the computed info from lance sqlite cache for (const { path, cacheKey } of results.addTag) { const stmt = await sqliteDb.prepare( - "SELECT * FROM lance_db_cache WHERE cacheKey = ? AND path = ? AND artifact_id = ?", + "SELECT * FROM lance_db_cache WHERE cacheKey = ? AND artifact_id = ?", cacheKey, - path, this.artifactId, ); const cachedItems = await stmt.all(); @@ -360,7 +388,6 @@ export class LanceDbIndex implements CodebaseIndex { }; } - // Delete or remove tag - remove from lance table) if (!needToCreateLanceTable) { const toDel = [...results.removeTag, ...results.del]; @@ -369,7 +396,6 @@ export class LanceDbIndex implements CodebaseIndex { } for (const { path, cacheKey } of toDel) { - // This is where the aforementioned lowercase conversion problem shows await lanceTable.delete( `cachekey = '${cacheKey}' AND path = '${path}'`, ); @@ -385,7 +411,6 @@ export class LanceDbIndex implements CodebaseIndex { await markComplete(results.removeTag, IndexResultType.RemoveTag); - // Delete - also remove from sqlite cache for (const { path, cacheKey } of results.del) { await sqliteDb.run( "DELETE FROM lance_db_cache WHERE cacheKey = ? AND path = ? AND artifact_id = ?", @@ -415,7 +440,7 @@ export class LanceDbIndex implements CodebaseIndex { n: number, directory: string | undefined, vector: number[], - db: any, /// lancedb.Connection + db: any, ): Promise { const tableName = this.tableNameForTag(tag); const tableNames = await db.tableNames(); @@ -427,7 +452,6 @@ export class LanceDbIndex implements CodebaseIndex { const table = await db.openTable(tableName); let query = table.search(vector); if (directory) { - // seems like lancedb is only post-filtering, so have to return a bunch of results and slice after query = query.where(`path LIKE '${directory}%'`).limit(300); } else { query = query.limit(n); @@ -442,6 +466,7 @@ export class LanceDbIndex implements CodebaseIndex { tags: BranchAndDir[], filterDirectory: string | undefined, ): Promise { + const lance = LanceDbIndex.lance!; if (!this.embeddingsProvider) { return []; } @@ -474,7 +499,7 @@ export class LanceDbIndex implements CodebaseIndex { return data.map((d) => { return { digest: d.cacheKey, - filepath: d.path, + filepath: localPathToUri(d.path), startLine: d.startLine, endLine: d.endLine, index: 0, diff --git a/core/indexing/chunk/ChunkCodebaseIndex.ts b/core/indexing/chunk/ChunkCodebaseIndex.ts index 1f6a45258..9b39e506a 100644 --- a/core/indexing/chunk/ChunkCodebaseIndex.ts +++ b/core/indexing/chunk/ChunkCodebaseIndex.ts @@ -80,9 +80,9 @@ export class ChunkCodebaseIndex implements CodebaseIndex { ` INSERT INTO chunk_tags (chunkId, tag) SELECT id, ? FROM chunks - WHERE cacheKey = ? AND path = ? + WHERE cacheKey = ? `, - [tagString, item.cacheKey, item.path], + [tagString, item.cacheKey], ); await markComplete([item], IndexResultType.AddTag); accumulatedProgress += 1 / results.addTag.length / 4; @@ -158,7 +158,8 @@ export class ChunkCodebaseIndex implements CodebaseIndex { id INTEGER PRIMARY KEY AUTOINCREMENT, tag TEXT NOT NULL, chunkId INTEGER NOT NULL, - FOREIGN KEY (chunkId) REFERENCES chunks (id) + FOREIGN KEY (chunkId) REFERENCES chunks (id), + UNIQUE (tag, chunkId) )`); } diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index 307e3c117..75f92b145 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -1,7 +1,6 @@ import { ConfigResult } from "@continuedev/config-yaml"; import { open, type Database } from "sqlite"; import sqlite3 from "sqlite3"; -import lancedb, { Connection } from "vectordb"; import { Chunk, @@ -14,7 +13,10 @@ import { SiteIndexingConfig, } from "../.."; import { ConfigHandler } from "../../config/ConfigHandler"; -import { addContextProvider } from "../../config/util"; +import { + addContextProvider, + isSupportedLanceDbCpuTargetForLinux, +} from "../../config/util"; import DocsContextProvider from "../../context/providers/DocsContextProvider"; import TransformersJsEmbeddingsProvider from "../../llm/llms/TransformersJsEmbeddingsProvider"; import { FromCoreProtocol, ToCoreProtocol } from "../../protocol"; @@ -43,6 +45,8 @@ import { } from "./preIndexed"; import preIndexedDocs from "./preIndexedDocs"; +import type * as LanceType from "vectordb"; + // Purposefully lowercase because lancedb converts export interface LanceDbDocsRow { title: string; @@ -81,6 +85,7 @@ export type AddParams = { - add/index one */ export default class DocsService { + private static lance: typeof LanceType | null = null; static lanceTableName = "docs"; static sqlitebTableName = "docs"; @@ -112,6 +117,22 @@ export default class DocsService { this.githubToken = token; } + private async initLanceDb() { + if (!isSupportedLanceDbCpuTargetForLinux()) { + return null; + } + + try { + if (!DocsService.lance) { + DocsService.lance = await import("vectordb"); + } + return DocsService.lance; + } catch (err) { + console.error("Failed to load LanceDB:", err); + return null; + } + } + // Singleton pattern: only one service globally private static instance?: DocsService; static createSingleton( @@ -988,7 +1009,7 @@ export default class DocsService { // Lance DB Initialization private async createLanceDocsTable( - connection: Connection, + connection: LanceType.Connection, initializationVector: number[], tableName: string, ) { @@ -1035,7 +1056,12 @@ export default class DocsService { initializationVector: number[]; startUrl: string; }) { - const conn = await lancedb.connect(getLanceDbPath()); + const lance = await this.initLanceDb(); + if (!lance) { + throw new Error("LanceDB not available on this platform"); + } + + const conn = await lance.connect(getLanceDbPath()); const tableNames = await conn.tableNames(); const { provider } = await this.getEmbeddingsProvider(startUrl); @@ -1157,8 +1183,13 @@ export default class DocsService { // Delete methods private async deleteEmbeddingsFromLance(startUrl: string) { + const lance = await this.initLanceDb(); + if (!lance) { + return; + } + for (const tableName of this.lanceTableNamesSet) { - const conn = await lancedb.connect(getLanceDbPath()); + const conn = await lance.connect(getLanceDbPath()); const table = await conn.openTable(tableName); await table.delete(`starturl = '${startUrl}'`); } diff --git a/core/indexing/docs/migrations.ts b/core/indexing/docs/migrations.ts index 38aa987b3..64e313175 100644 --- a/core/indexing/docs/migrations.ts +++ b/core/indexing/docs/migrations.ts @@ -1,5 +1,5 @@ import { type Database } from "sqlite"; -import { Table } from "vectordb"; +import { type Table } from "vectordb"; import { editConfigJson, migrate } from "../../util/paths.js"; diff --git a/core/indexing/ignore.ts b/core/indexing/ignore.ts index 6075bdb26..7f5e8a039 100644 --- a/core/indexing/ignore.ts +++ b/core/indexing/ignore.ts @@ -114,6 +114,10 @@ export const defaultIgnoreDir = ignore().add(DEFAULT_IGNORE_DIRS); export const DEFAULT_IGNORE = DEFAULT_IGNORE_FILETYPES.join("\n") + "\n" + DEFAULT_IGNORE_DIRS.join("\n"); +export const defaultIgnoreFileAndDir = ignore() + .add(defaultIgnoreFile) + .add(defaultIgnoreDir); + export function gitIgArrayFromFile(file: string) { return file .split(/\r?\n/) // Split on new line diff --git a/core/indexing/refreshIndex.ts b/core/indexing/refreshIndex.ts index 34c1ac4a2..ef21149b1 100644 --- a/core/indexing/refreshIndex.ts +++ b/core/indexing/refreshIndex.ts @@ -157,32 +157,64 @@ async function getAddRemoveForTag( const remove: PathAndCacheKey[] = []; const updateLastUpdated: PathAndCacheKey[] = []; - for (const item of saved) { - const { lastUpdated, ...pathAndCacheKey } = item; + // First, group items by path and find latest timestamp for each + const pathGroups = new Map + }>(); - if (files[item.path] === undefined) { - // Was indexed, but no longer exists. Remove - remove.push(pathAndCacheKey); + for (const item of saved) { + const { lastUpdated, path, cacheKey } = item; + + if (!pathGroups.has(path)) { + pathGroups.set(path, { + latest: { lastUpdated, cacheKey }, + allVersions: [{ cacheKey }] + }); + } else { + const group = pathGroups.get(path)!; + group.allVersions.push({ cacheKey }); + if (lastUpdated > group.latest.lastUpdated) { + group.latest = { lastUpdated, cacheKey }; + } + } + } + + // Now process each unique path + for (const [path, group] of pathGroups) { + if (files[path] === undefined) { + // Was indexed, but no longer exists. Remove all versions + for (const version of group.allVersions) { + remove.push({ path, cacheKey: version.cacheKey }); + } } else { // Exists in old and new, so determine whether it was updated - if (lastUpdated < files[item.path].lastModified) { + if (group.latest.lastUpdated < files[path].lastModified) { // Change was made after last update - const newHash = calculateHash(await readFile(pathAndCacheKey.path)); - if (pathAndCacheKey.cacheKey !== newHash) { + const newHash = calculateHash(await readFile(path)); + if (group.latest.cacheKey !== newHash) { updateNewVersion.push({ - path: pathAndCacheKey.path, + path, cacheKey: newHash, }); - updateOldVersion.push(pathAndCacheKey); + for (const version of group.allVersions) { + updateOldVersion.push({ path, cacheKey: version.cacheKey }); + } } else { - updateLastUpdated.push(pathAndCacheKey); + // File contents did not change + updateLastUpdated.push({ path, cacheKey: group.latest.cacheKey }); + for (const version of group.allVersions) { + if (version.cacheKey !== group.latest.cacheKey) { + updateOldVersion.push({ path, cacheKey: version.cacheKey }); + } + } } } else { // Already updated, do nothing } - // Remove so we can check leftovers afterward - delete files[item.path]; + // Remove path, so that only newly created paths remain + delete files[path]; } } diff --git a/core/indexing/shouldIgnore.test.ts b/core/indexing/shouldIgnore.test.ts new file mode 100644 index 000000000..c1935e7d9 --- /dev/null +++ b/core/indexing/shouldIgnore.test.ts @@ -0,0 +1,167 @@ +// Generated by continue + +import { testIde } from "../test/fixtures"; +import { + TEST_DIR, + addToTestDir, + setUpTestDir, + tearDownTestDir, +} from "../test/testDir"; + +import { shouldIgnore } from "./shouldIgnore"; + +// Test for the shouldIgnore function +describe("shouldIgnore", () => { + beforeEach(() => { + setUpTestDir(); + }); + + afterEach(() => { + tearDownTestDir(); + }); + + test("should return true if a file is ignored by .gitignore", async () => { + addToTestDir([ + ["ignored-file.txt", "content"], + [".gitignore", "ignored-file.txt"], + ]); + const result = await shouldIgnore(TEST_DIR + "/ignored-file.txt", testIde, [ + TEST_DIR, + ]); + expect(result).toBe(true); + }); + test("should return true if a folder is ignored by .continueignore", async () => { + addToTestDir([ + ["ignored-folder/file.txt", "content"], + [".continueignore", "ignored-folder/"], + ]); + const result = await shouldIgnore( + TEST_DIR + "/ignored-folder/file.txt", + testIde, + [TEST_DIR], + ); + expect(result).toBe(true); + }); + test("should return false if a file is not ignored", async () => { + addToTestDir([["kept-file.txt", "contents"]]); + const result = await shouldIgnore(TEST_DIR + "/kept-file.txt", testIde, [ + TEST_DIR, + ]); + expect(result).toBe(false); + }); + test("should return true if a file is ignored by .gitignore with spaces in file name", async () => { + addToTestDir([ + ["ignored file.txt", "content"], + [".gitignore", "ignored file.txt"], + ]); + const result = await shouldIgnore(TEST_DIR + "/ignored file.txt", testIde, [ + TEST_DIR, + ]); + expect(result).toBe(true); + }); + + test("should return true if a .continueignore override ignores file", async () => { + addToTestDir([ + ["override-file.txt", "content"], + [".gitignore", "override-file.txt"], + [".continueignore", "!override-file.txt"], + ]); + const result = await shouldIgnore( + TEST_DIR + "/override-file.txt", + testIde, + [TEST_DIR], + ); + expect(result).toBe(false); + }); + + test("should return true for deeply nested file ignored by ignore files at multiple levels", async () => { + addToTestDir([ + ["level1/level2/level3/ignored-file.txt", "content"], + ["level1/.gitignore", "level2/"], + ["level1/level2/.continueignore", "level3/"], + ]); + const result = await shouldIgnore( + TEST_DIR + "/level1/level2/level3/ignored-file.txt", + testIde, + [TEST_DIR], + ); + expect(result).toBe(true); + }); + + test("should return false if a file with spaces is not ignored", async () => { + addToTestDir([["kept file.txt", "contents"]]); + const result = await shouldIgnore(TEST_DIR + "/kept file.txt", testIde, [ + TEST_DIR, + ]); + expect(result).toBe(false); + }); + + test("should handle multiple levels of directories with some files ignored", async () => { + addToTestDir([ + ["nested/dir1/.gitignore", "ignored.txt"], + ["nested/dir1/ignored.txt", "content"], + ["nested/dir2/kept.txt", "content"], + ]); + const ignoredResult = await shouldIgnore( + TEST_DIR + "/nested/dir1/ignored.txt", + testIde, + [TEST_DIR], + ); + expect(ignoredResult).toBe(true); + + const keptResult = await shouldIgnore( + TEST_DIR + "/nested/dir2/kept.txt", + testIde, + [TEST_DIR], + ); + expect(keptResult).toBe(false); + }); + + test("should respect default file and folder ignores top level", async () => { + addToTestDir([ + [".env", "contents"], + ["go.sum", "contents"], + ".idea/", + [".idea/test.xml", "contents"], + ]); + let result = await shouldIgnore(TEST_DIR + "/.env", testIde, [TEST_DIR]); + expect(result).toBe(true); + + result = await shouldIgnore(TEST_DIR + "/go.sum", testIde, [TEST_DIR]); + expect(result).toBe(true); + + result = await shouldIgnore(TEST_DIR + "/.idea", testIde, [TEST_DIR]); + expect(result).toBe(true); + + result = await shouldIgnore(TEST_DIR + "/.idea/test.xml", testIde, [ + TEST_DIR, + ]); + expect(result).toBe(true); + }); + + test("should respect default file and folder ignores at nested level", async () => { + addToTestDir([ + "nested/.idea/test.xml", + ["nested/.env", "contents"], + ["nested/go.sum", "contents"], + ]); + + let result = await shouldIgnore(TEST_DIR + "/nested/.idea", testIde, [ + TEST_DIR, + ]); + expect(result).toBe(true); + + result = await shouldIgnore(TEST_DIR + "/nested/.idea/test.xml", testIde, [ + TEST_DIR, + ]); + expect(result).toBe(true); + + result = await shouldIgnore(TEST_DIR + "/nested/.env", testIde, [TEST_DIR]); + expect(result).toBe(true); + + result = await shouldIgnore(TEST_DIR + "/nested/go.sum", testIde, [ + TEST_DIR, + ]); + expect(result).toBe(true); + }); +}); diff --git a/core/indexing/shouldIgnore.ts b/core/indexing/shouldIgnore.ts new file mode 100644 index 000000000..dd82a0457 --- /dev/null +++ b/core/indexing/shouldIgnore.ts @@ -0,0 +1,73 @@ +import ignore from "ignore"; +import type { FileType, IDE } from "../"; +import { findUriInDirs, getUriPathBasename } from "../util/uri"; +import { defaultIgnoreFileAndDir, getGlobalContinueIgArray } from "./ignore"; +import { getIgnoreContext } from "./walkDir"; + +/* + Process: + 1. Check global/default ignores + 2. Walk UP tree from file, checking ignores at each level + + TODO there might be issues with symlinks here +*/ +export async function shouldIgnore( + fileUri: string, + ide: IDE, + rootDirCandidates?: string[], +): Promise { + const rootDirUris = rootDirCandidates ?? (await ide.getWorkspaceDirs()); + const { foundInDir: rootDir, uri } = findUriInDirs(fileUri, rootDirUris); + + if (!rootDir) { + return true; + } + + const defaultAndGlobalIgnores = ignore() + .add(defaultIgnoreFileAndDir) + .add(getGlobalContinueIgArray()); + + let currentDir = uri; + let directParent = true; + let fileType = 1 as FileType.File as FileType; + while (currentDir !== rootDir) { + // Go to parent dir of file + const splitUri = currentDir.split("/"); + splitUri.pop(); + currentDir = splitUri.join("/"); + + // Get all files in the dir + const dirEntries = await ide.listDir(currentDir); + + // Check if the file is a symbolic link, ignore if so + if (directParent) { + directParent = false; + const baseName = getUriPathBasename(fileUri); + const entry = dirEntries.find(([name, _]) => name === baseName); + if (entry) { + fileType = entry[1]; + if (fileType === (64 as FileType.SymbolicLink)) { + return true; + } + } + } + + const ignoreContext = await getIgnoreContext( + currentDir, + dirEntries, + ide, + defaultAndGlobalIgnores, + ); + + let relativePath = uri.substring(currentDir.length + 1); + if (fileType === (2 as FileType.Directory)) { + relativePath += "/"; + } + + if (ignoreContext.ignores(relativePath)) { + return true; + } + } + + return false; +} diff --git a/core/indexing/walkDir.test.ts b/core/indexing/walkDir.test.ts index 8a9d26e7e..50d21c778 100644 --- a/core/indexing/walkDir.test.ts +++ b/core/indexing/walkDir.test.ts @@ -1,14 +1,14 @@ // Generated by continue -import { testIde } from "../test/fixtures"; -import { - setUpTestDir, - tearDownTestDir, - addToTestDir, - TEST_DIR_PATH, -} from "../test/testDir"; -import { walkDir, walkDirAsync, walkDirs } from "../indexing/walkDir"; import fs from "fs"; import path from "path"; +import { walkDir, walkDirAsync, walkDirs } from "../indexing/walkDir"; +import { testIde } from "../test/fixtures"; +import { + addToTestDir, + setUpTestDir, + tearDownTestDir, + TEST_DIR_PATH, +} from "../test/testDir"; describe("walkDir functions", () => { beforeEach(async () => { @@ -19,6 +19,27 @@ describe("walkDir functions", () => { tearDownTestDir(); }); + // describe.only("test speed", () => { + // it("should walk a simple directory structure", async () => { + // addToTestDir([ + // "src/", + // ["src/file1.ts", "content1"], + // ["src/file2.ts", "content2"], + // "src/nested/", + // ["src/nested/file3.ts", "content3"], + // ]); + + // const dir = await testIde.getWorkspaceDirs(); + + // const start = Date.now(); + // for (let i = 0; i < 10000; i++) { + // await walkDir(dir[0], testIde); + // } + // const passed = Date.now() - start; + // console.log(`Test took ${passed} ms`); + // }); + // }); + describe("walkDir", () => { it("should walk a simple directory structure", async () => { addToTestDir([ @@ -171,12 +192,7 @@ describe("walkDir functions", () => { it("should skip symlinks", async () => { const filePath = path.join(TEST_DIR_PATH, "real.ts"); addToTestDir([["real.ts", "content"]]); - fs.symlink( - filePath, - path.join(TEST_DIR_PATH, "symlink.ts"), - "file", - () => {}, - ); + fs.symlinkSync(filePath, path.join(TEST_DIR_PATH, "symlink.ts"), "file"); const files = await walkDirs(testIde); @@ -313,6 +329,9 @@ describe("walkDir functions", () => { ["node_modules/package/index.js", "content"], ["dist/bundle.js", "content"], ["coverage/lcov.env", "content"], + ["nested/node_modules/package/index.js", "content"], + ["nested/dist/bundle.js", "content"], + ["nested/coverage/lcov.env", "content"], ]); const files = await walkDir( @@ -327,6 +346,9 @@ describe("walkDir functions", () => { expect(files).not.toContain(".git/config"); expect(files).not.toContain("node_modules/package/index.js"); expect(files).not.toContain("coverage/lcov.info"); + expect(files).not.toContain("nested/node_modules/package/index.js"); + expect(files).not.toContain("nested/dist/bundle.js"); + expect(files).not.toContain("nested/coverage/lcov.env"); }); it("should handle directory-specific ignore patterns correctly", async () => { diff --git a/core/indexing/walkDir.ts b/core/indexing/walkDir.ts index 4e97e01d4..757163d96 100644 --- a/core/indexing/walkDir.ts +++ b/core/indexing/walkDir.ts @@ -2,27 +2,23 @@ import ignore, { Ignore } from "ignore"; import type { FileType, IDE } from ".."; +import { joinPathsToUri } from "../util/uri"; import { - DEFAULT_IGNORE_DIRS, - DEFAULT_IGNORE_FILETYPES, - defaultIgnoreDir, - defaultIgnoreFile, + defaultIgnoreFileAndDir, getGlobalContinueIgArray, gitIgArrayFromFile, } from "./ignore"; -import { joinPathsToUri } from "../util/uri"; export interface WalkerOptions { - ignoreFiles?: string[]; onlyDirs?: boolean; returnRelativeUrisPaths?: boolean; - additionalIgnoreRules?: string[]; } type Entry = [string, FileType]; // helper struct used for the DFS walk type WalkableEntry = { + name: string; relativeUriPath: string; uri: string; type: FileType; @@ -41,143 +37,110 @@ type IgnoreContext = { }; class DFSWalker { - private readonly ignoreFileNames: Set; - constructor( private readonly uri: string, private readonly ide: IDE, private readonly options: WalkerOptions, - ) { - this.ignoreFileNames = new Set(options.ignoreFiles); - } + ) {} // walk is a depth-first search implementation public async *walk(): AsyncGenerator { - const root = this.newRootWalkContext(); - const stack = [root]; - for (let cur = stack.pop(); cur; cur = stack.pop()) { - const walkableEntries = await this.listDirForWalking(cur.walkableEntry); - const ignoreContexts = await this.getIgnoreToApplyInDir( - cur, - walkableEntries, - ); - for (const w of walkableEntries) { - if (!this.shouldInclude(w, ignoreContexts)) { - continue; - } - if (this.entryIsDirectory(w.entry)) { - stack.push({ - walkableEntry: w, - ignoreContexts: ignoreContexts, - }); - if (this.options.onlyDirs) { - // when onlyDirs is enabled the walker will only return directory names - if (this.options.returnRelativeUrisPaths) { - yield w.relativeUriPath; - } else { - yield w.uri; - } - } - } else { - // Note that shouldInclude handles skipping files if options.onlyDirs is true - if (this.options.returnRelativeUrisPaths) { - yield w.relativeUriPath; - } else { - yield w.uri; - } - } - } - } - } + const defaultAndGlobalIgnores = ignore() + .add(defaultIgnoreFileAndDir) + .add(getGlobalContinueIgArray()); - private newRootWalkContext(): WalkContext { - const globalIgnoreFile = getGlobalContinueIgArray(); - return { + const rootContext: WalkContext = { walkableEntry: { + name: "", relativeUriPath: "", uri: this.uri, type: 2 as FileType.Directory, entry: ["", 2 as FileType.Directory], }, - ignoreContexts: [ + ignoreContexts: [], + }; + const stack = [rootContext]; + + for (let cur = stack.pop(); cur; cur = stack.pop()) { + // Only directories will be added to the stack + const entries = await this.ide.listDir(cur.walkableEntry.uri); + + const newIgnore = await getIgnoreContext( + cur.walkableEntry.uri, + entries, + this.ide, + defaultAndGlobalIgnores, + ); + + const ignoreContexts = [ + ...cur.ignoreContexts, { - ignore: ignore() - .add(defaultIgnoreDir) - .add(defaultIgnoreFile) - .add(globalIgnoreFile), - dirname: "", + ignore: newIgnore, + dirname: cur.walkableEntry.relativeUriPath, }, - ], - }; - } + ]; - private async listDirForWalking( - walkableEntry: WalkableEntry, - ): Promise { - const entries = await this.ide.listDir(walkableEntry.uri); - return entries.map((e) => ({ - relativeUriPath: `${walkableEntry.relativeUriPath}${walkableEntry.relativeUriPath ? "/" : ""}${e[0]}`, - uri: joinPathsToUri(walkableEntry.uri, e[0]), - type: e[1], - entry: e, - })); - } + for (const entry of entries) { + if (this.entryIsSymlink(entry)) { + // If called from the root, a symlink either links to a real file in this repository, + // and therefore will be walked OR it links to something outside of the repository and + // we do not want to index it + continue; + } + const walkableEntry = { + name: entry[0], + relativeUriPath: `${cur.walkableEntry.relativeUriPath}${cur.walkableEntry.relativeUriPath ? "/" : ""}${entry[0]}`, + uri: joinPathsToUri(cur.walkableEntry.uri, entry[0]), + type: entry[1], + entry: entry, + }; - private async getIgnoreToApplyInDir( - curDir: WalkContext, - entriesInDir: WalkableEntry[], - ): Promise { - const ignoreFilesInDir = await this.loadIgnoreFiles(entriesInDir); - if (ignoreFilesInDir.length === 0) { - return curDir.ignoreContexts; - } - const patterns = ignoreFilesInDir.map((c) => gitIgArrayFromFile(c)).flat(); - const newIgnoreContext = { - ignore: ignore().add(patterns), - dirname: curDir.walkableEntry.relativeUriPath, - }; - return [...curDir.ignoreContexts, newIgnoreContext]; - } + let relPath = walkableEntry.relativeUriPath; + if (this.entryIsDirectory(entry)) { + relPath = `${relPath}/`; + } else { + if (this.options.onlyDirs) { + continue; + } + } + let shouldInclude = true; + for (const ig of ignoreContexts) { + // remove the directory name and path separator from the match path, unless this an ignore file + // in the root directory + const prefixLength = + ig.dirname.length === 0 ? 0 : ig.dirname.length + 1; + // The ignore library expects a path relative to the ignore file location + const matchPath = relPath.substring(prefixLength); + if (ig.ignore.ignores(matchPath)) { + shouldInclude = false; + } + } + if (!shouldInclude) { + continue; + } - private async loadIgnoreFiles(entries: WalkableEntry[]): Promise { - const ignoreEntries = entries.filter((w) => - this.entryIsIgnoreFile(w.entry), - ); - const promises = ignoreEntries.map(async (w) => { - return await this.ide.readFile(w.uri); - }); - return Promise.all(promises); - } - - private shouldInclude( - walkableEntry: WalkableEntry, - ignoreContexts: IgnoreContext[], - ) { - if (this.entryIsSymlink(walkableEntry.entry)) { - // If called from the root, a symlink either links to a real file in this repository, - // and therefore will be walked OR it links to something outside of the repository and - // we do not want to index it - return false; - } - let relPath = walkableEntry.relativeUriPath; - if (this.entryIsDirectory(walkableEntry.entry)) { - relPath = `${relPath}/`; - } else { - if (this.options.onlyDirs) { - return false; + if (this.entryIsDirectory(entry)) { + stack.push({ + walkableEntry, + ignoreContexts, + }); + if (this.options.onlyDirs) { + // when onlyDirs is enabled the walker will only return directory names + if (this.options.returnRelativeUrisPaths) { + yield walkableEntry.relativeUriPath; + } else { + yield walkableEntry.uri; + } + } + } else { + if (this.options.returnRelativeUrisPaths) { + yield walkableEntry.relativeUriPath; + } else { + yield walkableEntry.uri; + } + } } } - for (const ig of ignoreContexts) { - // remove the directory name and path separator from the match path, unless this an ignore file - // in the root directory - const prefixLength = ig.dirname.length === 0 ? 0 : ig.dirname.length + 1; - // The ignore library expects a path relative to the ignore file location - const matchPath = relPath.substring(prefixLength); - if (ig.ignore.ignores(matchPath)) { - return false; - } - } - return true; } private entryIsDirectory(entry: Entry) { @@ -187,21 +150,9 @@ class DFSWalker { private entryIsSymlink(entry: Entry) { return entry[1] === (64 as FileType.SymbolicLink); } - - private entryIsIgnoreFile(e: Entry): boolean { - if ( - e[1] === (2 as FileType.Directory) || - e[1] === (64 as FileType.SymbolicLink) - ) { - return false; - } - return this.ignoreFileNames.has(e[0]); - } } const defaultOptions: WalkerOptions = { - ignoreFiles: [".gitignore", ".continueignore"], - additionalIgnoreRules: [...DEFAULT_IGNORE_DIRS, ...DEFAULT_IGNORE_FILETYPES], onlyDirs: false, returnRelativeUrisPaths: false, }; @@ -238,3 +189,49 @@ export async function walkDirs( ); return results.flat(); } + +export async function getIgnoreContext( + currentDir: string, + currentDirEntries: Entry[], + ide: IDE, + defaultAndGlobalIgnores: Ignore, +) { + const dirFiles = currentDirEntries + .filter(([_, entryType]) => entryType === (1 as FileType.File)) + .map(([name, _]) => name); + + // Find ignore files and get ignore arrays from their contexts + // These are done separately so that .continueignore can override .gitignore + const gitIgnoreFile = dirFiles.find((name) => name === ".gitignore"); + const continueIgnoreFile = dirFiles.find( + (name) => name === ".continueignore", + ); + + const getGitIgnorePatterns = async () => { + if (gitIgnoreFile) { + const contents = await ide.readFile(`${currentDir}/.gitignore`); + return gitIgArrayFromFile(contents); + } + return []; + }; + const getContinueIgnorePatterns = async () => { + if (continueIgnoreFile) { + const contents = await ide.readFile(`${currentDir}/.continueignore`); + return gitIgArrayFromFile(contents); + } + return []; + }; + + const ignoreArrays = await Promise.all([ + getGitIgnorePatterns(), + getContinueIgnorePatterns(), + ]); + + // Note precedence here! + const ignoreContext = ignore() + .add(ignoreArrays[0]) // gitignore + .add(defaultAndGlobalIgnores) // default file/folder ignores followed by global .continueignore - this is combined for speed + .add(ignoreArrays[1]); // local .continueignore + + return ignoreContext; +} diff --git a/core/llm/autodetect.ts b/core/llm/autodetect.ts index 6b9884c21..4fe864bfc 100644 --- a/core/llm/autodetect.ts +++ b/core/llm/autodetect.ts @@ -71,6 +71,7 @@ const PROVIDER_SUPPORTS_IMAGES: string[] = [ "sagemaker", "continue-proxy", "openrouter", + "sambanova", "vertexai", "azure", "scaleway", @@ -92,6 +93,7 @@ const MODEL_SUPPORTS_IMAGES: string[] = [ "haiku", "pixtral", "llama3.2", + "llama-3.2", ]; function modelSupportsTools(modelDescription: ModelDescription) { diff --git a/core/llm/index.ts b/core/llm/index.ts index e9724d8d4..8ed1a3d07 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -19,6 +19,7 @@ import { LLMFullCompletionOptions, LLMOptions, ModelCapability, + ModelInstaller, PromptLog, PromptTemplate, RequestOptions, @@ -58,6 +59,17 @@ import { toFimBody, } from "./openaiTypeConverters.js"; + +export class LLMError extends Error { + constructor(message: string, public llm: ILLM) { + super(message); + } +} + +export function isModelInstaller(provider: any): provider is ModelInstaller { + return provider && typeof provider.installModel === 'function'; +} + export abstract class BaseLLM implements ILLM { static providerName: string; static defaultOptions: Partial | undefined = undefined; @@ -380,9 +392,11 @@ export abstract class BaseLLM implements ILLM { if (!resp.ok) { let text = await resp.text(); if (resp.status === 404 && !resp.url.includes("/v1")) { - if (text.includes("try pulling it first")) { - const model = JSON.parse(text).error.split(" ")[1].slice(1, -1); + const error = JSON.parse(text)?.error?.replace(/"/g, "'"); + let model = error?.match(/model '(.*)' not found/)?.[1]; + if (model && resp.url.match("127.0.0.1:11434")) { text = `The model "${model}" was not found. To download it, run \`ollama run ${model}\`.`; + throw new LLMError(text, this);// No need to add HTTP status details } else if (text.includes("/api/chat")) { text = "The /api/chat endpoint was not found. This may mean that you are using an older version of Ollama that does not support /api/chat. Upgrading to the latest version will solve the issue."; @@ -442,6 +456,10 @@ export abstract class BaseLLM implements ILLM { throw new Error(message); } } + //if e instance of LLMError, rethrow + if (e instanceof LLMError) { + throw e; + } throw new Error(e.message); } }; @@ -764,6 +782,7 @@ export abstract class BaseLLM implements ILLM { let thinking = ""; let completion = ""; + let citations: null | string[] = null try { if (this.templateMessages) { @@ -791,6 +810,8 @@ export abstract class BaseLLM implements ILLM { completion = renderChatMessage(msg); } else { // Stream true + console.log("Streaming"); + const stream = this.openaiAdapter.chatCompletionStream( { ...body, @@ -803,6 +824,9 @@ export abstract class BaseLLM implements ILLM { if (result) { yield result; } + if (!citations && (chunk as any).citations && Array.isArray((chunk as any).citations)) { + citations = (chunk as any).citations; + } } } } else { @@ -845,6 +869,10 @@ export abstract class BaseLLM implements ILLM { requests when not using tools, so it's the simplest option to always add to history. */ await this.writeLog(`Completion:\n${completion}\n\n`); + + if (citations) { + await this.writeLog(`Citations:\n${citations.map((c, i) => `${i + 1}: ${c}`).join("\n")}\n\n`); + } } return { diff --git a/core/llm/llm.test.ts b/core/llm/llm.test.ts index 9912b862e..ff897d5a3 100644 --- a/core/llm/llm.test.ts +++ b/core/llm/llm.test.ts @@ -205,10 +205,11 @@ describe("LLM", () => { }); testLLM( new OpenAI({ apiKey: process.env.OPENAI_API_KEY, model: "o1-preview" }), - { skip: false, timeout: 20000 }, + { skip: false, timeout: 60000 }, ); testLLM(new OpenAI({ apiKey: process.env.OPENAI_API_KEY, model: "o1" }), { skip: false, + timeout: 60000, }); testLLM( new Gemini({ diff --git a/core/llm/llms/Bedrock.test.ts b/core/llm/llms/Bedrock.test.ts new file mode 100644 index 000000000..d39246fa5 --- /dev/null +++ b/core/llm/llms/Bedrock.test.ts @@ -0,0 +1,375 @@ +import { BedrockRuntimeClient } from "@aws-sdk/client-bedrock-runtime"; +import { fromIni } from "@aws-sdk/credential-providers"; +import Bedrock from "./Bedrock.js"; +import { ChatMessage, Chunk, CompletionOptions, UserChatMessage } from "../../index.js"; + +// Mock AWS SDK +jest.mock("@aws-sdk/client-bedrock-runtime", () => ({ + BedrockRuntimeClient: jest.fn().mockImplementation(() => ({ + send: jest.fn(), + middlewareStack: { add: jest.fn() }, + })), + ConverseStreamCommand: jest.fn(), + InvokeModelCommand: jest.fn(), +})); + +// Mock credential provider +jest.mock("@aws-sdk/credential-providers", () => ({ + fromIni: jest.fn().mockImplementation(() => async () => ({ + accessKeyId: "test-access-key", + secretAccessKey: "test-secret-key", + sessionToken: "test-session-token", + })), +})); + +// Extend CompletionOptions for testing +interface TestCompletionOptions extends CompletionOptions { + mockError?: string; + mockToolUse?: boolean; +} + +// Create a test class that overrides the protected methods +class TestBedrock extends Bedrock { + // Make _streamChat public for testing + public async *streamChat( + messages: ChatMessage[], + signal: AbortSignal, + options: TestCompletionOptions + ): AsyncGenerator { + if (options.mockError) { + throw new Error(options.mockError); + } + + if (options.mockToolUse) { + yield { + role: "assistant", + content: "", + toolCalls: [{ + id: "tool-1", + type: "function", + function: { + name: "test_tool", + arguments: '{"arg1":"value1"}' + } + }], + }; + return; + } + + yield { role: "assistant", content: "Hello" }; + yield { role: "assistant", content: " world" }; + } + + // Override embed to avoid making real API calls + async embed(chunks: string[]): Promise { + if (chunks[0] === "error") { + throw new Error("Embedding Error"); + } + return [[0.1, 0.2, 0.3]]; + } + + // Override rerank to avoid making real API calls + async rerank(query: string, chunks: Chunk[]): Promise { + if (!query || !chunks.length) { + throw new Error("Query and chunks must not be empty"); + } + + if (query === "error") { + throw new Error("Reranking Error"); + } + + return chunks.map((_, i) => 0.8 - i * 0.3); + } +} + +describe("Bedrock", () => { + beforeEach(() => { + jest.clearAllMocks(); + }); + + describe("constructor", () => { + it("should initialize with default options", () => { + const bedrock = new TestBedrock({ + apiKey: "test-key", + model: "anthropic.claude-3-sonnet-20240229-v1:0", + region: "us-east-1", + }); + + expect(bedrock.region).toBe("us-east-1"); + expect(bedrock.profile).toBe("bedrock"); + expect(bedrock.apiBase).toBe("https://bedrock-runtime.us-east-1.amazonaws.com"); + }); + + it("should use custom options when provided", () => { + const bedrock = new TestBedrock({ + apiKey: "test-key", + model: "anthropic.claude-3-sonnet-20240229-v1:0", + region: "us-west-2", + profile: "custom-profile", + apiBase: "https://custom-endpoint.amazonaws.com/", + }); + + expect(bedrock.region).toBe("us-west-2"); + expect(bedrock.profile).toBe("custom-profile"); + expect(bedrock.apiBase).toBe("https://custom-endpoint.amazonaws.com/"); + }); + }); + + describe("streamChat", () => { + let bedrock: TestBedrock; + const mockAbortSignal = new AbortController().signal; + const defaultOptions: TestCompletionOptions = { + model: "anthropic.claude-3-sonnet-20240229-v1:0", + }; + + beforeEach(() => { + bedrock = new TestBedrock({ + apiKey: "test-key", + model: "anthropic.claude-3-sonnet-20240229-v1:0", + region: "us-east-1", + }); + }); + + it("should handle text streaming correctly", async () => { + const messages: ChatMessage[] = [{ + role: "user", + content: "Hi" + } as UserChatMessage]; + + const results = []; + + for await (const message of bedrock.streamChat(messages, mockAbortSignal, defaultOptions)) { + results.push(message); + } + + expect(results).toEqual([ + { role: "assistant", content: "Hello" }, + { role: "assistant", content: " world" }, + ]); + }); + + it("should handle tool use streaming correctly", async () => { + const messages: ChatMessage[] = [{ + role: "user", + content: "Use a tool" + } as UserChatMessage]; + + const results = []; + const options: TestCompletionOptions = { + ...defaultOptions, + mockToolUse: true + }; + + for await (const message of bedrock.streamChat(messages, mockAbortSignal, options)) { + results.push(message); + } + + expect(results).toEqual([ + { + role: "assistant", + content: "", + toolCalls: [{ + id: "tool-1", + type: "function", + function: { + name: "test_tool", + arguments: '{"arg1":"value1"}' + } + }], + }, + ]); + }); + + it("should handle API errors", async () => { + const messages: ChatMessage[] = [{ + role: "user", + content: "Hi" + } as UserChatMessage]; + + const options: TestCompletionOptions = { + ...defaultOptions, + mockError: "API Error" + }; + + await expect(async () => { + for await (const _ of bedrock.streamChat(messages, mockAbortSignal, options)) { + // consume generator + } + }).rejects.toThrow("API Error"); + }); + }); + + describe("embed", () => { + let bedrock: TestBedrock; + + beforeEach(() => { + bedrock = new TestBedrock({ + apiKey: "test-key", + model: "cohere.embed-english-v3", + region: "us-east-1", + }); + }); + + it("should handle embedding requests correctly", async () => { + const result = await bedrock.embed(["test text"]); + expect(result).toEqual([[0.1, 0.2, 0.3]]); + }); + + it("should handle embedding errors", async () => { + await expect(bedrock.embed(["error"])).rejects.toThrow("Embedding Error"); + }); + }); + + describe("rerank", () => { + let bedrock: TestBedrock; + + beforeEach(() => { + bedrock = new TestBedrock({ + apiKey: "test-key", + model: "cohere.rerank-english-v2.0", + region: "us-east-1", + }); + }); + + it("should handle reranking requests correctly", async () => { + const chunks: Chunk[] = [ + { + content: "doc1", + digest: "digest1", + filepath: "file1", + index: 0, + startLine: 1, + endLine: 1 + }, + { + content: "doc2", + digest: "digest2", + filepath: "file2", + index: 1, + startLine: 1, + endLine: 1 + } + ]; + + const result = await bedrock.rerank("query", chunks); + expect(result).toEqual([0.8, 0.5]); + }); + + it("should handle reranking errors", async () => { + const chunk: Chunk = { + content: "doc1", + digest: "digest1", + filepath: "file1", + index: 0, + startLine: 1, + endLine: 1 + }; + + await expect( + bedrock.rerank("error", [chunk]) + ).rejects.toThrow("Reranking Error"); + }); + + it("should throw error for empty input", async () => { + await expect(bedrock.rerank("", [])).rejects.toThrow("Query and chunks must not be empty"); + }); + }); + + describe("message conversion", () => { + let bedrock: TestBedrock; + + beforeEach(() => { + bedrock = new TestBedrock({ + apiKey: "test-key", + model: "anthropic.claude-3-sonnet-20240229-v1:0", + region: "us-east-1", + }); + }); + + it("should convert text messages correctly", () => { + const message: ChatMessage = { + role: "user", + content: "Hello" + } as UserChatMessage; + const converted = bedrock["_convertMessage"](message); + expect(converted).toEqual({ + role: "user", + content: [{ text: "Hello" }], + }); + }); + + it("should convert tool responses correctly", () => { + const message: ChatMessage = { + role: "tool", + content: "Tool result", + toolCallId: "tool-1", + }; + const converted = bedrock["_convertMessage"](message); + expect(converted).toEqual({ + role: "user", + content: [{ + toolResult: { + toolUseId: "tool-1", + content: [{ text: "Tool result" }], + }, + }], + }); + }); + + it("should convert tool calls correctly", () => { + const message: ChatMessage = { + role: "assistant", + content: "", + toolCalls: [{ + id: "tool-1", + type: "function" as const, + function: { + name: "test_tool", + arguments: '{"arg":"value"}', + }, + }], + }; + const converted = bedrock["_convertMessage"](message); + expect(converted).toEqual({ + role: "assistant", + content: [{ + toolUse: { + toolUseId: "tool-1", + name: "test_tool", + input: { arg: "value" }, + }, + }], + }); + }); + + it("should handle multimodal content correctly", () => { + const message: ChatMessage = { + role: "user", + content: [ + { type: "text", text: "Look at this image:" }, + { + type: "imageUrl", + imageUrl: { + url: "data:image/jpeg;base64,/9j/4AAQSkZJRg==", + }, + }, + ], + } as UserChatMessage; + const converted = bedrock["_convertMessage"](message); + expect(converted).toEqual({ + role: "user", + content: [ + { text: "Look at this image:" }, + { + image: { + format: "jpeg", + source: { + bytes: Buffer.from("/9j/4AAQSkZJRg==", "base64"), + }, + }, + }, + ], + }); + }); + }); +}); diff --git a/core/llm/llms/Bedrock.ts b/core/llm/llms/Bedrock.ts index 17d2911b8..aa15997ad 100644 --- a/core/llm/llms/Bedrock.ts +++ b/core/llm/llms/Bedrock.ts @@ -10,16 +10,25 @@ import { Chunk, CompletionOptions, LLMOptions, - MessageContent, } from "../../index.js"; import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; +import { PROVIDER_TOOL_SUPPORT } from "../toolSupport.js"; interface ModelConfig { formatPayload: (text: string) => any; extractEmbeddings: (responseBody: any) => number[][]; } +/** + * Interface for tool use state tracking + */ +interface ToolUseState { + toolUseId: string; + name: string; + input: string; +} + class Bedrock extends BaseLLM { static providerName = "bedrock"; static defaultOptions: Partial = { @@ -29,6 +38,10 @@ class Bedrock extends BaseLLM { profile: "bedrock", }; + private _currentToolResponse: Partial | null = null; + + public requestOptions: { region?: string; credentials?: any; headers?: Record }; + constructor(options: LLMOptions) { super(options); if (!options.apiBase) { @@ -39,6 +52,10 @@ class Bedrock extends BaseLLM { } else { this.profile = "bedrock"; } + this.requestOptions = { + region: options.region, + headers: {}, + }; } protected async *_streamComplete( @@ -58,7 +75,6 @@ class Bedrock extends BaseLLM { options: CompletionOptions, ): AsyncGenerator { const credentials = await this._getCredentials(); - const client = new BedrockRuntimeClient({ region: this.region, endpoint: this.apiBase, @@ -70,9 +86,9 @@ class Bedrock extends BaseLLM { }); let config_headers = - this.requestOptions && this.requestOptions.headers - ? this.requestOptions.headers - : {}; + this.requestOptions && this.requestOptions.headers + ? this.requestOptions.headers + : {}; // AWS SigV4 requires strict canonicalization of headers. // DO NOT USE "_" in your header name. It will return an error like below. // "The request signature we calculated does not match the signature you provided." @@ -90,32 +106,116 @@ class Bedrock extends BaseLLM { }, ); - const input = this._generateConverseInput(messages, options); + const input = this._generateConverseInput(messages, { ...options, stream: true }); const command = new ConverseStreamCommand(input); - const response = await client.send(command, { abortSignal: signal }); - if (response.stream) { + let response; + try { + response = await client.send(command, { abortSignal: signal }); + } catch (error: unknown) { + const message = error instanceof Error ? error.message : "Unknown error"; + throw new Error(`Failed to communicate with Bedrock API: ${message}`); + } + + if (!response?.stream) { + throw new Error("No stream received from Bedrock API"); + } + + try { for await (const chunk of response.stream) { - if (chunk.contentBlockDelta?.delta?.text) { - yield { - role: "assistant", - content: chunk.contentBlockDelta.delta.text, - }; + + console.log(chunk); + + if (chunk.contentBlockDelta?.delta) { + + // Handle text content + if (chunk.contentBlockDelta.delta.text) { + yield { role: "assistant", content: chunk.contentBlockDelta.delta.text }; + continue; + } + + if (chunk.contentBlockDelta.delta.toolUse?.input && this._currentToolResponse) { + // Append the new input to the existing string + if (this._currentToolResponse.input === undefined) { + this._currentToolResponse.input = ""; + } + this._currentToolResponse.input += chunk.contentBlockDelta.delta.toolUse.input; + continue; + } + } + + if (chunk.contentBlockStart?.start) { + const toolUse = chunk.contentBlockStart.start.toolUse; + if (toolUse?.toolUseId && toolUse?.name) { + this._currentToolResponse = { + toolUseId: toolUse.toolUseId, + name: toolUse.name, + input: "" + }; + } + continue; + } + + if (chunk.contentBlockStop) { + if (this._currentToolResponse) { + yield { + role: "assistant", + content: "", + toolCalls: [{ + id: this._currentToolResponse.toolUseId, + type: "function", + function: { + name: this._currentToolResponse.name, + arguments: this._currentToolResponse.input + } + }], + }; + this._currentToolResponse = null; + } + continue; } } + } catch (error: unknown) { + this._currentToolResponse = null; + if (error instanceof Error) { + if ("code" in error) { + // AWS SDK specific errors + throw new Error(`AWS Bedrock stream error (${(error as any).code}): ${error.message}`); + } + throw new Error(`Error processing Bedrock stream: ${error.message}`); + } + throw new Error("Error processing Bedrock stream: Unknown error occurred"); } } + /** + * Generates the input payload for the Bedrock Converse API + * @param messages - Array of chat messages + * @param options - Completion options + * @returns Formatted input payload for the API + */ private _generateConverseInput( messages: ChatMessage[], options: CompletionOptions, ): any { const convertedMessages = this._convertMessages(messages); + const supportsTools = PROVIDER_TOOL_SUPPORT.bedrock?.(options.model || "") ?? false; return { modelId: options.model, messages: convertedMessages, system: this.systemMessage ? [{ text: this.systemMessage }] : undefined, + toolConfig: supportsTools && options.tools ? { + tools: options.tools.map(tool => ({ + toolSpec: { + name: tool.function.name, + description: tool.function.description, + inputSchema: { + json: tool.function.parameters + } + } + })) + } : undefined, inferenceConfig: { maxTokens: options.maxTokens, temperature: options.temperature, @@ -135,35 +235,93 @@ class Bedrock extends BaseLLM { }; } - private _convertMessages(messages: ChatMessage[]): any[] { - return messages - .filter((message) => message.role !== "system") - .map((message) => ({ + private _convertMessage(message: ChatMessage): any { + // Handle system messages explicitly + if (message.role === "system") { + return; + } + + // Tool response handling + if (message.role === "tool") { + return { + role: "user", + content: [ + { + toolResult: { + toolUseId: message.toolCallId, + content: [ + { + text: message.content || "" + } + ] + } + } + ] + }; + } + + // Tool calls handling + if (message.role === "assistant" && message.toolCalls) { + return { + role: "assistant", + content: message.toolCalls.map((toolCall) => ({ + toolUse: { + toolUseId: toolCall.id, + name: toolCall.function?.name, + input: JSON.parse(toolCall.function?.arguments || "{}"), + } + })) + }; + } + + // Standard text message + if (typeof message.content === "string") { + return { role: message.role, - content: this._convertMessageContent(message.content), - })); + content: [{ text: message.content }] + }; + } + + // Improved multimodal content handling + if (Array.isArray(message.content)) { + return { + role: message.role, + content: message.content.map(part => { + if (part.type === "text") { + return { text: part.text }; + } + if (part.type === "imageUrl" && part.imageUrl) { + try { + const [mimeType, base64Data] = part.imageUrl.url.split(","); + const format = mimeType.split("/")[1]?.split(";")[0] || "jpeg"; + return { + image: { + format, + source: { + bytes: Buffer.from(base64Data, "base64") + } + } + }; + } catch (error) { + console.warn(`Failed to process image: ${error}`); + return null; + } + } + return null; + }).filter(Boolean) + }; + } } - private _convertMessageContent(messageContent: MessageContent): any[] { - if (typeof messageContent === "string") { - return [{ text: messageContent }]; - } - return messageContent - .map((part) => { - if (part.type === "text") { - return { text: part.text }; + private _convertMessages(messages: ChatMessage[]): any[] { + return messages + .map((message) => { + try { + return this._convertMessage(message); + } catch (error) { + console.error(`Failed to convert message: ${error}`); + return null; } - if (part.type === "imageUrl" && part.imageUrl) { - return { - image: { - format: "jpeg", - source: { - bytes: Buffer.from(part.imageUrl.url.split(",")[1], "base64"), - }, - }, - }; - } - return null; }) .filter(Boolean); } @@ -229,6 +387,7 @@ class Bedrock extends BaseLLM { return modelConfig.extractEmbeddings(responseBody); } + private _getModelConfig() { const modelConfigs: { [key: string]: ModelConfig } = { cohere: { @@ -301,9 +460,15 @@ class Bedrock extends BaseLLM { return responseBody.results .sort((a: any, b: any) => a.index - b.index) .map((result: any) => result.relevance_score); - } catch (error) { - console.error("Error in BedrockReranker.rerank:", error); - throw error; + } catch (error: unknown) { + if (error instanceof Error) { + if ("code" in error) { + // AWS SDK specific errors + throw new Error(`AWS Bedrock rerank error (${(error as any).code}): ${error.message}`); + } + throw new Error(`Error in BedrockReranker.rerank: ${error.message}`); + } + throw new Error("Error in BedrockReranker.rerank: Unknown error occurred"); } } } diff --git a/core/llm/llms/CustomLLM.ts b/core/llm/llms/CustomLLM.ts index 062f141f6..e04ea0ab7 100644 --- a/core/llm/llms/CustomLLM.ts +++ b/core/llm/llms/CustomLLM.ts @@ -1,4 +1,5 @@ import { ChatMessage, CompletionOptions, CustomLLM } from "../../index.js"; +import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; class CustomLLMClass extends BaseLLM { @@ -18,7 +19,7 @@ class CustomLLMClass extends BaseLLM { signal: AbortSignal, options: CompletionOptions, fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise, - ) => AsyncGenerator; + ) => AsyncGenerator; constructor(custom: CustomLLM) { super(custom.options || { model: "custom" }); @@ -38,7 +39,11 @@ class CustomLLMClass extends BaseLLM { options, (...args) => this.fetch(...args), )) { - yield { role: "assistant", content }; + if (typeof content === "string") { + yield { role: "assistant", content }; + } else { + yield content; + } } } else { for await (const update of super._streamChat(messages, signal, options)) { @@ -68,7 +73,11 @@ class CustomLLMClass extends BaseLLM { options, (...args) => this.fetch(...args), )) { - yield content; + if (typeof content === "string") { + yield content; + } else { + yield renderChatMessage(content); + } } } else { throw new Error( diff --git a/core/llm/llms/NCompass.ts b/core/llm/llms/NCompass.ts index 744366b41..45ee8ca7c 100644 --- a/core/llm/llms/NCompass.ts +++ b/core/llm/llms/NCompass.ts @@ -12,7 +12,9 @@ class NCompass extends OpenAI { private static modelConversion: { [key: string]: string } = { "qwen2.5-coder-7b": "Qwen/Qwen2.5-Coder-7B-Instruct", + "qwen2.5-coder:7b": "Qwen/Qwen2.5-Coder-7B-Instruct", "qwen2.5-coder-32b": "Qwen/Qwen2.5-Coder-32B-Instruct", + "qwen2.5-coder:32b": "Qwen/Qwen2.5-Coder-32B-Instruct", }; protected _convertModelName(model: string): string { return NCompass.modelConversion[model] ?? model; diff --git a/core/llm/llms/Ollama.ts b/core/llm/llms/Ollama.ts index 7d581b750..123183781 100644 --- a/core/llm/llms/Ollama.ts +++ b/core/llm/llms/Ollama.ts @@ -1,7 +1,14 @@ import { JSONSchema7, JSONSchema7Object } from "json-schema"; -import { ChatMessage, ChatMessageRole, CompletionOptions, LLMOptions } from "../../index.js"; +import { + ChatMessage, + ChatMessageRole, + CompletionOptions, + LLMOptions, + ModelInstaller, +} from "../../index.js"; import { renderChatMessage } from "../../util/messageContent.js"; +import { getRemoteModelInfo } from "../../util/ollamaHelper.js"; import { BaseLLM } from "../index.js"; import { streamResponse } from "../stream.js"; @@ -82,10 +89,10 @@ type OllamaBaseResponse = { model: string; created_at: string; } & ( - | { + | { done: false; } - | { + | { done: true; done_reason: string; total_duration: number; // Time spent generating the response in nanoseconds @@ -96,7 +103,7 @@ type OllamaBaseResponse = { eval_duration: number; // Time spent generating the response in nanoseconds context: number[]; // An encoding of the conversation used in this response; can be sent in the next request to keep conversational memory } - ); +); type OllamaErrorResponse = { error: string; @@ -105,14 +112,14 @@ type OllamaErrorResponse = { type OllamaRawResponse = | OllamaErrorResponse | (OllamaBaseResponse & { - response: string; // the generated response - }); + response: string; // the generated response + }); type OllamaChatResponse = | OllamaErrorResponse | (OllamaBaseResponse & { - message: OllamaChatMessage; - }); + message: OllamaChatMessage; + }); interface OllamaTool { type: "function"; @@ -123,7 +130,7 @@ interface OllamaTool { }; } -class Ollama extends BaseLLM { +class Ollama extends BaseLLM implements ModelInstaller { static providerName = "ollama"; static defaultOptions: Partial = { apiBase: "http://localhost:11434/", @@ -559,7 +566,7 @@ class Ollama extends BaseLLM { model: this.model, input: chunks, }), - headers: headers + headers: headers, }); if (!resp.ok) { @@ -574,6 +581,45 @@ class Ollama extends BaseLLM { } return embedding; } + + public async installModel( + modelName: string, + signal: AbortSignal, + progressReporter?: (task: string, increment: number, total: number) => void, + ): Promise { + const modelInfo = await getRemoteModelInfo(modelName, signal); + if (!modelInfo) { + throw new Error(`'${modelName}' not found in the Ollama registry!`); + } + const response = await fetch(this.getEndpoint("api/pull"), { + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${this.apiKey}`, + }, + body: JSON.stringify({ name: modelName }), + signal, + }); + + const reader = response.body?.getReader(); + //TODO: generate proper progress based on modelInfo size + while (true) { + const { done, value } = (await reader?.read()) || { + done: true, + value: undefined, + }; + if (done) { + break; + } + + const chunk = new TextDecoder().decode(value); + const lines = chunk.split("\n").filter(Boolean); + for (const line of lines) { + const data = JSON.parse(line); + progressReporter?.(data.status, data.completed, data.total); + } + } + } } export default Ollama; diff --git a/core/llm/llms/OpenAI.ts b/core/llm/llms/OpenAI.ts index 92f0aca08..139d033ab 100644 --- a/core/llm/llms/OpenAI.ts +++ b/core/llm/llms/OpenAI.ts @@ -97,6 +97,10 @@ class OpenAI extends BaseLLM { return !!model && (model.startsWith("o1") || model.startsWith("o3")); } + private isFireworksAiModel(model?: string): boolean { + return !!model && model.startsWith("accounts/fireworks/models"); + } + protected supportsPrediction(model: string): boolean { const SUPPORTED_MODELS = ["gpt-4o-mini", "gpt-4o", "mistral-large"]; return SUPPORTED_MODELS.some((m) => model.includes(m)); @@ -274,7 +278,13 @@ class OpenAI extends BaseLLM { body.max_completion_tokens = undefined; } - if (body.tools?.length && !body.model?.startsWith("o3")) { + if (body.tools?.length) { + if (this.isFireworksAiModel(body.model)) { + // fireworks.ai does not support parallel tool calls, but their api expects this to be true anyway otherwise they return an error. + // tooling works with them as a inference provider once this is set to true. + // https://docs.fireworks.ai/guides/function-calling#openai-compatibility + body.parallel_tool_calls = true; + } // To ensure schema adherence: https://platform.openai.com/docs/guides/function-calling#parallel-function-calling-and-structured-outputs // In practice, setting this to true and asking for multiple tool calls // leads to "arguments" being something like '{"file": "test.ts"}{"file": "test.js"}' diff --git a/core/llm/llms/SambaNova.ts b/core/llm/llms/SambaNova.ts index 7c1f83c89..4c2599529 100644 --- a/core/llm/llms/SambaNova.ts +++ b/core/llm/llms/SambaNova.ts @@ -9,11 +9,20 @@ class SambaNova extends OpenAI { }; private static MODEL_IDS: { [name: string]: string } = { + "qwen2.5-coder-32b": "Qwen2.5-Coder-32B-Instruct", + "llama3.3-70b": "Meta-Llama-3.3-70B-Instruct", "llama3.1-8b": "Meta-Llama-3.1-8B-Instruct", "llama3.1-70b": "Meta-Llama-3.1-70B-Instruct", "llama3.1-405b": "Meta-Llama-3.1-405B-Instruct", - "llama3.1-1b": "Meta-Llama-3.2-1B-Instruct", - "llama3.1-3b": "Meta-Llama-3.2-3B-Instruct", + "llama3.1-tulu-405b": "Llama-3.1-Tulu-3-405B", + "llama3.2-1b": "Meta-Llama-3.2-1B-Instruct", + "llama3.2-3b": "Meta-Llama-3.2-3B-Instruct", + "llama3.2-11b": "Llama-3.2-11B-Vision-Instruct", + "llama3.2-90b": "Llama-3.2-90B-Vision-Instruct", + "qwen2.5-72b": "Qwen2.5-72B-Instruct", + "qwq-32b": "QwQ-32B-Preview", + "deepseek-r1-distill-llama-70b": "DeepSeek-R1-Distill-Llama-70B", + "deepseek-r1": "DeepSeek-R1", }; protected _convertModelName(model: string) { diff --git a/core/llm/toolSupport.test.ts b/core/llm/toolSupport.test.ts new file mode 100644 index 000000000..df18dc876 --- /dev/null +++ b/core/llm/toolSupport.test.ts @@ -0,0 +1,203 @@ +// core/llm/toolSupport.test.ts +import { PROVIDER_TOOL_SUPPORT } from "./toolSupport"; + +describe("PROVIDER_TOOL_SUPPORT", () => { + describe("continue-proxy", () => { + const supportsFn = PROVIDER_TOOL_SUPPORT["continue-proxy"]; + + it("should return true for Claude 3.5 models", () => { + expect(supportsFn("claude-3-5-sonnet")).toBe(true); + expect(supportsFn("claude-3.5-sonnet")).toBe(true); + }); + + it("should return true for Claude 3.7 models", () => { + expect(supportsFn("claude-3-7-haiku")).toBe(true); + expect(supportsFn("claude-3.7-sonnet")).toBe(true); + }); + + it("should return true for GPT-4 models", () => { + expect(supportsFn("gpt-4-turbo")).toBe(true); + expect(supportsFn("gpt-4-1106-preview")).toBe(true); + }); + + it("should return true for O3 models", () => { + expect(supportsFn("o3-preview")).toBe(true); + }); + + it("should return true for Gemini models", () => { + expect(supportsFn("gemini-pro")).toBe(true); + expect(supportsFn("gemini-1.5-pro")).toBe(true); + }); + + it("should return false for unsupported models", () => { + expect(supportsFn("gpt-3.5-turbo")).toBe(false); + expect(supportsFn("claude-2")).toBe(false); + expect(supportsFn("llama-3")).toBe(false); + }); + + it("should handle case insensitivity", () => { + expect(supportsFn("CLAUDE-3-5-sonnet")).toBe(true); + expect(supportsFn("GPT-4-turbo")).toBe(true); + expect(supportsFn("GEMINI-pro")).toBe(true); + }); + }); + + describe("anthropic", () => { + const supportsFn = PROVIDER_TOOL_SUPPORT["anthropic"]; + + it("should return true for Claude 3.5 models", () => { + expect(supportsFn("claude-3-5-sonnet")).toBe(true); + expect(supportsFn("claude-3.5-haiku")).toBe(true); + }); + + it("should return true for Claude 3.7 models", () => { + expect(supportsFn("claude-3-7-haiku")).toBe(true); + expect(supportsFn("claude-3.7-sonnet")).toBe(true); + }); + + it("should return undefined for unsupported models", () => { + expect(supportsFn("claude-2")).toBeUndefined(); + expect(supportsFn("claude-instant")).toBeUndefined(); + }); + + it("should handle case insensitivity", () => { + expect(supportsFn("CLAUDE-3-5-sonnet")).toBe(true); + expect(supportsFn("CLAUDE-3.7-haiku")).toBe(true); + }); + }); + + describe("openai", () => { + const supportsFn = PROVIDER_TOOL_SUPPORT["openai"]; + + it("should return true for GPT-4 models", () => { + expect(supportsFn("gpt-4")).toBe(true); + expect(supportsFn("gpt-4-turbo")).toBe(true); + expect(supportsFn("gpt-4-1106-preview")).toBe(true); + }); + + it("should return true for O3 models", () => { + expect(supportsFn("o3")).toBe(true); + expect(supportsFn("o3-preview")).toBe(true); + }); + + it("should return undefined for unsupported models", () => { + expect(supportsFn("gpt-3.5-turbo")).toBeUndefined(); + expect(supportsFn("davinci")).toBeUndefined(); + }); + + it("should handle case insensitivity", () => { + expect(supportsFn("GPT-4-turbo")).toBe(true); + expect(supportsFn("O3-preview")).toBe(true); + }); + }); + + describe("gemini", () => { + const supportsFn = PROVIDER_TOOL_SUPPORT["gemini"]; + + it("should return true for all Gemini models", () => { + expect(supportsFn("gemini-pro")).toBe(true); + expect(supportsFn("gemini-1.5-pro")).toBe(true); + expect(supportsFn("gemini-ultra")).toBe(true); + }); + + it("should return false for non-Gemini models", () => { + expect(supportsFn("gpt-4")).toBe(false); + expect(supportsFn("claude-3")).toBe(false); + }); + + it("should handle case insensitivity", () => { + expect(supportsFn("GEMINI-pro")).toBe(true); + expect(supportsFn("Gemini-1.5-Pro")).toBe(true); + }); + }); + + describe("bedrock", () => { + const supportsFn = PROVIDER_TOOL_SUPPORT["bedrock"]; + + it("should return true for Claude 3.5 Sonnet models", () => { + expect(supportsFn("anthropic.claude-3-5-sonnet-20240620-v1:0")).toBe(true); + expect(supportsFn("anthropic.claude-3.5-sonnet-20240620-v1:0")).toBe(true); + }); + + it("should return true for Claude 3.7 Sonnet models", () => { + expect(supportsFn("anthropic.claude-3-7-sonnet-20240620-v1:0")).toBe(true); + expect(supportsFn("anthropic.claude-3.7-sonnet-20240620-v1:0")).toBe(true); + }); + + it("should return undefined for Claude Haiku and Opus models", () => { + expect(supportsFn("anthropic.claude-3-5-haiku-20240307-v1:0")).toBeUndefined(); + expect(supportsFn("anthropic.claude-3.5-haiku-20240620-v1:0")).toBeUndefined(); + expect(supportsFn("anthropic.claude-3-7-haiku-20240620-v1:0")).toBeUndefined(); + expect(supportsFn("anthropic.claude-3-5-opus-20240620-v1:0")).toBeUndefined(); + expect(supportsFn("anthropic.claude-3.7-opus-20240620-v1:0")).toBeUndefined(); + }); + + it("should return undefined for other unsupported models", () => { + expect(supportsFn("anthropic.claude-instant-v1")).toBeUndefined(); + expect(supportsFn("anthropic.titan-text-express-v1")).toBeUndefined(); + }); + + it("should handle case insensitivity", () => { + expect(supportsFn("ANTHROPIC.CLAUDE-3-5-SONNET-20240620-v1:0")).toBe(true); + expect(supportsFn("ANTHROPIC.CLAUDE-3.7-SONNET-20240620-v1:0")).toBe(true); + }); + }); + + describe("ollama", () => { + const supportsFn = PROVIDER_TOOL_SUPPORT["ollama"]; + + it("should return true for supported models", () => { + expect(supportsFn("llama3.1")).toBe(true); + expect(supportsFn("llama3.2-8b")).toBe(true); + expect(supportsFn("llama3.3-70b")).toBe(true); + expect(supportsFn("qwen2")).toBe(true); + expect(supportsFn("mixtral-8x7b")).toBe(true); + expect(supportsFn("command-r")).toBe(true); + expect(supportsFn("smollm2")).toBe(true); + expect(supportsFn("hermes3")).toBe(true); + expect(supportsFn("athene-v2")).toBe(true); + expect(supportsFn("nemotron-4-340b")).toBe(true); + expect(supportsFn("llama3-groq")).toBe(true); + expect(supportsFn("granite3")).toBe(true); + expect(supportsFn("aya-expanse")).toBe(true); + expect(supportsFn("firefunction-v2")).toBe(true); + expect(supportsFn("mistral-7b")).toBe(true); + }); + + it("should return false for explicitly unsupported models", () => { + expect(supportsFn("vision")).toBe(false); + expect(supportsFn("math")).toBe(false); + expect(supportsFn("guard")).toBe(false); + expect(supportsFn("mistrallite")).toBe(false); + expect(supportsFn("mistral-openorca")).toBe(false); + }); + + it("should return undefined for other models", () => { + expect(supportsFn("llama2")).toBeUndefined(); + expect(supportsFn("phi-2")).toBeUndefined(); + expect(supportsFn("falcon")).toBeUndefined(); + }); + + it("should handle case insensitivity", () => { + expect(supportsFn("LLAMA3.1")).toBe(true); + expect(supportsFn("MIXTRAL-8x7b")).toBe(true); + expect(supportsFn("VISION")).toBe(false); + }); + }); + + describe("edge cases", () => { + it("should handle empty model names", () => { + expect(PROVIDER_TOOL_SUPPORT["continue-proxy"]("")).toBe(false); + expect(PROVIDER_TOOL_SUPPORT["anthropic"]("")).toBeUndefined(); + expect(PROVIDER_TOOL_SUPPORT["openai"]("")).toBeUndefined(); + expect(PROVIDER_TOOL_SUPPORT["gemini"]("")).toBe(false); + expect(PROVIDER_TOOL_SUPPORT["bedrock"]("")).toBeUndefined(); + expect(PROVIDER_TOOL_SUPPORT["ollama"]("")).toBeUndefined(); + }); + + it("should handle non-existent provider", () => { + // @ts-ignore - Testing runtime behavior with invalid provider + expect(PROVIDER_TOOL_SUPPORT["non-existent"]).toBeUndefined(); + }); + }); +}); diff --git a/core/llm/toolSupport.ts b/core/llm/toolSupport.ts index ea7f2adf3..06994ec93 100644 --- a/core/llm/toolSupport.ts +++ b/core/llm/toolSupport.ts @@ -3,9 +3,24 @@ export const PROVIDER_TOOL_SUPPORT: Record< (model: string) => boolean | undefined > = { "continue-proxy": (model) => { - return ["claude-3-5", "claude-3.5", "claude-3-7", "claude-3.7", "gpt-4", "o3", "gemini"].some((part) => - model.toLowerCase().startsWith(part), - ); + // see getContinueProxyModelName + const provider = model.split("/")[2]; + const _model = model.split("/")[3]; + if (provider && _model && provider !== "continue-proxy") { + const fn = PROVIDER_TOOL_SUPPORT[provider]; + if (fn) { + return fn(_model); + } + } + return [ + "claude-3-5", + "claude-3.5", + "claude-3-7", + "claude-3.7", + "gpt-4", + "o3", + "gemini", + ].some((part) => model.toLowerCase().startsWith(part)); }, anthropic: (model) => { if ( @@ -24,16 +39,49 @@ export const PROVIDER_TOOL_SUPPORT: Record< ) { return true; } + // firworks-ai https://docs.fireworks.ai/guides/function-calling + if (model.startsWith("accounts/fireworks/models/")) { + switch (model.substring(26)) { + case "llama-v3p1-405b-instruct": + case "llama-v3p1-70b-instruct": + case "qwen2p5-72b-instruct": + case "firefunction-v1": + case "firefunction-v2": + return true; + default: + return false; + } + } }, gemini: (model) => { // All gemini models support function calling return model.toLowerCase().includes("gemini"); }, + bedrock: (model) => { + // For Bedrock, only support Claude Sonnet models with versions 3.5/3-5 and 3.7/3-7 + if ( + model.toLowerCase().includes("sonnet") && + ["claude-3-5", "claude-3.5", "claude-3-7", "claude-3.7"].some((part) => + model.toLowerCase().includes(part), + ) + ) { + return true; + } + }, // https://ollama.com/search?c=tools ollama: (model) => { + let modelName = ""; + // Extract the model name after the last slash to support other registries + if(model.includes("/")) { + let parts = model.split('/'); + modelName = parts[parts.length - 1]; + } else { + modelName = model; + } + if ( ["vision", "math", "guard", "mistrallite", "mistral-openorca"].some( - (part) => model.toLowerCase().includes(part), + (part) => modelName.toLowerCase().includes(part), ) ) { return false; @@ -53,10 +101,19 @@ export const PROVIDER_TOOL_SUPPORT: Record< "nemotron", "llama3-groq", "granite3", + "granite-3", "aya-expanse", "firefunction-v2", "mistral", - ].some((part) => model.toLowerCase().startsWith(part)) + ].some((part) => modelName.toLowerCase().includes(part)) + ) { + return true; + } + }, + sambanova: (model) => { + // https://docs.sambanova.ai/cloud/docs/capabilities/function-calling + if ( + model.toLowerCase().startsWith("meta-llama-3") ) { return true; } diff --git a/core/package-lock.json b/core/package-lock.json index abe4271f8..a15d33faf 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -6163,9 +6163,10 @@ "integrity": "sha512-lHe62zvbTB5eEABUVi/AwVh0ZKY9rMMDhmm+eeyuuUQbQ3+J+fONVQOZyj+DdrvD4BY33uYniyRJ4UJIaSKAfw==" }, "node_modules/axios": { - "version": "1.7.9", - "resolved": "https://registry.npmjs.org/axios/-/axios-1.7.9.tgz", - "integrity": "sha512-LhLcE7Hbiryz8oMDdDptSrWowmB4Bl6RCt6sIJKpRB4XtVf0iEgewX3au/pJqm+Py1kCASkb/FFKjxQaLtxJvw==", + "version": "1.8.2", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.8.2.tgz", + "integrity": "sha512-ls4GYBm5aig9vWx8AWDSGLpnpDQRtWAfrjU+EuytuODrFBkqesN2RkOQCBzrA1RQNHw1SmRMSDDDSwzNAYQ6Rg==", + "license": "MIT", "dependencies": { "follow-redirects": "^1.15.6", "form-data": "^4.0.0", diff --git a/core/promptFiles/v2/getPromptFiles.ts b/core/promptFiles/v2/getPromptFiles.ts index d991d140a..7859c7cf7 100644 --- a/core/promptFiles/v2/getPromptFiles.ts +++ b/core/promptFiles/v2/getPromptFiles.ts @@ -16,7 +16,7 @@ export async function getPromptFilesFromDir( return []; } - const uris = await walkDir(dir, ide, { ignoreFiles: [] }); + const uris = await walkDir(dir, ide); const promptFilePaths = uris.filter((p) => p.endsWith(".prompt")); const results = promptFilePaths.map(async (uri) => { const content = await ide.readFile(uri); // make a try catch diff --git a/core/protocol/coreWebview.ts b/core/protocol/coreWebview.ts index 67b5919a4..5e71e5f11 100644 --- a/core/protocol/coreWebview.ts +++ b/core/protocol/coreWebview.ts @@ -5,7 +5,10 @@ import { ToWebviewFromIdeOrCoreProtocol } from "./webview.js"; export type ToCoreFromWebviewProtocol = ToCoreFromIdeOrWebviewProtocol & { didChangeSelectedProfile: [{ id: string | null }, void]; - didChangeSelectedOrg: [{ id: string | null }, void]; + didChangeSelectedOrg: [ + { id: string | null; profileId?: string | null }, + void, + ]; }; export type ToWebviewFromCoreProtocol = ToWebviewFromIdeOrCoreProtocol & { didChangeAvailableProfiles: [ diff --git a/core/test/testDir.ts b/core/test/testDir.ts index 9b0473b46..0e34f509b 100644 --- a/core/test/testDir.ts +++ b/core/test/testDir.ts @@ -1,7 +1,7 @@ import fs from "fs"; import os from "os"; import path from "path"; -import { localPathToUri, localPathOrUriToPath } from "../util/pathToUri"; +import { localPathOrUriToPath, localPathToUri } from "../util/pathToUri"; // Want this outside of the git repository so we can change branches in tests export const TEST_DIR_PATH = path.join(os.tmpdir(), "testWorkspaceDir"); @@ -26,7 +26,7 @@ export function tearDownTestDir() { "index/index.ts" creates an empty index/index.ts ["index/index.ts", "hello"] creates index/index.ts with contents "hello" */ -export function addToTestDir(pathsOrUris: (string | string[])[]) { +export function addToTestDir(pathsOrUris: (string | [string, string])[]) { // Allow tests to use URIs or local paths const paths = pathsOrUris.map((val) => { if (Array.isArray(val)) { diff --git a/core/util/GlobalContext.ts b/core/util/GlobalContext.ts index 06cede64c..640bf7a56 100644 --- a/core/util/GlobalContext.ts +++ b/core/util/GlobalContext.ts @@ -36,7 +36,7 @@ export type GlobalContextType = { hasDismissedConfigTsNoticeJetBrains: boolean; hasAlreadyCreatedAPromptFile: boolean; showConfigUpdateToast: boolean; - isSupportedLanceDbCpuTarget: boolean; + isSupportedLanceDbCpuTargetForLinux: boolean; sharedConfig: SharedConfigSchema; failedDocs: SiteIndexingConfig[]; }; diff --git a/core/util/ollamaHelper.ts b/core/util/ollamaHelper.ts index a00e869dd..2d5266318 100644 --- a/core/util/ollamaHelper.ts +++ b/core/util/ollamaHelper.ts @@ -1,6 +1,13 @@ +import crypto from "crypto"; +import { exec } from "node:child_process"; import path from "node:path"; import { IDE } from ".."; -import { exec } from "node:child_process"; + +export interface ModelInfo { + id: string; + size: number; + digest: string; +} export async function isOllamaInstalled(): Promise { return new Promise((resolve, _reject) => { @@ -39,3 +46,54 @@ export async function startLocalOllama(ide: IDE): Promise { }); } } + +export async function getRemoteModelInfo( + modelId: string, + signal?: AbortSignal, + ): Promise { + const start = Date.now(); + const [modelName, tag = "latest"] = modelId.split(":"); + const url = `https://registry.ollama.ai/v2/library/${modelName}/manifests/${tag}`; + try { + const sig = signal ? signal : AbortSignal.timeout(3000); + const response = await fetch(url, { signal: sig }); + + if (!response.ok) { + throw new Error(`Failed to fetch the model page: ${response.statusText}`); + } + + // First, read the response body as an ArrayBuffer to compute the digest + const buffer = await response.arrayBuffer(); + const digest = getDigest(buffer); + + // Then, decode the ArrayBuffer into a string and parse it as JSON + const text = new TextDecoder().decode(buffer); + const manifest = JSON.parse(text) as { + config: { size: number }; + layers: { size: number }[]; + }; + const modelSize = + manifest.config.size + + manifest.layers.reduce((sum, layer) => sum + layer.size, 0); + + const data: ModelInfo = { + id: modelId, + size: modelSize, + digest, + }; + // Cache the successful result + return data; + } catch (error) { + console.error(`Error fetching or parsing model info: ${error}`); + } finally { + const elapsed = Date.now() - start; + console.log(`Fetched remote information for ${modelId} in ${elapsed} ms`); + } + return undefined; + } + + function getDigest(buffer: ArrayBuffer): string { + const hash = crypto.createHash("sha256"); + hash.update(new Uint8Array(buffer)); + return hash.digest("hex"); + } \ No newline at end of file diff --git a/core/util/paths.ts b/core/util/paths.ts index 9a4c77bb2..02d2f43b5 100644 --- a/core/util/paths.ts +++ b/core/util/paths.ts @@ -5,10 +5,10 @@ import * as path from "path"; import * as JSONC from "comment-json"; import dotenv from "dotenv"; +import { DevEventName } from "@continuedev/config-yaml"; import { IdeType, SerializedContinueConfig } from "../"; import { defaultConfig, defaultConfigJetBrains } from "../config/default"; import Types from "../config/types"; -import { DevEventName } from "@continuedev/config-yaml"; dotenv.config(); @@ -103,7 +103,7 @@ export function getConfigJsonPath(ideType: IdeType = "vscode"): string { return p; } -export function getConfigYamlPath(ideType: IdeType): string { +export function getConfigYamlPath(ideType?: IdeType): string { const p = path.join(getContinueGlobalPath(), "config.yaml"); // if (!fs.existsSync(p)) { // if (ideType === "jetbrains") { @@ -115,6 +115,14 @@ export function getConfigYamlPath(ideType: IdeType): string { return p; } +export function getPrimaryConfigFilePath(): string { + const configYamlPath = getConfigYamlPath(); + if (fs.existsSync(configYamlPath)) { + return configYamlPath; + } + return getConfigJsonPath(); +} + export function getConfigTsPath(): string { const p = path.join(getContinueGlobalPath(), "config.ts"); if (!fs.existsSync(p)) { @@ -353,6 +361,10 @@ export function getGlobalPromptsPath(): string { return path.join(getContinueGlobalPath(), "prompts"); } +export function getGlobalAssistantsPath(): string { + return path.join(getContinueGlobalPath(), "assistants"); +} + export function readAllGlobalPromptFiles( folderPath: string = getGlobalPromptsPath(), ): { path: string; content: string }[] { @@ -368,7 +380,7 @@ export function readAllGlobalPromptFiles( if (stats.isDirectory()) { const nestedPromptFiles = readAllGlobalPromptFiles(filepath); promptFiles.push(...nestedPromptFiles); - } else { + } else if (file.endsWith(".prompt")) { const content = fs.readFileSync(filepath, "utf8"); promptFiles.push({ path: filepath, content }); } @@ -397,10 +409,6 @@ export function migrateV1DevDataFiles() { if (!fs.existsSync(newFilePath)) { fs.copyFileSync(oldFilePath, newFilePath); fs.unlinkSync(oldFilePath); - } else { - console.warn( - `V1 Dev data migration: ${newFilePath} already exists, skipping ${oldFileName}`, - ); } } } diff --git a/core/util/text.ts b/core/util/text.ts new file mode 100644 index 000000000..e4870dfa0 --- /dev/null +++ b/core/util/text.ts @@ -0,0 +1,6 @@ +export const capitalizeFirstLetter = (val: string) => { + if (val.length === 0) { + return ""; + } + return val[0].toUpperCase() + val.slice(1); +}; diff --git a/core/util/uri.ts b/core/util/uri.ts index 13d7956ac..e180a0a69 100644 --- a/core/util/uri.ts +++ b/core/util/uri.ts @@ -116,19 +116,23 @@ export function getLastNUriRelativePathParts( } export function joinPathsToUri(uri: string, ...pathSegments: string[]) { - const components = URI.parse(uri); + let baseUri = uri; + if (baseUri.at(-1) !== "/") { + baseUri += "/"; + } const segments = pathSegments.map((segment) => pathToUriPathSegment(segment)); - components.path = `${components.path}/${segments.join("/")}`; - return URI.serialize(components); + return URI.resolve(baseUri, segments.join("/")); } export function joinEncodedUriPathSegmentToUri( uri: string, pathSegment: string, ) { - const components = URI.parse(uri); - components.path = `${components.path}/${pathSegment}`; - return URI.serialize(components); + let baseUri = uri; + if (baseUri.at(-1) !== "/") { + baseUri += "/"; + } + return URI.resolve(baseUri, pathSegment); } export function getShortestUniqueRelativeUriPaths( diff --git a/docs/docs/customize/deep-dives/configuration.md b/docs/docs/customize/deep-dives/configuration.md index 11522e86f..5cd0ebf24 100644 --- a/docs/docs/customize/deep-dives/configuration.md +++ b/docs/docs/customize/deep-dives/configuration.md @@ -18,7 +18,7 @@ To open your configuration file, you can click the "gear" icon in the bottom rig When you save a config file from the IDE, Continue will automatically refresh to take into account your changes. A config file is automatically created the first time you use Continue, and always automatically generated with default values if it doesn't exist. -See the full reference for `config.yaml` [here](../../reference.md). +See the full reference for `config.yaml` [here](../../yaml-reference.md). ## Deprecated configuration methods diff --git a/docs/docs/customize/deep-dives/development-data.md b/docs/docs/customize/deep-dives/development-data.md index 976c02833..da9f5136c 100644 --- a/docs/docs/customize/deep-dives/development-data.md +++ b/docs/docs/customize/deep-dives/development-data.md @@ -14,7 +14,7 @@ You can read more about how development data is generated as a byproduct of LLM- You can also configure custom destinations for your data, including remote HTTP endpoints and local file directories. -For hub assistants, data destinations are configured in `data` blocks. Visit the hub to [explore example data blocks](https://hub.continue.dev/explore/data) or [create your own](https://hub.continue.dev/new?type=block&block=data). +For hub assistants, data destinations are configured in `data` blocks. Visit the hub to [explore example data blocks](https://hub.continue.dev/explore/data) or [create your own](https://hub.continue.dev/new?type=block&blockType=data). See more details about adding `data` blocks to your configuration files in the [YAML specification](../../yaml-reference.md#data) diff --git a/docs/docs/customize/deep-dives/docs.mdx b/docs/docs/customize/deep-dives/docs.mdx index 7a5be2263..ee806263e 100644 --- a/docs/docs/customize/deep-dives/docs.mdx +++ b/docs/docs/customize/deep-dives/docs.mdx @@ -64,7 +64,7 @@ Pre-indexed docs are only available in VS Code because the VS Code extension shi ### Hub `docs` Blocks -@Docs uses [`docs` blocks](../../hub/blocks/block-types.md#docs) in Assistants from the hub. Visit the hub to [explore `docs` blocks](https://hub.continue.dev/explore/docs) or [create your own](https://hub.continue.dev/new?type=block&block=docs). +@Docs uses [`docs` blocks](../../hub/blocks/block-types.md#docs) in Assistants from the hub. Visit the hub to [explore `docs` blocks](https://hub.continue.dev/explore/docs) or [create your own](https://hub.continue.dev/new?type=block&blockType=docs). ### Through the `@Docs` Context Provider @@ -137,7 +137,7 @@ As with [@Codebase context provider configuration](./codebase#configuration), yo context: - provider: docs params: - nRetrieve: 25 # The number of docs to retreive from the embeddings query + nRetrieve: 25 # The number of docs to retrieve from the embeddings query nFinal: 5 # The number of docs chunks to return IF reranking useReranking: true # use reranking if a reranker is configured (defaults to true) ``` @@ -149,7 +149,7 @@ As with [@Codebase context provider configuration](./codebase#configuration), yo { "name": "docs", "params": { - "nRetrieve": 25, // The number of docs to retreive from the embeddings query + "nRetrieve": 25, // The number of docs to retrieve from the embeddings query "nFinal": 5, // The number of docs chunks to return IF reranking "useReranking": true // use reranking if a reranker is configured (defaults to true) } diff --git a/docs/docs/customize/deep-dives/prompt-files.md b/docs/docs/customize/deep-dives/prompt-files.md index 1ab90e94a..f5c834c17 100644 --- a/docs/docs/customize/deep-dives/prompt-files.md +++ b/docs/docs/customize/deep-dives/prompt-files.md @@ -4,7 +4,7 @@ title: Prompt files Prompt files provide a convenient way to standardize common patterns and share a collection of LLM prompts with your team. They make it easy to build and use these prompts. -On the [hub](../../hub/introduction.md), prompt files are stored within [prompt blocks](../../hub/blocks/block-types.md#prompts), which show up as [slash commands](../slash-commands.mdx) in Chat. Visit the hub to [explore prompts](https://hub.continue.dev/explore/prompts) or [create your own](https://hub.continue.dev/new?type=block&block=rules). +On the [hub](../../hub/introduction.md), prompt files are stored within [prompt blocks](../../hub/blocks/block-types.md#prompts), which show up as [slash commands](../slash-commands.mdx) in Chat. Visit the hub to [explore prompts](https://hub.continue.dev/explore/prompts) or [create your own](https://hub.continue.dev/new?type=block&blockType=rules). Prompt files can also be stored within your project's root directory as `.prompt` files. See below. diff --git a/docs/docs/customize/deep-dives/rules.md b/docs/docs/customize/deep-dives/rules.md index eac9137ce..59f816c15 100644 --- a/docs/docs/customize/deep-dives/rules.md +++ b/docs/docs/customize/deep-dives/rules.md @@ -9,7 +9,7 @@ Rules are used to provide instructions to **chat** models. They are inserted int ## Hub `rules` blocks -Rules can be added to an Assistant on the Continue Hub. Explore available rules [here](https://hub.continue.dev/explore/rules), or [create your own](https://hub.continue.dev/new?type=block&block=rules) in the Hub. +Rules can be added to an Assistant on the Continue Hub. Explore available rules [here](https://hub.continue.dev/explore/rules), or [create your own](https://hub.continue.dev/new?type=block&blockType=rules) in the Hub. ## `.continuerules` diff --git a/docs/docs/customize/model-providers/more/SambaNova.mdx b/docs/docs/customize/model-providers/more/SambaNova.mdx index 8fb2facfb..3d554006e 100644 --- a/docs/docs/customize/model-providers/more/SambaNova.mdx +++ b/docs/docs/customize/model-providers/more/SambaNova.mdx @@ -3,15 +3,15 @@ import Tabs from "@theme/Tabs"; # SambaNova Cloud -The SambaNova Cloud is a cloud platform for running large AI models with the world record Llama 3.1 70B/405B performance. You can follow the instructions in [this blog post](https://sambanova.ai/blog/accelerating-coding-with-sambanova-cloud?ref=blog.continue.dev) to configure your setup. +The SambaNova Cloud is a cloud platform for running large AI models with the world record open source models performance. You can follow the instructions in [this blog post](https://sambanova.ai/blog/accelerating-coding-with-sambanova-cloud?ref=blog.continue.dev) to configure your setup. ```yaml title="config.yaml" models: - - name: SambaNova Llama 3.1 405B + - name: SambaNova Qwen2.5 coder provider: sambanova - model: llama3.1-405b + model: qwen2.5-coder-32b apiKey: ``` @@ -20,9 +20,9 @@ The SambaNova Cloud is a cloud platform for running large AI models with the wor { "models": [ { - "title": "SambaNova Llama 3.1 405B", + "title": "SambaNova Qwen2.5 coder", "provider": "sambanova", - "model": "llama3.1-405b", + "model": "qwen2.5-coder-32b", "apiKey": "" } ] diff --git a/docs/docs/customize/model-providers/top-level/azure.mdx b/docs/docs/customize/model-providers/top-level/azure.mdx index cbb955bca..2c201d938 100644 --- a/docs/docs/customize/model-providers/top-level/azure.mdx +++ b/docs/docs/customize/model-providers/top-level/azure.mdx @@ -51,7 +51,7 @@ We recommend configuring **GPT-4o** as your chat model. ## Autocomplete model -We recommend configuring **Codestral** as your autocomplete model. +We recommend configuring **Codestral** as your autocomplete model. If you use Azure AI Foundry to deploy Codestral: @@ -60,6 +60,8 @@ We recommend configuring **Codestral** as your autocomplete model. - name: Codestral provider: mistral model: codestral-latest + apiBase: https://..models.ai.azure.com/v1 + apiKey: roles: - autocomplete ``` @@ -70,7 +72,9 @@ We recommend configuring **Codestral** as your autocomplete model. "tabAutocompleteModel": { "title": "Codestral", "provider": "mistral", - "model": "codestral-latest" + "model": "codestral-latest", + "apiBase": "https://..models.ai.azure.com/v1", + "apiKey": "" } } ``` diff --git a/docs/docs/customize/model-roles/edit.mdx b/docs/docs/customize/model-roles/edit.mdx index 57bbc76aa..de817ed42 100644 --- a/docs/docs/customize/model-roles/edit.mdx +++ b/docs/docs/customize/model-roles/edit.mdx @@ -45,4 +45,4 @@ In Continue, you can add `edit` to a model's roles to specify that it can be use -Explore edit models in [the hub](https://hub.continue.dev/explore/models?roles=edit). Generally, we our recommendations for Edit overlap with recommendations for Chat. +Explore edit models in [the hub](https://hub.continue.dev/explore/models?roles=edit). Generally, our recommendations for Edit overlap with recommendations for Chat. diff --git a/docs/docs/customize/tools.mdx b/docs/docs/customize/tools.mdx index 45280697e..1aad549f1 100644 --- a/docs/docs/customize/tools.mdx +++ b/docs/docs/customize/tools.mdx @@ -30,7 +30,7 @@ Currently custom tools can be configured using the [Model Context Protocol](http MCP Servers can be added to hub Assistants using `mcpServers` blocks. You can explore available MCP server blocks [here](https://hub.continue.dev/explore/mcp). -To set up your own MCP server, read the [MCP quickstart](https://modelcontextprotocol.io/quickstart) and then [create an `mcpServers` block](https://hub.continue.dev/new?type=block&block=mcpServers) or add the following to your [config file](../customize/deep-dives/configuration.md): +To set up your own MCP server, read the [MCP quickstart](https://modelcontextprotocol.io/quickstart) and then [create an `mcpServers` block](https://hub.continue.dev/new?type=block&blockType=mcpServers) or add the following to your [config file](../customize/deep-dives/configuration.md): diff --git a/docs/docs/troubleshooting.mdx b/docs/docs/troubleshooting.mdx index ae54ee8ac..3065bdc28 100644 --- a/docs/docs/troubleshooting.mdx +++ b/docs/docs/troubleshooting.mdx @@ -41,7 +41,7 @@ If you're getting a response from the LLM that doesn't seem to make sense, you c 1. Open the "Output" panel (right next to the terminal) 2. In the dropdown, select "Continue - LLM Prompts/Completions" -3. View the exact prompts that were sent to the LLM and the completions recieved +3. View the exact prompts that were sent to the LLM and the completions received ### JetBrains @@ -151,6 +151,14 @@ This can be accomplished using the following command: `Continue: Rebuild codebas This can be fixed by selecting `Actions > Choose Boot runtime for the IDE` then selecting the latest version, and then restarting Android Studio. [See this thread](https://github.com/continuedev/continue/issues/596#issuecomment-1789327178) for details. +### I received a "Codebase indexing disabled - Your Linux system lacks required CPU features (AVX2, FMA)" notification + +We use LanceDB as our vector database for codebase search features. On x64 Linux systems, LanceDB requires specific CPU features (FMA and AVX2) which may not be available on older processors. + +Most Continue features will work normally, including autocomplete and chat. However, commands that rely on codebase indexing, such as `@codebase`, `@files`, and `@folder`, will be disabled. + +For more details about this requirement, see the [LanceDB issue #2195](https://github.com/lancedb/lance/issues/2195). + ## Still having trouble? You can also join our Discord community [here](https://discord.gg/vapESyrFmJ) for additional support and discussions. Alternatively, you can create a GitHub issue [here](https://github.com/continuedev/continue/issues/new?assignees=&labels=bug&projects=&template=bug-report-%F0%9F%90%9B.md&title=), providing details of your problem, and we'll be able to help you out more quickly. diff --git a/docs/docs/yaml-migration.md b/docs/docs/yaml-migration.md index 0a7773670..4619018f2 100644 --- a/docs/docs/yaml-migration.md +++ b/docs/docs/yaml-migration.md @@ -12,7 +12,7 @@ See also - [Intro to YAML](https://yaml.org/) - [JSON Continue Config Reference](/json-reference) -- [YAML Continue Config Reference](/reference) +- [YAML Continue Config Reference](/yaml-reference) ## Create YAML file @@ -37,9 +37,9 @@ Add all model configurations in `config.json`, including models in `models`, `ta - `inlineEdit` -> e.g. `roles: [chat, edit]` - `applyCodeBlock` -> e.g. `roles: [chat, apply]` -Model-level `requestOptions` remain, with minor changes. See [YAML Continue Config Reference](/reference#requestoptions) +Model-level `requestOptions` remain, with minor changes. See [YAML Continue Config Reference](/yaml-reference#requestoptions) -Model-level `completionOptions` are replaced by `defaultCompletionOptions`, with minor changes. See [YAML Continue Config Reference](/reference#completionoptions) +Model-level `completionOptions` are replaced by `defaultCompletionOptions`, with minor changes. See [YAML Continue Config Reference](/yaml-reference#completionoptions) diff --git a/docs/docs/yaml-reference.md b/docs/docs/yaml-reference.md index 9de133cd7..d4e63d1b4 100644 --- a/docs/docs/yaml-reference.md +++ b/docs/docs/yaml-reference.md @@ -4,7 +4,7 @@ description: Reference for the Continue configuration YAML file keywords: [config, yaml, configuration, customize, customization] --- -# confg.yaml Reference +# config.yaml Reference ## Introduction diff --git a/docs/docusaurus.config.js b/docs/docusaurus.config.js index 8216da215..c8d987266 100644 --- a/docs/docusaurus.config.js +++ b/docs/docusaurus.config.js @@ -19,7 +19,7 @@ const config = { favicon: "img/favicon.ico", // Set the production url of your site here - url: "https://continue.dev", + url: "https://docs.continue.dev", // Set the // pathname under which your site is served // For GitHub pages deployment, it is often '//' baseUrl: "/", diff --git a/extensions/intellij/.run/Prompt Logs.run.xml b/extensions/intellij/.run/Prompt Logs.run.xml index ce8c399dd..7bee897b2 100644 --- a/extensions/intellij/.run/Prompt Logs.run.xml +++ b/extensions/intellij/.run/Prompt Logs.run.xml @@ -1,6 +1,6 @@ -