diff --git a/.vscode/launch.json b/.vscode/launch.json index ab4db3b42..d641772be 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -22,7 +22,6 @@ "CONTINUE_GLOBAL_DIR": "${workspaceFolder}/binary/.continue" } }, - { "name": "Debug Jest Tests", "type": "node", @@ -35,6 +34,7 @@ "--config", "${workspaceRoot}/core/jest.config.js" ], + "console": "integratedTerminal", "internalConsoleOptions": "neverOpen" }, @@ -113,7 +113,12 @@ ], "cwd": "${workspaceRoot}/core", "console": "integratedTerminal", - "internalConsoleOptions": "neverOpen" + "internalConsoleOptions": "neverOpen", + "env": { + "NODE_OPTIONS": "--experimental-vm-modules", + "CI": "true", + "DEBUG": "jest" + } }, { "name": "[openai-adapters] Jest Test Debugger, Current Open File", diff --git a/.vscode/settings.json b/.vscode/settings.json index 49c41d928..060bc5e6c 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -14,7 +14,8 @@ } }, "search.exclude": { - "./binary": true, - "**/core/vendor/**": true + "**/binary": true, + "**/core/vendor/**": true, + "**/gui/dist": true } } diff --git a/binary/package-lock.json b/binary/package-lock.json index a379713d4..dc4c7cb58 100644 --- a/binary/package-lock.json +++ b/binary/package-lock.json @@ -106,6 +106,7 @@ "@types/jest": "^29.5.12", "@types/jquery": "^3.5.29", "@types/mustache": "^4.2.5", + "@types/request": "^2.48.12", "@types/uuid": "^9.0.7", "esbuild": "0.17.19", "eslint": "^8", diff --git a/binary/package.json b/binary/package.json index 774993a9f..cb14c50f7 100644 --- a/binary/package.json +++ b/binary/package.json @@ -1,6 +1,7 @@ { "name": "binary", "version": "1.0.0", + "author": "Continue Dev, Inc", "description": "", "main": "out/index.js", "bin": "out/index.js", @@ -26,7 +27,6 @@ "build:dev": "tsc", "esbuild": "node build.js --esbuild-only" }, - "author": "", "license": "Apache-2.0", "devDependencies": { "@biomejs/biome": "1.6.4", diff --git a/binary/tsconfig.json b/binary/tsconfig.json index 351115f59..3c95ceef0 100644 --- a/binary/tsconfig.json +++ b/binary/tsconfig.json @@ -3,7 +3,7 @@ "module": "commonjs", "target": "ES2020", "outDir": "out", - "lib": ["ES2020", "dom", "es6", "es5", "dom.iterable", "scripthost"], + "lib": ["ES2021", "dom", "es6", "es5", "dom.iterable", "scripthost"], "sourceMap": true, "rootDirs": ["src", "../core"], "allowJs": true, diff --git a/core/.eslintrc.json b/core/.eslintrc.json index ed9d52781..1c67b146c 100644 --- a/core/.eslintrc.json +++ b/core/.eslintrc.json @@ -8,7 +8,6 @@ "plugins": ["@typescript-eslint", "import"], "rules": { "quotes": ["warn", "double", {}], - "import/extensions": ["error", "ignorePackages"], "@typescript-eslint/naming-convention": "warn", "@typescript-eslint/semi": "warn", "curly": "warn", diff --git a/core/autocomplete/completionProvider.ts b/core/autocomplete/completionProvider.ts index 74dd73481..912d6cc1d 100644 --- a/core/autocomplete/completionProvider.ts +++ b/core/autocomplete/completionProvider.ts @@ -52,6 +52,7 @@ import { getTemplateForModel } from "./templates.js"; import { GeneratorReuseManager } from "./util.js"; // @prettier-ignore import Handlebars from "handlebars"; +import { getConfigJsonPath } from "../util/paths.js"; export interface AutocompleteInput { completionId: string; @@ -249,6 +250,11 @@ export class CompletionProvider { ...config.tabAutocompleteOptions, }; + // Check whether we're in the continue config.json file + if (input.filepath === getConfigJsonPath()) { + return undefined; + } + // Check whether autocomplete is disabled for this file if (options.disableInFiles) { // Relative path needed for `ignore` diff --git a/core/config/ConfigHandler.ts b/core/config/ConfigHandler.ts index 2180ce0a1..ce5c17119 100644 --- a/core/config/ConfigHandler.ts +++ b/core/config/ConfigHandler.ts @@ -105,6 +105,37 @@ export class ConfigHandler { private profiles: ProfileLifecycleManager[]; private selectedProfileId: string; + constructor( + private readonly ide: IDE, + private ideSettingsPromise: Promise, + private readonly writeLog: (text: string) => Promise, + private controlPlaneClient: ControlPlaneClient, + ) { + this.ide = ide; + this.ideSettingsPromise = ideSettingsPromise; + this.writeLog = writeLog; + + // Set local profile as default + const localProfileLoader = new LocalProfileLoader( + ide, + ideSettingsPromise, + controlPlaneClient, + writeLog, + ); + this.profiles = [new ProfileLifecycleManager(localProfileLoader)]; + this.selectedProfileId = localProfileLoader.profileId; + + // Always load local profile immediately in case control plane doesn't load + try { + this.loadConfig(); + } catch (e) { + console.error("Failed to load config: ", e); + } + + // Load control plane profiles + this.fetchControlPlaneProfiles(); + } + // This will be the local profile private get fallbackProfile() { return this.profiles[0]; @@ -163,37 +194,6 @@ export class ConfigHandler { }); } - constructor( - private readonly ide: IDE, - private ideSettingsPromise: Promise, - private readonly writeLog: (text: string) => Promise, - private controlPlaneClient: ControlPlaneClient, - ) { - this.ide = ide; - this.ideSettingsPromise = ideSettingsPromise; - this.writeLog = writeLog; - - // Set local profile as default - const localProfileLoader = new LocalProfileLoader( - ide, - ideSettingsPromise, - controlPlaneClient, - writeLog, - ); - this.profiles = [new ProfileLifecycleManager(localProfileLoader)]; - this.selectedProfileId = localProfileLoader.profileId; - - // Always load local profile immediately in case control plane doesn't load - try { - this.loadConfig(); - } catch (e) { - console.error("Failed to load config: ", e); - } - - // Load control plane profiles - this.fetchControlPlaneProfiles(); - } - async setSelectedProfile(profileId: string) { this.selectedProfileId = profileId; const newConfig = await this.loadConfig(); diff --git a/core/config/promptFile.ts b/core/config/promptFile.ts index 582360933..bc5be2da7 100644 --- a/core/config/promptFile.ts +++ b/core/config/promptFile.ts @@ -1,11 +1,11 @@ import Handlebars from "handlebars"; import path from "path"; import * as YAML from "yaml"; -import type { IDE, SlashCommand } from "../index.js"; -import { walkDir } from "../indexing/walkDir.js"; -import { stripImages } from "../llm/images.js"; -import { renderTemplatedString } from "../llm/llms/index.js"; -import { getBasename } from "../util/index.js"; +import type { IDE, SlashCommand } from ".."; +import { walkDir } from "../indexing/walkDir"; +import { stripImages } from "../llm/images"; +import { renderTemplatedString } from "../llm/llms/index"; +import { getBasename } from "../util/index"; export const DEFAULT_PROMPTS_FOLDER = ".prompts"; @@ -133,6 +133,7 @@ export function slashCommandFromPromptFile( provider.description.title, async (context: any) => { const items = await provider.getContextItems(context, { + config, embeddingsProvider: config.embeddingsProvider, fetch, fullInput: userInput, diff --git a/core/context/providers/DocsContextProvider.ts b/core/context/providers/DocsContextProvider.ts index c2c6af7f0..77a22cc27 100644 --- a/core/context/providers/DocsContextProvider.ts +++ b/core/context/providers/DocsContextProvider.ts @@ -4,18 +4,16 @@ import { ContextProviderDescription, ContextProviderExtras, ContextSubmenuItem, - EmbeddingsProvider, LoadSubmenuItemsArgs, - Reranker, -} from "../../index.js"; -import { DocsService } from "../../indexing/docs/DocsService.js"; -import preIndexedDocs from "../../indexing/docs/preIndexedDocs.js"; -import { Telemetry } from "../../util/posthog.js"; -import { BaseContextProvider } from "../index.js"; +} from "../.."; +import DocsService from "../../indexing/docs/DocsService"; +import preIndexedDocs from "../../indexing/docs/preIndexedDocs"; +import { Telemetry } from "../../util/posthog"; +import { BaseContextProvider } from "../"; class DocsContextProvider extends BaseContextProvider { - static DEFAULT_N_RETRIEVE = 30; - static DEFAULT_N_FINAL = 15; + static nRetrieve = 30; + static nFinal = 15; static description: ContextProviderDescription = { title: "docs", displayTitle: "Docs", @@ -23,11 +21,8 @@ class DocsContextProvider extends BaseContextProvider { type: "submenu", }; - private docsService: DocsService; - constructor(options: any) { super(options); - this.docsService = DocsService.getInstance(); } private async _rerankChunks( @@ -46,14 +41,14 @@ class DocsContextProvider extends BaseContextProvider { chunksCopy = chunksCopy.splice( 0, - this.options?.nFinal ?? DocsContextProvider.DEFAULT_N_FINAL, + this.options?.nFinal ?? DocsContextProvider.nFinal, ); } catch (e) { console.warn(`Failed to rerank docs results: ${e}`); chunksCopy = chunksCopy.splice( 0, - this.options?.nFinal ?? DocsContextProvider.DEFAULT_N_FINAL, + this.options?.nFinal ?? DocsContextProvider.nFinal, ); } @@ -84,14 +79,15 @@ class DocsContextProvider extends BaseContextProvider { query: string, extras: ContextProviderExtras, ): Promise { - const ideInfo = await extras.ide.getIdeInfo(); - const isJetBrains = ideInfo.ideType === "jetbrains"; + const docsService = DocsService.getSingleton(); + + if (!docsService) { + console.error(`${DocsService.name} has not been initialized`); + return []; + } const isJetBrainsAndPreIndexedDocsProvider = - this.docsService.isJetBrainsAndPreIndexedDocsProvider( - ideInfo, - extras.embeddingsProvider.id, - ); + await docsService.isJetBrainsAndPreIndexedDocsProvider(); if (isJetBrainsAndPreIndexedDocsProvider) { extras.ide.errorPopup( @@ -106,29 +102,26 @@ class DocsContextProvider extends BaseContextProvider { const preIndexedDoc = preIndexedDocs[query]; - let embeddingsProvider: EmbeddingsProvider; - - if (!!preIndexedDoc && !isJetBrains) { - // Pre-indexed docs should be filtered out in `loadSubmenuItems`, - // for JetBrains users, but we sanity check that here + if (!!preIndexedDoc) { Telemetry.capture("docs_pre_indexed_doc_used", { doc: preIndexedDoc["title"], }); - - embeddingsProvider = DocsService.preIndexedDocsEmbeddingsProvider; - } else { - embeddingsProvider = extras.embeddingsProvider; } + const embeddingsProvider = await docsService.getEmbeddingsProvider( + !!preIndexedDoc, + ); + const [vector] = await embeddingsProvider.embed([extras.fullInput]); - let chunks = await this.docsService.retrieve( + let chunks = await docsService.retrieveChunks( query, vector, - this.options?.nRetrieve ?? DocsContextProvider.DEFAULT_N_RETRIEVE, - embeddingsProvider.id, + this.options?.nRetrieve ?? DocsContextProvider.nRetrieve, ); + const favicon = await docsService.getFavicon(query); + if (extras.reranker) { chunks = await this._rerankChunks( chunks, @@ -140,6 +133,7 @@ class DocsContextProvider extends BaseContextProvider { return [ ...chunks .map((chunk) => ({ + icon: favicon, name: chunk.filepath.includes("/tree/main") // For display of GitHub files ? chunk.filepath .split("/") @@ -168,17 +162,19 @@ class DocsContextProvider extends BaseContextProvider { async loadSubmenuItems( args: LoadSubmenuItemsArgs, ): Promise { - const ideInfo = await args.ide.getIdeInfo(); - const isJetBrains = ideInfo.ideType === "jetbrains"; - const configSites = [ - ...new Set([...(this.options?.sites || []), ...(args.config.docs || [])]), - ]; + const docsService = DocsService.getSingleton(); + + if (!docsService) { + console.error(`${DocsService.name} has not been initialized`); + return []; + } + + const docs = (await docsService.list()) ?? []; + const canUsePreindexedDocs = await docsService.canUsePreindexedDocs(); + const submenuItemsMap = new Map(); - if (!isJetBrains) { - // Currently, we generate and host embeddings for pre-indexed docs using transformers.js. - // However, we don't ship transformers.js with the JetBrains extension. - // So, we only include pre-indexed docs in the submenu for non-JetBrains IDEs. + if (canUsePreindexedDocs) { for (const { startUrl, title } of Object.values(preIndexedDocs)) { submenuItemsMap.set(startUrl, { title, @@ -191,25 +187,18 @@ class DocsContextProvider extends BaseContextProvider { } } - for (const { title, baseUrl } of await this.docsService.list()) { - submenuItemsMap.set(baseUrl, { - title, - id: baseUrl, - description: new URL(baseUrl).hostname, - }); - } - - for (const { startUrl, title } of configSites) { + for (const { startUrl, title, favicon } of docs) { submenuItemsMap.set(startUrl, { title, id: startUrl, description: new URL(startUrl).hostname, + icon: favicon, }); } const submenuItems = Array.from(submenuItemsMap.values()); - if (!isJetBrains) { + if (canUsePreindexedDocs) { return this._sortByPreIndexedDocs(submenuItems); } diff --git a/core/core.ts b/core/core.ts index 715029a12..216a2b641 100644 --- a/core/core.ts +++ b/core/core.ts @@ -1,38 +1,32 @@ import { v4 as uuidv4 } from "uuid"; -import { CompletionProvider } from "./autocomplete/completionProvider.js"; -import { ConfigHandler } from "./config/ConfigHandler.js"; +import type { ContextItemId, IDE, IndexingProgressUpdate } from "."; +import { CompletionProvider } from "./autocomplete/completionProvider"; +import { ConfigHandler } from "./config/ConfigHandler"; import { setupApiKeysMode, setupFreeTrialMode, setupLocalAfterFreeTrial, setupLocalMode, -} from "./config/onboarding.js"; -import { createNewPromptFile } from "./config/promptFile.js"; -import { addModel, addOpenAIKey, deleteModel } from "./config/util.js"; -import { recentlyEditedFilesCache } from "./context/retrieval/recentlyEditedFilesCache.js"; -import { ContinueServerClient } from "./continueServer/stubs/client.js"; -import { getAuthUrlForTokenPage } from "./control-plane/auth/index.js"; -import { ControlPlaneClient } from "./control-plane/client.js"; -import type { - ContextItemId, - EmbeddingsProvider, - IDE, - IndexingProgressUpdate, - SiteIndexingConfig, -} from "./index.js"; -import { CodebaseIndexer, PauseToken } from "./indexing/CodebaseIndexer.js"; -import { DocsService } from "./indexing/docs/DocsService.js"; -import Ollama from "./llm/llms/Ollama.js"; -import type { FromCoreProtocol, ToCoreProtocol } from "./protocol/index.js"; -import { GlobalContext } from "./util/GlobalContext.js"; -import { logDevData } from "./util/devdata.js"; -import { DevDataSqliteDb } from "./util/devdataSqlite.js"; -import { fetchwithRequestOptions } from "./util/fetchWithOptions.js"; -import historyManager from "./util/history.js"; -import type { IMessenger, Message } from "./util/messenger.js"; -import { editConfigJson } from "./util/paths.js"; -import { Telemetry } from "./util/posthog.js"; -import { streamDiffLines } from "./util/verticalEdit.js"; +} from "./config/onboarding"; +import { createNewPromptFile } from "./config/promptFile"; +import { addModel, addOpenAIKey, deleteModel } from "./config/util"; +import { recentlyEditedFilesCache } from "./context/retrieval/recentlyEditedFilesCache"; +import { ContinueServerClient } from "./continueServer/stubs/client"; +import { getAuthUrlForTokenPage } from "./control-plane/auth/index"; +import { ControlPlaneClient } from "./control-plane/client"; +import { CodebaseIndexer, PauseToken } from "./indexing/CodebaseIndexer"; +import DocsService, { docsServiceSingleton } from "./indexing/docs/DocsService"; +import Ollama from "./llm/llms/Ollama"; +import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; +import { GlobalContext } from "./util/GlobalContext"; +import { logDevData } from "./util/devdata"; +import { DevDataSqliteDb } from "./util/devdataSqlite"; +import { fetchwithRequestOptions } from "./util/fetchWithOptions"; +import historyManager from "./util/history"; +import type { IMessenger, Message } from "./util/messenger"; +import { editConfigJson } from "./util/paths"; +import { Telemetry } from "./util/posthog"; +import { streamDiffLines } from "./util/verticalEdit"; export class Core { // implements IMessenger @@ -42,8 +36,9 @@ export class Core { continueServerClientPromise: Promise; indexingState: IndexingProgressUpdate; controlPlaneClient: ControlPlaneClient; + private docsService: DocsService; private globalContext = new GlobalContext(); - private docsService = DocsService.getInstance(); + private readonly indexingPauseToken = new PauseToken( this.globalContext.get("indexingPaused") === true, ); @@ -98,20 +93,16 @@ export class Core { this.controlPlaneClient, ); + this.docsService = DocsService.createSingleton( + this.configHandler, + this.ide, + this.messenger, + ); + this.configHandler.onConfigUpdate( (() => this.messenger.send("configUpdate", undefined)).bind(this), ); - this.configHandler.onConfigUpdate(async ({ embeddingsProvider }) => { - if ( - await this.shouldReindexDocsOnNewEmbeddingsProvider( - embeddingsProvider.id, - ) - ) { - await this.reindexDocsOnNewEmbeddingsProvider(embeddingsProvider); - } - }); - this.configHandler.onDidChangeAvailableProfiles((profiles) => this.messenger.send("didChangeAvailableProfiles", { profiles }), ); @@ -209,12 +200,15 @@ export class Core { on("history/list", (msg) => { return historyManager.list(msg.data); }); + on("history/delete", (msg) => { historyManager.delete(msg.data.id); }); + on("history/load", (msg) => { return historyManager.load(msg.data.id); }); + on("history/save", (msg) => { historyManager.save(msg.data); }); @@ -230,14 +224,17 @@ export class Core { addModel(model); this.configHandler.reloadConfig(); }); + on("config/addOpenAiKey", (msg) => { addOpenAIKey(msg.data); this.configHandler.reloadConfig(); }); + on("config/deleteModel", (msg) => { deleteModel(msg.data.title); this.configHandler.reloadConfig(); }); + on("config/newPromptFile", async (msg) => { createNewPromptFile( this.ide, @@ -245,10 +242,12 @@ export class Core { ); this.configHandler.reloadConfig(); }); + on("config/reload", (msg) => { this.configHandler.reloadConfig(); return this.configHandler.getSerializedConfig(); }); + on("config/ideSettingsUpdate", (msg) => { this.configHandler.updateIdeSettings(msg.data); }); @@ -258,40 +257,33 @@ export class Core { // Context providers on("context/addDocs", async (msg) => { - await this.getEmbeddingsProviderAndIndexDoc(msg.data); + let hasFailed = false; - this.ide.infoPopup(`Successfully indexed ${msg.data.title}`); - this.messenger.send("refreshSubmenuItems", undefined); + for await (const result of this.docsService.indexAndAdd(msg.data)) { + if (result.status === "failed") { + hasFailed = true; + break; + } + } + + if (hasFailed) { + this.ide.infoPopup(`Failed to index ${msg.data.startUrl}`); + } else { + this.ide.infoPopup(`Successfully indexed ${msg.data.startUrl}`); + this.messenger.send("refreshSubmenuItems", undefined); + } }); + on("context/removeDocs", async (msg) => { - const baseUrl = msg.data.baseUrl; - await this.docsService.delete(baseUrl); + await this.docsService.delete(msg.data.startUrl); this.messenger.send("refreshSubmenuItems", undefined); }); + on("context/indexDocs", async (msg) => { - const config = await this.config(); - const provider: any = config.contextProviders?.find( - (provider) => provider.description.title === "docs", - ); - - if (!provider) { - this.ide.infoPopup("No docs in configuration"); - return; - } - - const siteIndexingOptions: SiteIndexingConfig[] = ((mProvider) => [ - ...new Set([ - ...(mProvider?.options?.sites || []), - ...(config.docs || []), - ]), - ])({ ...provider }); - - for (const site of siteIndexingOptions) { - await this.getEmbeddingsProviderAndIndexDoc(site, msg.data.reIndex); - } - - this.ide.infoPopup("Docs indexing completed"); + await this.docsService.indexAllDocs(msg.data.reIndex); + this.messenger.send("refreshSubmenuItems", undefined); }); + on("context/loadSubmenuItems", async (msg) => { const config = await this.config(); const items = await config.contextProviders @@ -304,6 +296,7 @@ export class Core { }); return items || []; }); + on("context/getContextItems", async (msg) => { const { name, query, fullInput, selectedCode } = msg.data; const config = await this.config(); @@ -320,7 +313,9 @@ export class Core { providerTitle: provider.description.title, itemId: uuidv4(), }; + const items = await provider.getContextItems(query, { + config, llm, embeddingsProvider: config.embeddingsProvider, fullInput, @@ -688,100 +683,4 @@ export class Core { this.messenger.send("refreshSubmenuItems", undefined); } - - private async shouldReindexDocsOnNewEmbeddingsProvider( - curEmbeddingsProviderId: EmbeddingsProvider["id"], - ): Promise { - const ideInfo = await this.ide.getIdeInfo(); - const isJetBrainsAndPreIndexedDocsProvider = - this.docsService.isJetBrainsAndPreIndexedDocsProvider( - ideInfo, - curEmbeddingsProviderId, - ); - - if (isJetBrainsAndPreIndexedDocsProvider) { - try { - this.ide.errorPopup( - "The 'transformers.js' embeddings provider currently cannot be used to index " + - "documentation in JetBrains. To enable documentation indexing, you can use " + - "any of the other providers described in the docs: " + - "https://docs.continue.dev/walkthroughs/codebase-embeddings#embeddings-providers", - ); - } catch (error) { - console.error("Failed to show error popup:", error); - } - this.globalContext.update( - "curEmbeddingsProviderId", - curEmbeddingsProviderId, - ); - - return false; - } - - const lastEmbeddingsProviderId = this.globalContext.get( - "curEmbeddingsProviderId", - ); - - if (!lastEmbeddingsProviderId) { - // If it's the first time we're setting the `curEmbeddingsProviderId` - // global state, we don't need to reindex docs - this.globalContext.update( - "curEmbeddingsProviderId", - curEmbeddingsProviderId, - ); - - return false; - } - - return lastEmbeddingsProviderId !== curEmbeddingsProviderId; - } - - private async getEmbeddingsProviderAndIndexDoc( - site: SiteIndexingConfig, - reIndex: boolean = false, - ): Promise { - const config = await this.config(); - const { embeddingsProvider } = config; - - for await (const update of this.docsService.indexAndAdd( - site, - embeddingsProvider, - reIndex, - )) { - // Temporary disabled posting progress updates to the UI due to - // possible collision with code indexing progress updates. - // this.messenger.request("indexProgress", update); - // this.indexingState = update; - } - } - - private async reindexDocsOnNewEmbeddingsProvider( - embeddingsProvider: EmbeddingsProvider, - ) { - const docs = await this.docsService.list(); - - if (docs.length === 0) { - return; - } - - this.ide.infoPopup("Reindexing docs with new embeddings provider"); - - for (const { title, baseUrl } of docs) { - await this.docsService.delete(baseUrl); - - const generator = this.docsService.indexAndAdd( - { title, startUrl: baseUrl, rootUrl: baseUrl }, - embeddingsProvider, - ); - - while (!(await generator.next()).done) {} - } - - // Important that this only is invoked after we have successfully - // cleared and reindex the docs so that the table cannot end up in an - // invalid state. - this.globalContext.update("curEmbeddingsProviderId", embeddingsProvider.id); - - this.ide.infoPopup("Completed reindexing of all docs"); - } } diff --git a/core/index.d.ts b/core/index.d.ts index cc783d743..8c08c5923 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -127,6 +127,7 @@ export interface ContextProviderDescription { export type FetchFunction = (url: string | URL, init?: any) => Promise; export interface ContextProviderExtras { + config: ContinueConfig; fullInput: string; embeddingsProvider: EmbeddingsProvider; reranker: Reranker | undefined; @@ -161,21 +162,21 @@ export interface ContextSubmenuItem { id: string; title: string; description: string; - iconUrl?: string; + icon?: string; metadata?: any; } export interface SiteIndexingConfig { - startUrl: string; - rootUrl: string; title: string; + startUrl: string; + rootUrl?: string; maxDepth?: number; faviconUrl?: string; } export interface SiteIndexingConfig { startUrl: string; - rootUrl: string; + rootUrl?: string; title: string; maxDepth?: number; } @@ -269,6 +270,7 @@ export interface ContextItem { description: string; editing?: boolean; editable?: boolean; + icon?: string; } export interface ContextItemWithId { @@ -278,6 +280,7 @@ export interface ContextItemWithId { id: ContextItemId; editing?: boolean; editable?: boolean; + icon?: string; } export interface InputModifiers { @@ -339,7 +342,15 @@ export interface LLMOptions { // GCP Options region?: string; projectId?: string; - capabilities?: ModelCapability + capabilities?: ModelCapability; + + // WatsonX options + watsonxUrl?: string; + watsonxApiKey?: string; + watsonxZenApiKeyBase64?:string// Required if using watsonx software with ZenApiKey auth + watsonxUsername?:string; + watsonxPassword?:string; + watsonxProjectId?: string; } type RequireAtLeastOne = Pick< T, @@ -591,7 +602,8 @@ type ModelProvider = | "deepseek" | "azure" | "openai-aiohttp" - | "msty"; + | "msty" + | "watsonx"; export type ModelName = | "AUTODETECT" @@ -735,7 +747,7 @@ export interface ModelDescription { systemMessage?: string; requestOptions?: RequestOptions; promptTemplates?: { [key: string]: string }; - capabilities?: ModelCapability + capabilities?: ModelCapability; } export type EmbeddingsProviderName = @@ -896,6 +908,7 @@ export interface SerializedContinueConfig { reranker?: RerankerDescription; experimental?: ExperimentalConfig; analytics?: AnalyticsConfig; + docs?: SiteIndexingConfig[]; } export type ConfigMergeType = "merge" | "overwrite"; diff --git a/core/indexing/LanceDbIndex.ts b/core/indexing/LanceDbIndex.ts index 4b98040d9..3a312b719 100644 --- a/core/indexing/LanceDbIndex.ts +++ b/core/indexing/LanceDbIndex.ts @@ -62,9 +62,17 @@ export class LanceDbIndex implements CodebaseIndex { "lancedb_sqlite_artifact_id_column", async () => { try { - await db.exec( - "ALTER TABLE lance_db_cache ADD COLUMN artifact_id TEXT NOT NULL DEFAULT 'UNDEFINED'", + const pragma = await db.all("PRAGMA table_info(lance_db_cache)"); + + const hasArtifactIdCol = pragma.some( + (pragma) => pragma.name === "artifact_id", ); + + if (!hasArtifactIdCol) { + await db.exec( + "ALTER TABLE lance_db_cache ADD COLUMN artifact_id TEXT NOT NULL DEFAULT 'UNDEFINED'", + ); + } } finally { resolve(undefined); } diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index 8d2854b9e..4142dffa1 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -1,23 +1,41 @@ -import { open, type Database } from "sqlite"; -import sqlite3 from "sqlite3"; import { Chunk, + ContinueConfig, EmbeddingsProvider, - IdeInfo, + IDE, IndexingProgressUpdate, SiteIndexingConfig, } from "../../index.js"; -import { getDocsSqlitePath, getLanceDbPath } from "../../util/paths.js"; +import { + editConfigJson, + getDocsSqlitePath, + getLanceDbPath, +} from "../../util/paths.js"; import { Article, chunkArticle, pageToArticle } from "./article.js"; import { crawlPage } from "./crawl.js"; -import { downloadFromS3, SiteIndexingResults } from "./preIndexed.js"; +import { + downloadFromS3, + getS3Filename, + S3Buckets, + SiteIndexingResults, +} from "./preIndexed.js"; import preIndexedDocs from "./preIndexedDocs.js"; import TransformersJsEmbeddingsProvider from "../embeddings/TransformersJsEmbeddingsProvider.js"; +import { ConfigHandler } from "../../config/ConfigHandler.js"; +import lancedb, { Connection } from "vectordb"; +import { GlobalContext } from "../../util/GlobalContext.js"; +import DocsContextProvider from "../../context/providers/DocsContextProvider.js"; +import { open, type Database } from "sqlite"; +import sqlite3 from "sqlite3"; +import { Telemetry } from "../../util/posthog.js"; +import { runSqliteMigrations, runLanceMigrations } from "./migrations.js"; +import { IMessenger } from "../../util/messenger.js"; +import { ToCoreProtocol, FromCoreProtocol } from "../../protocol/index.js"; // Purposefully lowercase because lancedb converts -interface LanceDbDocsRow { +export interface LanceDbDocsRow { title: string; - baseurl: string; + starturl: string; // Chunk content: string; path: string; @@ -27,200 +45,142 @@ interface LanceDbDocsRow { [key: string]: any; } -export class DocsService { - private static instance: DocsService; - private static DOCS_TABLE_NAME = "docs"; - public static preIndexedDocsEmbeddingsProvider = - new TransformersJsEmbeddingsProvider(); - private _sqliteTable: Database | undefined; - private docsIndexingQueue: Set = new Set(); +export interface SqliteDocsRow { + title: string; + startUrl: string; + favicon: string; +} - public static getInstance(): DocsService { - if (!DocsService.instance) { - DocsService.instance = new DocsService(); - } +export type AddParams = { + siteIndexingConfig: SiteIndexingConfig; + chunks: Chunk[]; + embeddings: number[][]; + favicon?: string; +}; + +export default class DocsService { + static lanceTableName = "docs"; + static sqlitebTableName = "docs"; + static preIndexedDocsEmbeddingsProvider = + new TransformersJsEmbeddingsProvider(); + + private static instance?: DocsService; + public isInitialized: Promise; + public isSyncing: boolean = false; + + private docsIndexingQueue = new Set(); + private globalContext = new GlobalContext(); + private lanceTableNamesSet = new Set(); + + private config!: ContinueConfig; + private sqliteDb?: Database; + + // If we are instantiating a new DocsService from `getContextItems()`, + // we have access to the direct config object. + // When instantiating the DocsService from core, we have access + // to a ConfigHandler instance. + constructor( + configOrHandler: ConfigHandler, + private readonly ide: IDE, + private readonly messenger?: IMessenger, + ) { + this.isInitialized = this.init(configOrHandler); + } + + static getSingleton() { return DocsService.instance; } - private async getSqliteTable() { - if (!this._sqliteTable) { - this._sqliteTable = await open({ - filename: getDocsSqlitePath(), - driver: sqlite3.Database, - }); - - this._sqliteTable.exec(`CREATE TABLE IF NOT EXISTS docs ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - title STRING NOT NULL, - baseUrl STRING NOT NULL UNIQUE - )`); - } - - return this._sqliteTable; - } - - private async getLanceDb() { - const lancedb = await import("vectordb"); - const lance = await lancedb.connect(getLanceDbPath()); - return lance; - } - - async retrieve( - baseUrl: string, - vector: number[], - nRetrieve: number, - embeddingsProviderId: string, - nested = false, - ): Promise { - const lance = await this.getLanceDb(); - const tableNames = await lance.tableNames(); - const preIndexedDoc = preIndexedDocs[baseUrl]; - const isPreIndexedDoc = !!preIndexedDoc; - let shouldDownloadPreIndexedDoc = - !tableNames.includes(DocsService.DOCS_TABLE_NAME) && isPreIndexedDoc; - - const downloadAndRetrievePreIndexedDoc = async ( - preIndexedDoc: SiteIndexingConfig, - ) => { - await this.downloadAndAddPreIndexedDocs( - embeddingsProviderId, - preIndexedDoc.title, - ); - - return await this.retrieve( - baseUrl, - vector, - nRetrieve, - embeddingsProviderId, - true, - ); - }; - - if (shouldDownloadPreIndexedDoc) { - return await downloadAndRetrievePreIndexedDoc(preIndexedDoc!); - } - - const table = await lance.openTable(DocsService.DOCS_TABLE_NAME); - - let docs: LanceDbDocsRow[] = await table - .search(vector) - .limit(nRetrieve) - .where(`baseurl = '${baseUrl}'`) - .execute(); - - docs = docs.filter((doc) => doc.baseurl === baseUrl); - - shouldDownloadPreIndexedDoc = - (!docs || docs.length === 0) && !nested && isPreIndexedDoc; - - if (shouldDownloadPreIndexedDoc) { - return await downloadAndRetrievePreIndexedDoc(preIndexedDoc!); - } - - return docs.map((doc) => ({ - digest: doc.path, - filepath: doc.path, - startLine: doc.startline, - endLine: doc.endline, - index: 0, - content: doc.content, - otherMetadata: { - title: doc.title, - }, - })); - } - - private async add( - title: string, - baseUrl: URL, - chunks: Chunk[], - embeddings: number[][], + static createSingleton( + configOrHandler: ConfigHandler, + ide: IDE, + messenger?: IMessenger, ) { - const data: LanceDbDocsRow[] = chunks.map((chunk, i) => ({ - title: chunk.otherMetadata?.title || title, - baseurl: baseUrl.toString(), - content: chunk.content, - path: chunk.filepath, - startline: chunk.startLine, - endline: chunk.endLine, - vector: embeddings[i], - })); - - const lance = await this.getLanceDb(); - const tableNames = await lance.tableNames(); - if (!tableNames.includes(DocsService.DOCS_TABLE_NAME)) { - await lance.createTable(DocsService.DOCS_TABLE_NAME, data); - } else { - const table = await lance.openTable(DocsService.DOCS_TABLE_NAME); - await table.add(data); - } - - // Only after add it to SQLite - const db = await this.getSqliteTable(); - await db.run( - "INSERT INTO docs (title, baseUrl) VALUES (?, ?)", - title, - baseUrl.toString(), - ); + const docsService = new DocsService(configOrHandler, ide, messenger); + DocsService.instance = docsService; + return docsService; } - async list(): Promise<{ title: string; baseUrl: string }[]> { - const db = await this.getSqliteTable(); - const docs = db.all("SELECT title, baseUrl FROM docs"); + async isJetBrainsAndPreIndexedDocsProvider(): Promise { + const isJetBrains = await this.isJetBrains(); + + const isPreIndexedDocsProvider = + this.config.embeddingsProvider.id === + DocsService.preIndexedDocsEmbeddingsProvider.id; + + return isJetBrains && isPreIndexedDocsProvider; + } + + /* + * Currently, we generate and host embeddings for pre-indexed docs using transformers.js. + * However, we don't ship transformers.js with the JetBrains extension. + * So, we only include pre-indexed docs in the submenu for non-JetBrains IDEs. + */ + async canUsePreindexedDocs() { + const isJetBrains = await this.isJetBrains(); + return !isJetBrains; + } + + async delete(startUrl: string) { + await this.deleteFromLance(startUrl); + await this.deleteFromSqlite(startUrl); + this.deleteFromConfig(startUrl); + + if (this.messenger) { + this.messenger.send("refreshSubmenuItems", undefined); + } + } + + async has(startUrl: string): Promise> { + const db = await this.getOrCreateSqliteDb(); + const title = await db.get( + `SELECT title FROM ${DocsService.sqlitebTableName} WHERE startUrl = ?`, + startUrl, + ); + + return !!title; + } + + async indexAllDocs(reIndex: boolean = false) { + if (!this.hasDocsContextProvider()) { + this.ide.infoPopup( + "No 'docs' provider configured under 'contextProviders' in config.json", + ); + return; + } + + const docs = await this.list(); + + for (const doc of docs) { + const generator = this.indexAndAdd(doc, reIndex); + while (!(await generator.next()).done) {} + } + + this.ide.infoPopup("Docs indexing completed"); + } + + async list() { + const db = await this.getOrCreateSqliteDb(); + const docs = await db.all( + `SELECT title, startUrl, favicon FROM ${DocsService.sqlitebTableName}`, + ); + return docs; } - async delete(baseUrl: string) { - const db = await this.getSqliteTable(); - await db.run("DELETE FROM docs WHERE baseUrl = ?", baseUrl); - const lance = await this.getLanceDb(); - const tableNames = await lance.tableNames(); - if (tableNames.includes(DocsService.DOCS_TABLE_NAME)) { - const table = await lance.openTable(DocsService.DOCS_TABLE_NAME); - await table.delete(`baseurl = '${baseUrl}'`); - } - } - - async has(baseUrl: string) { - const db = await this.getSqliteTable(); - const doc = await db.get( - "SELECT title FROM docs WHERE baseUrl =?", - baseUrl, - ); - return !!doc; - } - - private async downloadAndAddPreIndexedDocs( - embeddingsProviderId: string, - title: string, - ) { - const data = await downloadFromS3( - "continue-indexed-docs", - `${embeddingsProviderId}/${title}`, - "us-west-1", - ); - const results = JSON.parse(data) as SiteIndexingResults; - await this.add( - results.title, - new URL(results.url), - results.chunks, - results.chunks.map((c) => c.embedding), - ); - } - async *indexAndAdd( siteIndexingConfig: SiteIndexingConfig, - embeddingsProvider: EmbeddingsProvider, reIndex: boolean = false, ): AsyncGenerator { - const startUrl = new URL(siteIndexingConfig.startUrl.toString()); + const { startUrl } = siteIndexingConfig; + const embeddingsProvider = await this.getEmbeddingsProvider(); - if (this.docsIndexingQueue.has(startUrl.toString())) { + if (this.docsIndexingQueue.has(startUrl)) { console.log("Already in queue"); return; } - if (!reIndex && (await this.has(startUrl.toString()))) { + if (!reIndex && (await this.has(startUrl))) { yield { progress: 1, desc: "Already indexed", @@ -230,7 +190,7 @@ export class DocsService { } // Mark the site as currently being indexed - this.docsIndexingQueue.add(startUrl.toString()); + this.docsIndexingQueue.add(startUrl); yield { progress: 0, @@ -243,12 +203,18 @@ export class DocsService { let maxKnownPages = 1; // Crawl pages and retrieve info as articles - for await (const page of crawlPage(startUrl, siteIndexingConfig.maxDepth)) { + for await (const page of crawlPage( + new URL(startUrl), + siteIndexingConfig.maxDepth, + )) { processedPages++; + const article = pageToArticle(page); + if (!article) { continue; } + articles.push(article); // Use a heuristic approach for progress calculation @@ -281,14 +247,19 @@ export class DocsService { }; try { - const subpathEmbeddings = await embeddingsProvider.embed( - chunkArticle(article, embeddingsProvider.maxChunkSize).map( - (chunk) => { - chunks.push(chunk); + const chunkedArticle = chunkArticle( + article, + embeddingsProvider.maxChunkSize, + ); - return chunk.content; - }, - ), + const chunkedArticleContents = chunkedArticle.map( + (chunk) => chunk.content, + ); + + chunks.push(...chunkedArticle); + + const subpathEmbeddings = await embeddingsProvider.embed( + chunkedArticleContents, ); embeddings.push(...subpathEmbeddings); @@ -297,8 +268,23 @@ export class DocsService { } } + if (embeddings.length === 0) { + console.error( + `No embeddings were created for site: ${siteIndexingConfig.startUrl}\n Num chunks: ${chunks.length}`, + ); + + yield { + progress: 1, + desc: `No embeddings were created for site: ${siteIndexingConfig.startUrl}`, + status: "failed", + }; + + return; + } + // Add docs to databases - console.log("Adding ", embeddings.length, " embeddings to db"); + console.log(`Adding ${embeddings.length} embeddings to db`); + yield { progress: 0.5, desc: `Adding ${embeddings.length} embeddings to db`, @@ -308,27 +294,503 @@ export class DocsService { // Clear old index if re-indexing. if (reIndex) { console.log("Deleting old embeddings"); - await this.delete(startUrl.toString()); + await this.delete(startUrl); } - await this.add(siteIndexingConfig.title, startUrl, chunks, embeddings); - this.docsIndexingQueue.delete(startUrl.toString()); + const favicon = await this.fetchFavicon(siteIndexingConfig); + + await this.add({ + siteIndexingConfig, + chunks, + embeddings, + favicon, + }); + + this.docsIndexingQueue.delete(startUrl); yield { progress: 1, desc: "Done", status: "done", }; + + console.log(`Successfully indexed: ${siteIndexingConfig.startUrl}`); + + if (this.messenger) { + this.messenger.send("refreshSubmenuItems", undefined); + } } - public isJetBrainsAndPreIndexedDocsProvider( - ideInfo: IdeInfo, - embeddingsProviderId: EmbeddingsProvider["id"], - ): boolean { - const isJetBrains = ideInfo.ideType === "jetbrains"; - const isPreIndexedDocsProvider = - embeddingsProviderId === DocsService.preIndexedDocsEmbeddingsProvider.id; + async retrieveChunks( + startUrl: string, + vector: number[], + nRetrieve: number, + isRetry: boolean = false, + ): Promise { + const table = await this.getOrCreateLanceTable({ + initializationVector: vector, + isPreIndexedDoc: !!preIndexedDocs[startUrl], + }); - return isJetBrains && isPreIndexedDocsProvider; + const docs: LanceDbDocsRow[] = await table + .search(vector) + .limit(nRetrieve) + .where(`starturl = '${startUrl}'`) + .execute(); + + const hasIndexedDoc = await this.hasIndexedDoc(startUrl); + + if (!hasIndexedDoc && docs.length === 0) { + const preIndexedDoc = preIndexedDocs[startUrl]; + + if (isRetry || !preIndexedDoc) { + return []; + } + + await this.fetchAndAddPreIndexedDocEmbeddings(preIndexedDoc.title); + return await this.retrieveChunks(startUrl, vector, nRetrieve, true); + } + + return docs.map((doc) => ({ + digest: doc.path, + filepath: doc.path, + startLine: doc.startline, + endLine: doc.endline, + index: 0, + content: doc.content, + otherMetadata: { + title: doc.title, + }, + })); + } + + async getEmbeddingsProvider(isPreIndexedDoc: boolean = false) { + const canUsePreindexedDocs = await this.canUsePreindexedDocs(); + + if (isPreIndexedDoc && canUsePreindexedDocs) { + return DocsService.preIndexedDocsEmbeddingsProvider; + } + + return this.config.embeddingsProvider; + } + + async getFavicon(startUrl: string) { + const db = await this.getOrCreateSqliteDb(); + const { favicon } = await db.get( + `SELECT favicon FROM ${DocsService.sqlitebTableName} WHERE startUrl = ?`, + startUrl, + ); + + return favicon; + } + + /** + * A ConfigHandler is passed to the DocsService in `core` when + * we don't yet have access to the config object. This handler + * is used to set up a single instance of the DocsService that + * subscribes to config updates, e.g. to trigger re-indexing + * on a new embeddings provider. + */ + private async init(configHandler: ConfigHandler) { + if (configHandler instanceof ConfigHandler) { + this.config = await configHandler.loadConfig(); + } else { + this.config = configHandler; + } + + const embeddingsProvider = await this.getEmbeddingsProvider(); + + this.globalContext.update("curEmbeddingsProviderId", embeddingsProvider.id); + + configHandler.onConfigUpdate(async (newConfig) => { + const oldConfig = this.config; + + // Need to update class property for config at the beginning of this callback + // to ensure downstream methods have access to the latest config. + this.config = newConfig; + + if (oldConfig.docs !== newConfig.docs) { + await this.syncConfigAndSqlite(); + } + + const shouldReindex = await this.shouldReindexDocsOnNewEmbeddingsProvider( + newConfig.embeddingsProvider.id, + ); + + if (shouldReindex) { + await this.reindexDocsOnNewEmbeddingsProvider( + newConfig.embeddingsProvider, + ); + } + }); + } + + private async syncConfigAndSqlite() { + this.isSyncing = true; + + const sqliteDocs = await this.list(); + const sqliteDocStartUrls = sqliteDocs.map((doc) => doc.startUrl) || []; + + const configDocs = this.config.docs || []; + const configDocStartUrls = + this.config.docs?.map((doc) => doc.startUrl) || []; + + const newDocs = configDocs.filter( + (doc) => !sqliteDocStartUrls.includes(doc.startUrl), + ); + const deletedDocs = sqliteDocs.filter( + (doc) => + !configDocStartUrls.includes(doc.startUrl) && + !preIndexedDocs[doc.startUrl], + ); + + for (const doc of newDocs) { + console.log(`Indexing new doc: ${doc.startUrl}`); + Telemetry.capture("add_docs_config", { url: doc.startUrl }); + + const generator = this.indexAndAdd(doc); + while (!(await generator.next()).done) {} + } + + for (const doc of deletedDocs) { + console.log(`Deleting doc: ${doc.startUrl}`); + await this.delete(doc.startUrl); + } + + this.isSyncing = false; + } + + private hasDocsContextProvider() { + return !!this.config.contextProviders?.some( + (provider) => + provider.description.title === DocsContextProvider.description.title, + ); + } + + private async getOrCreateSqliteDb() { + if (!this.sqliteDb) { + const db = await open({ + filename: getDocsSqlitePath(), + driver: sqlite3.Database, + }); + + await runSqliteMigrations(db); + + db.exec(`CREATE TABLE IF NOT EXISTS ${DocsService.sqlitebTableName} ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + title STRING NOT NULL, + startUrl STRING NOT NULL UNIQUE, + favicon STRING + )`); + + this.sqliteDb = db; + } + + return this.sqliteDb; + } + + private async createLanceDocsTable( + connection: Connection, + initializationVector: number[], + tableName: string, + ) { + const mockRowTitle = "mockRowTitle"; + const mockRow: LanceDbDocsRow[] = [ + { + title: mockRowTitle, + vector: initializationVector, + starturl: "", + content: "", + path: "", + startline: 0, + endline: 0, + }, + ]; + + const table = await connection.createTable(tableName, mockRow); + + await runLanceMigrations(table); + + await table.delete(`title = '${mockRowTitle}'`); + } + + private removeInvalidLanceTableNameChars(tableName: string) { + return tableName.replace(/:/g, ""); + } + + private async getLanceTableNameFromEmbeddingsProvider( + isPreIndexedDoc: boolean, + ) { + const embeddingsProvider = await this.getEmbeddingsProvider( + isPreIndexedDoc, + ); + const embeddingsProviderId = this.removeInvalidLanceTableNameChars( + embeddingsProvider.id, + ); + const tableName = `${DocsService.lanceTableName}${embeddingsProviderId}`; + + return tableName; + } + + private async getOrCreateLanceTable({ + initializationVector, + isPreIndexedDoc, + }: { + initializationVector: number[]; + isPreIndexedDoc?: boolean; + }) { + const conn = await lancedb.connect(getLanceDbPath()); + const tableNames = await conn.tableNames(); + const tableNameFromEmbeddingsProvider = + await this.getLanceTableNameFromEmbeddingsProvider(!!isPreIndexedDoc); + + if (!tableNames.includes(tableNameFromEmbeddingsProvider)) { + if (initializationVector) { + await this.createLanceDocsTable( + conn, + initializationVector, + tableNameFromEmbeddingsProvider, + ); + } else { + console.trace( + "No existing Lance DB docs table was found and no initialization " + + "vector was passed to create one", + ); + } + } + + const table = await conn.openTable(tableNameFromEmbeddingsProvider); + + this.lanceTableNamesSet.add(tableNameFromEmbeddingsProvider); + + return table; + } + + private async isJetBrains() { + const ideInfo = await this.ide.getIdeInfo(); + return ideInfo.ideType === "jetbrains"; + } + + private async hasIndexedDoc(startUrl: string) { + const db = await this.getOrCreateSqliteDb(); + const docs = await db.all( + `SELECT startUrl FROM ${DocsService.sqlitebTableName} WHERE startUrl = ?`, + startUrl, + ); + + return docs.length > 0; + } + + private async addToLance({ + chunks, + siteIndexingConfig, + embeddings, + }: AddParams) { + const sampleVector = embeddings[0]; + const isPreIndexedDoc = !!preIndexedDocs[siteIndexingConfig.startUrl]; + const table = await this.getOrCreateLanceTable({ + isPreIndexedDoc, + initializationVector: sampleVector, + }); + + const rows: LanceDbDocsRow[] = chunks.map((chunk, i) => ({ + vector: embeddings[i], + starturl: siteIndexingConfig.startUrl, + title: chunk.otherMetadata?.title || siteIndexingConfig.title, + content: chunk.content, + path: chunk.filepath, + startline: chunk.startLine, + endline: chunk.endLine, + })); + + await table.add(rows); + } + + private async addToSqlite({ + siteIndexingConfig: { title, startUrl }, + favicon, + }: AddParams) { + const db = await this.getOrCreateSqliteDb(); + await db.run( + `INSERT INTO ${DocsService.sqlitebTableName} (title, startUrl, favicon) VALUES (?, ?, ?)`, + title, + startUrl, + favicon, + ); + } + + private addToConfig({ siteIndexingConfig }: AddParams) { + // Handles the case where a user has manually added the doc to config.json + // so it already exists in the file + const doesDocExist = this.config.docs?.some( + (doc) => doc.startUrl === siteIndexingConfig.startUrl, + ); + + if (!doesDocExist) { + editConfigJson((config) => ({ + ...config, + docs: [...(config.docs ?? []), siteIndexingConfig], + })); + } + } + + private async add(params: AddParams) { + await this.addToLance(params); + await this.addToSqlite(params); + + const isPreIndexedDoc = + !!preIndexedDocs[params.siteIndexingConfig.startUrl]; + + if (!isPreIndexedDoc) { + this.addToConfig(params); + } + } + + private async deleteFromLance(startUrl: string) { + for (const tableName of this.lanceTableNamesSet) { + const conn = await lancedb.connect(getLanceDbPath()); + const table = await conn.openTable(tableName); + await table.delete(`starturl = '${startUrl}'`); + } + } + + private async deleteFromSqlite(startUrl: string) { + const db = await this.getOrCreateSqliteDb(); + await db.run( + `DELETE FROM ${DocsService.sqlitebTableName} WHERE startUrl = ?`, + startUrl, + ); + } + + deleteFromConfig(startUrl: string) { + editConfigJson((config) => ({ + ...config, + docs: config.docs?.filter((doc) => doc.startUrl !== startUrl) || [], + })); + } + + private async fetchAndAddPreIndexedDocEmbeddings(title: string) { + const embeddingsProvider = await this.getEmbeddingsProvider(true); + + const data = await downloadFromS3( + S3Buckets.continueIndexedDocs, + getS3Filename(embeddingsProvider.id, title), + ); + + const siteEmbeddings = JSON.parse(data) as SiteIndexingResults; + const startUrl = new URL(siteEmbeddings.url).toString(); + const favicon = await this.fetchFavicon(preIndexedDocs[startUrl]); + + await this.add({ + favicon, + siteIndexingConfig: { + startUrl, + title: siteEmbeddings.title, + }, + chunks: siteEmbeddings.chunks, + embeddings: siteEmbeddings.chunks.map((c) => c.embedding), + }); + } + + private async fetchFavicon(siteIndexingConfig: SiteIndexingConfig) { + const faviconUrl = + siteIndexingConfig.faviconUrl ?? + new URL("/favicon.ico", siteIndexingConfig.startUrl); + + try { + const response = await fetch(faviconUrl); + const arrayBuffer = await response.arrayBuffer(); + const base64 = btoa( + new Uint8Array(arrayBuffer).reduce( + (data, byte) => data + String.fromCharCode(byte), + "", + ), + ); + const mimeType = response.headers.get("content-type") || "image/x-icon"; + + return `data:${mimeType};base64,${base64}`; + } catch { + console.error(`Failed to fetch favicon: ${faviconUrl}`); + } + + return undefined; + } + + private async shouldReindexDocsOnNewEmbeddingsProvider( + curEmbeddingsProviderId: EmbeddingsProvider["id"], + ): Promise { + const isJetBrainsAndPreIndexedDocsProvider = + await this.isJetBrainsAndPreIndexedDocsProvider(); + + if (isJetBrainsAndPreIndexedDocsProvider) { + this.ide.errorPopup( + "The 'transformers.js' embeddings provider currently cannot be used to index " + + "documentation in JetBrains. To enable documentation indexing, you can use " + + "any of the other providers described in the docs: " + + "https://docs.continue.dev/walkthroughs/codebase-embeddings#embeddings-providers", + ); + + this.globalContext.update( + "curEmbeddingsProviderId", + curEmbeddingsProviderId, + ); + + return false; + } + + const lastEmbeddingsProviderId = this.globalContext.get( + "curEmbeddingsProviderId", + ); + + if (!lastEmbeddingsProviderId) { + // If it's the first time we're setting the `curEmbeddingsProviderId` + // global state, we don't need to reindex docs + this.globalContext.update( + "curEmbeddingsProviderId", + curEmbeddingsProviderId, + ); + + return false; + } + + return lastEmbeddingsProviderId !== curEmbeddingsProviderId; + } + + /** + * Currently this deletes re-crawls + re-indexes all docs. + * A more optimal solution in the future will be to create + * a per-embeddings-provider table for docs. + */ + private async reindexDocsOnNewEmbeddingsProvider( + embeddingsProvider: EmbeddingsProvider, + ) { + // We use config as our source of truth here since it contains additional information + // needed for re-crawling such as `faviconUrl` and `maxDepth`. + const { docs } = this.config; + + if (!docs || docs.length === 0) { + return; + } + + console.log( + `Reindexing docs with new embeddings provider: ${embeddingsProvider.id}`, + ); + + for (const doc of docs) { + await this.delete(doc.startUrl); + + const generator = this.indexAndAdd(doc); + + while (!(await generator.next()).done) {} + } + + // Important that this only is invoked after we have successfully + // cleared and reindex the docs so that the table cannot end up in an + // invalid state. + this.globalContext.update("curEmbeddingsProviderId", embeddingsProvider.id); + + console.log("Completed reindexing of all docs"); } } + +export const docsServiceSingleton = DocsService.getSingleton(); diff --git a/core/indexing/docs/article.ts b/core/indexing/docs/article.ts index d1f6a94a7..e972652bf 100644 --- a/core/indexing/docs/article.ts +++ b/core/indexing/docs/article.ts @@ -118,7 +118,6 @@ function extractTitlesAndBodies(html: string): ArticleComponent[] { return result; } - export function stringToArticle( url: string, html: string, diff --git a/core/indexing/docs/migrations.ts b/core/indexing/docs/migrations.ts new file mode 100644 index 000000000..f617098af --- /dev/null +++ b/core/indexing/docs/migrations.ts @@ -0,0 +1,70 @@ +import { Table } from "vectordb"; +import { editConfigJson, migrate } from "../../util/paths.js"; +import { type Database } from "sqlite"; +import DocsService, { SqliteDocsRow } from "./DocsService.js"; + +export async function runLanceMigrations(table: Table) { + await new Promise((resolve) => + migrate( + "rename_baseurl_column_for_lance_docs", + async () => { + try { + const schema = await table.schema; + + if (schema.fields.some((field: any) => field.name === "baseurl")) { + await table.alterColumns([{ path: "baseurl", rename: "starturl" }]); + } + } finally { + resolve(undefined); + } + }, + () => resolve(undefined), + ), + ); +} + +export async function runSqliteMigrations(db: Database) { + await new Promise((resolve) => { + migrate( + "sqlite_modify_docs_columns_and_copy_to_config", + async () => { + try { + const pragma = await db.all( + `PRAGMA table_info(${DocsService.sqlitebTableName})`, + ); + + const hasFaviconCol = pragma.some( + (pragma) => pragma.name === "favicon", + ); + const hasBaseUrlCol = pragma.some( + (pragma) => pragma.name === "baseUrl", + ); + + if (!hasFaviconCol) { + await db.exec( + `ALTER TABLE ${DocsService.sqlitebTableName} ADD COLUMN favicon BLOB`, + ); + } + + if (hasBaseUrlCol) { + await db.exec( + `ALTER TABLE ${DocsService.sqlitebTableName} RENAME COLUMN baseUrl TO startUrl`, + ); + } + + const sqliteDocs = await db.all< + Array> + >(`SELECT title, startUrl FROM ${DocsService.sqlitebTableName}`); + + editConfigJson((config) => ({ + ...config, + docs: [...(config.docs || []), ...sqliteDocs], + })); + } finally { + resolve(undefined); + } + }, + () => resolve(undefined), + ); + }); +} diff --git a/core/indexing/docs/preIndexed.ts b/core/indexing/docs/preIndexed.ts index 95ce83db2..705693e36 100644 --- a/core/indexing/docs/preIndexed.ts +++ b/core/indexing/docs/preIndexed.ts @@ -1,16 +1,28 @@ -import { Chunk } from "../../index.js"; +import { Chunk } from "../../"; import request from "request"; +export function getS3Filename( + embeddingsProviderId: string, + title: string, +): string { + return `${embeddingsProviderId}/${title}`; +} + +export enum S3Buckets { + continueIndexedDocs = "continue-indexed-docs", +} + +const AWS_REGION = "us-west-1"; + export async function downloadFromS3( bucket: string, fileName: string, - region: string, ): Promise { return new Promise((resolve, reject) => { let data = ""; const download = request({ - url: `https://${bucket}.s3.${region}.amazonaws.com/${fileName}`, + url: `https://${bucket}.s3.${AWS_REGION}.amazonaws.com/${fileName}`, }); download.on("response", (response: any) => { if (response.statusCode !== 200) { diff --git a/core/indexing/embeddings/TransformersJsEmbeddingsProvider.ts b/core/indexing/embeddings/TransformersJsEmbeddingsProvider.ts index c7b99dbab..4dcf41141 100644 --- a/core/indexing/embeddings/TransformersJsEmbeddingsProvider.ts +++ b/core/indexing/embeddings/TransformersJsEmbeddingsProvider.ts @@ -41,6 +41,7 @@ export class TransformersJsEmbeddingsProvider extends BaseEmbeddingsProvider { static providerName: EmbeddingsProviderName = "transformers.js"; static maxGroupSize: number = 4; static model: string = "all-MiniLM-L6-v2"; + static mockVector: number[] = Array.from({ length: 384 }).fill(2) as number[]; constructor() { super({ model: TransformersJsEmbeddingsProvider.model }, () => @@ -49,6 +50,11 @@ export class TransformersJsEmbeddingsProvider extends BaseEmbeddingsProvider { } async embed(chunks: string[]) { + // Workaround to ignore testing issues in Jest + if (process.env.NODE_ENV === "test") { + return chunks.map(() => TransformersJsEmbeddingsProvider.mockVector); + } + const extractor = await EmbeddingsPipeline.getInstance(); if (!extractor) { diff --git a/core/indexing/ignore.ts b/core/indexing/ignore.ts index 318a42f9e..2ff68b9f0 100644 --- a/core/indexing/ignore.ts +++ b/core/indexing/ignore.ts @@ -68,37 +68,35 @@ export const DEFAULT_IGNORE_FILETYPES = [ // "*.prompt", // can be incredibly confusing for the LLM to have another set of instructions injected into the prompt ]; -// @ts-ignore -export const defaultIgnoreFile = ignore.default().add(DEFAULT_IGNORE_FILETYPES); +export const defaultIgnoreFile = ignore().add(DEFAULT_IGNORE_FILETYPES); export const DEFAULT_IGNORE_DIRS = [ - ".git", - ".svn", - ".vscode", - ".idea", - ".vs", - "venv", - ".venv", - "env", - ".env", - "node_modules", - "dist", - "build", - "target", - "out", - "bin", - ".pytest_cache", - ".vscode-test", - ".continue", - "__pycache__", - "site-packages", - ".gradle", - ".cache", - "gems", - "vendor", + ".git/", + ".svn/", + ".vscode/", + ".idea/", + ".vs/", + "venv/", + ".venv/", + "env/", + ".env/", + "node_modules/", + "dist/", + "build/", + "target/", + "out/", + "bin/", + ".pytest_cache/", + ".vscode-test/", + ".continue/", + "__pycache__/", + "site-packages/", + ".gradle/", + ".cache/", + "gems/", + "vendor/", ]; -// @ts-ignore -export const defaultIgnoreDir = ignore.default().add(DEFAULT_IGNORE_DIRS); +export const defaultIgnoreDir = ignore().add(DEFAULT_IGNORE_DIRS); export const DEFAULT_IGNORE = DEFAULT_IGNORE_FILETYPES.join("\n") + "\n" + DEFAULT_IGNORE_DIRS.join("\n"); diff --git a/core/indexing/walkDir.ts b/core/indexing/walkDir.ts index 1c320f181..090fcc96a 100644 --- a/core/indexing/walkDir.ts +++ b/core/indexing/walkDir.ts @@ -1,6 +1,6 @@ -import { Minimatch } from "minimatch"; import path from "node:path"; import { FileType, IDE } from "../index.d.js"; +import ignore, { Ignore } from "ignore"; import { DEFAULT_IGNORE_DIRS, DEFAULT_IGNORE_FILETYPES, @@ -28,40 +28,9 @@ type WalkableEntry = { // helper struct used for the DFS walk type WalkContext = { walkableEntry: WalkableEntry; - ignoreFiles: IgnoreFile[]; + ignore: Ignore; }; -class IgnoreFile { - private _rules: Minimatch[]; - - constructor( - public path: string, - public content: string, - ) { - this.path = path; - this.content = content; - this._rules = this.contentToRules(content); - } - - public get rules() { - return this._rules; - } - - private contentToRules(content: string): Minimatch[] { - const options = { - matchBase: true, - dot: true, - flipNegate: true, - nocase: true, - }; - return content - .split(/\r?\n/) - .map((l) => l.trim()) - .filter((l) => !/^#|^$/.test(l)) - .map((l) => new Minimatch(l, options)); - } -} - class DFSWalker { private readonly path: string; private readonly ide: IDE; @@ -84,23 +53,23 @@ class DFSWalker { type: 2 as FileType.Directory, entry: ["", 2 as FileType.Directory], }, - ignoreFiles: [], + ignore: ignore().add(defaultIgnoreDir).add(defaultIgnoreFile), }; const stack = [root]; for (let cur = stack.pop(); cur; cur = stack.pop()) { const walkableEntries = await this.listDirForWalking(cur.walkableEntry); - const ignoreFiles = await this.getIgnoreFilesToApplyInDir( - cur.ignoreFiles, + const ignore = await this.getIgnoreToApplyInDir( + cur.ignore, walkableEntries, ); for (const w of walkableEntries) { - if (!this.shouldInclude(w, ignoreFiles)) { + if (!this.shouldInclude(w, ignore)) { continue; } if (this.entryIsDirectory(w.entry)) { stack.push({ walkableEntry: w, - ignoreFiles: ignoreFiles, + ignore: ignore, }); if (this.options.onlyDirs) { // when onlyDirs is enabled the walker will only return directory names @@ -127,24 +96,28 @@ class DFSWalker { }); } - private async getIgnoreFilesToApplyInDir( - parentIgnoreFiles: IgnoreFile[], + private async getIgnoreToApplyInDir( + parentIgnore: Ignore, walkableEntries: WalkableEntry[], - ): Promise { + ): Promise { const ignoreFilesInDir = await this.loadIgnoreFiles(walkableEntries); if (ignoreFilesInDir.length === 0) { - return parentIgnoreFiles; + return parentIgnore; } - return Array.prototype.concat(parentIgnoreFiles, ignoreFilesInDir); + const patterns = ignoreFilesInDir.map(c => { + return c.split(/\r?\n/) + .map((l) => l.trim()) + .filter((l) => !/^#|^$/.test(l)); + }).flat(); + return ignore().add(parentIgnore).add(patterns); } private async loadIgnoreFiles( entries: WalkableEntry[], - ): Promise { + ): Promise { const ignoreEntries = entries.filter((w) => this.isIgnoreFile(w.entry)); const promises = ignoreEntries.map(async (w) => { - const content = await this.ide.readFile(w.absPath); - return new IgnoreFile(w.relPath, content); + return await this.ide.readFile(w.absPath); }); return Promise.all(promises); } @@ -156,7 +129,7 @@ class DFSWalker { private shouldInclude( walkableEntry: WalkableEntry, - ignoreFiles: IgnoreFile[], + ignore: Ignore, ) { if (this.entryIsSymlink(walkableEntry.entry)) { // If called from the root, a symlink either links to a real file in this repository, @@ -166,32 +139,13 @@ class DFSWalker { } let relPath = walkableEntry.relPath; if (this.entryIsDirectory(walkableEntry.entry)) { - if (defaultIgnoreDir.ignores(walkableEntry.relPath)) { - return false; - } relPath = `${relPath}/`; } else { if (this.options.onlyDirs) { return false; } - if (defaultIgnoreFile.ignores(walkableEntry.relPath)) { - return false; - } - relPath = `/${relPath}`; } - let included = true; - for (const ignoreFile of ignoreFiles) { - for (const r of ignoreFile.rules) { - if (r.negate === included) { - // no need to test when the file is already NOT to be included unless this is a negate rule and vice versa - continue; - } - if (r.match(relPath)) { - included = r.negate; - } - } - } - return included; + return !ignore.ignores(relPath); } private entryIsDirectory(entry: Entry) { diff --git a/core/jest.config.js b/core/jest.config.js index 06a3681fc..2567c5891 100644 --- a/core/jest.config.js +++ b/core/jest.config.js @@ -3,11 +3,11 @@ import { fileURLToPath } from "url"; export default { transform: { - "\\.[jt]sx?$": ["ts-jest", { useESM: true }], + "^.+\\.(ts|js)$": ["ts-jest", { useESM: true, useIsolatedModules: true }], }, - moduleNameMapper: { "^(\\.{1,2}/.*)\\.js$": "$1", + "^uuid$": "uuid", // https://stackoverflow.com/a/73626360 }, extensionsToTreatAsEsm: [".ts"], preset: "ts-jest/presets/default-esm", @@ -18,4 +18,5 @@ export default { __filename: path.resolve(fileURLToPath(import.meta.url)), }, globalSetup: "/jest.global-setup.ts", + setupFilesAfterEnv: ["/jest.setup-after-env.ts"], }; diff --git a/core/jest.global-setup.ts b/core/jest.global-setup.ts index 1c4fe12e8..ee9cddde4 100644 --- a/core/jest.global-setup.ts +++ b/core/jest.global-setup.ts @@ -1,4 +1,3 @@ -// jest.global-setup.js import path from "path"; export default async function () { diff --git a/core/jest.setup-after-env.ts b/core/jest.setup-after-env.ts new file mode 100644 index 000000000..d4b86824a --- /dev/null +++ b/core/jest.setup-after-env.ts @@ -0,0 +1,16 @@ +// https://github.com/mswjs/msw/issues/1576#issuecomment-1482643055 +import { TextEncoder, TextDecoder } from "util"; +import fetch, { Request, Response } from "node-fetch"; +import { jest } from "@jest/globals"; + +if (process.env.DEBUG === "jest") { + jest.setTimeout(5 * 60 * 1000); +} + +const globalThis = global as any; + +globalThis.fetch = fetch; +globalThis.Request = Request; +globalThis.Response = Response; +globalThis.TextEncoder = TextEncoder; +globalThis.TextDecoder = TextDecoder; diff --git a/core/llm/index.ts b/core/llm/index.ts index 28f72067c..2d37c40d6 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -105,6 +105,16 @@ export abstract class BaseLLM implements ILLM { accountId?: string; aiGatewaySlug?: string; + // For WatsonX only. + + watsonxUrl?: string; + watsonxApiKey?: string; + watsonxZenApiKeyBase64?:string = "YOUR_WATSONX_ZENAPIKEY" // Required if using watsonx software with ZenApiKey auth + watsonxUsername?:string; + watsonxPassword?:string; + watsonxProjectId?: string; + + private _llmOptions: LLMOptions; constructor(_options: LLMOptions) { @@ -156,6 +166,13 @@ export abstract class BaseLLM implements ILLM { this.apiKey = options.apiKey; this.aiGatewaySlug = options.aiGatewaySlug; this.apiBase = options.apiBase; + // for watsonx only + this.watsonxUrl = options.watsonxUrl; + this.watsonxApiKey = options.watsonxApiKey; + this.watsonxProjectId = options.watsonxProjectId; + this.watsonxUsername = options.watsonxUsername; + this.watsonxPassword = options.watsonxPassword; + if (this.apiBase && !this.apiBase.endsWith("/")) { this.apiBase = `${this.apiBase}/`; } diff --git a/core/llm/llms/Ollama.ts b/core/llm/llms/Ollama.ts index fe2eb6d6a..fe5ab7f55 100644 --- a/core/llm/llms/Ollama.ts +++ b/core/llm/llms/Ollama.ts @@ -106,6 +106,10 @@ class Ollama extends BaseLLM { "starcoder-3b": "starcoder:3b", "starcoder2-3b": "starcoder2:3b", "stable-code-3b": "stable-code:3b", + "granite-code-3b": "granite-code:3b", + "granite-code-8b": "granite-code:8b", + "granite-code-20b": "granite-code:20b", + "granite-code-34b": "granite-code:34b", }[this.model] ?? this.model ); } diff --git a/core/llm/llms/WatsonX.ts b/core/llm/llms/WatsonX.ts new file mode 100644 index 000000000..29ca63c39 --- /dev/null +++ b/core/llm/llms/WatsonX.ts @@ -0,0 +1,249 @@ +import { + ChatMessage, + CompletionOptions, + LLMOptions, + ModelProvider, +} from "../../index.js"; +import { stripImages } from "../images.js"; +import { BaseLLM } from "../index.js"; +const watsonxConfig = { + accessToken: { + expiration: 0, + token: "", + }, +}; +class WatsonX extends BaseLLM { + protected maxStopWords: number | undefined = undefined; + + constructor(options: LLMOptions) { + super(options); + } + async getBearerToken(): Promise<{ token: string; expiration: number }> { + if (this.watsonxUrl != null && this.watsonxUrl.includes("cloud.ibm.com")) { + // watsonx SaaS + const wxToken = await ( + await fetch( + `https://iam.cloud.ibm.com/identity/token?apikey=${this.watsonxApiKey}&grant_type=urn:ibm:params:oauth:grant-type:apikey`, + { + method: "POST", + headers: { + "Content-Type": "application/x-www-form-urlencoded", + Accept: "application/json", + }, + }, + ) + ).json(); + return { + token: wxToken["access_token"], + expiration: wxToken["expiration"], + }; + } else { + // watsonx Software + if ( + this.watsonxZenApiKeyBase64 && + this.watsonxZenApiKeyBase64 !== "YOUR_WATSONX_ZENAPIKEY" + ) { + // Using ZenApiKey auth + return { + token: this.watsonxZenApiKeyBase64, + expiration: -1, + }; + } else { + // Using username/password auth + + const wxToken = await ( + await fetch(`${this.watsonxUrl}/icp4d-api/v1/authorize`, { + method: "POST", + headers: { + "Content-Type": "application/json", + Accept: "application/json", + }, + body: JSON.stringify({ + username: this.watsonxUsername, + password: this.watsonxPassword, + }), + }) + ).json(); + const wxTokenExpiry = await ( + await fetch(`${this.watsonxUrl}/usermgmt/v1/user/tokenExpiry`, { + method: "GET", + headers: { + Accept: "application/json", + Authorization: `Bearer ${wxToken["token"]}`, + }, + }) + ).json(); + return { + token: wxToken["token"], + expiration: wxTokenExpiry["exp"], + }; + } + } + } + + static providerName: ModelProvider = "watsonx"; + + protected _convertMessage(message: ChatMessage) { + if (typeof message.content === "string") { + return message; + } + + const parts = message.content.map((part) => { + const msg: any = { + type: part.type, + text: part.text, + }; + if (part.type === "imageUrl") { + msg.image_url = { ...part.imageUrl, detail: "low" }; + msg.type = "image_url"; + } + return msg; + }); + return { + ...message, + content: parts, + }; + } + + protected _convertModelName(model: string): string { + return model; + } + + protected _convertArgs(options: any, messages: ChatMessage[]) { + const finalOptions = { + messages: messages.map(this._convertMessage), + model: this._convertModelName(options.model), + max_tokens: options.maxTokens, + temperature: options.temperature, + top_p: options.topP, + frequency_penalty: options.frequencyPenalty, + presence_penalty: options.presencePenalty, + }; + return finalOptions; + } + + protected _getHeaders() { + return { + "Content-Type": "application/json", + Authorization: `${watsonxConfig.accessToken.expiration === -1 ? "ZenApiKey" : "Bearer"} ${watsonxConfig.accessToken.token}`, + }; + } + + protected async _complete( + prompt: string, + options: CompletionOptions, + ): Promise { + let completion = ""; + for await (const chunk of this._streamChat( + [{ role: "user", content: prompt }], + options, + )) { + completion += chunk.content; + } + + return completion; + } + + protected async *_streamComplete( + prompt: string, + options: CompletionOptions, + ): AsyncGenerator { + for await (const chunk of this._streamChat( + [{ role: "user", content: prompt }], + options, + )) { + yield stripImages(chunk.content); + } + } + + protected async *_streamChat( + messages: ChatMessage[], + options: CompletionOptions, + ): AsyncGenerator { + var now = new Date().getTime() / 1000; + if ( + watsonxConfig.accessToken === undefined || + now > watsonxConfig.accessToken.expiration || + watsonxConfig.accessToken.token === undefined + ) { + watsonxConfig.accessToken = await this.getBearerToken(); + } else { + console.log( + `Reusing token (expires in ${(watsonxConfig.accessToken.expiration - now) / 60} mins)`, + ); + } + if (watsonxConfig.accessToken.token === undefined) { + throw new Error(`Something went wrong. Check your credentials, please.`); + } + var streamResponse = await fetch( + `${this.watsonxUrl}/ml/v1/text/generation_stream?version=2023-05-29`, + { + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: `${watsonxConfig.accessToken.expiration === -1 ? "ZenApiKey" : "Bearer"} ${watsonxConfig.accessToken.token}`, + }, + body: JSON.stringify({ + input: messages[messages.length - 1].content, + parameters: { + decoding_method: "greedy", + max_new_tokens: options.maxTokens ?? 1024, + min_new_tokens: 1, + stop_sequences: [], + repetition_penalty: 1, + }, + model_id: options.model, + project_id: this.watsonxProjectId, + }), + }, + ); + + if (!streamResponse.ok || streamResponse.body === null) { + throw new Error( + "Something went wrong. No response received, check your connection", + ); + } else { + const reader = streamResponse.body.getReader(); + while (true) { + const chunk = await reader.read(); + if (chunk.done) { + break; + } + + // Decode the stream + const textResponseMsg = new TextDecoder().decode(chunk.value); + const lines = textResponseMsg.split(/\r?\n/); + + let generatedChunk = ""; + let generatedTextIndex = undefined; + lines.forEach((el) => { + // console.log(`${el}`); + if (el.startsWith("id:")) { + generatedTextIndex = parseInt(el.replace(/^id:\s+/, "")); + if (isNaN(generatedTextIndex)) { + console.error(`Unable to parse stream chunk ID: ${el}`); + } + } else if (el.startsWith("data:")) { + const dataStr = el.replace(/^data:\s+/, ""); + try { + const data = JSON.parse(dataStr); + data.results.forEach((result: any) => { + generatedChunk += result.generated_text || ""; + }); + } catch (e) { + throw e; + } + } + }); + generatedChunk = generatedChunk.replaceAll("<|im_end|>", " "); + generatedChunk = generatedChunk.replaceAll("<|im_start|> ", "\n"); + yield { + role: "assistant", + content: generatedChunk, + }; + } + } + } +} + +export default WatsonX; diff --git a/core/llm/llms/index.ts b/core/llm/llms/index.ts index 20f77c850..84455399d 100644 --- a/core/llm/llms/index.ts +++ b/core/llm/llms/index.ts @@ -34,6 +34,7 @@ import Replicate from "./Replicate.js"; import TextGenWebUI from "./TextGenWebUI.js"; import Together from "./Together.js"; import ContinueProxy from "./stubs/ContinueProxy.js"; +import WatsonX from "./WatsonX.js"; function convertToLetter(num: number): string { let result = ""; @@ -126,6 +127,7 @@ const LLMs = [ Deepseek, Msty, Azure, + WatsonX ]; export async function llmFromDescription( diff --git a/core/package-lock.json b/core/package-lock.json index e3cd72120..71372470f 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -15,9 +15,6 @@ "@continuedev/llm-info": "^1.0.1", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.0.2", - "@types/jsdom": "^21.1.6", - "@types/mozilla-readability": "^0.2.1", - "@types/node-fetch": "^2.6.11", "@typescript-eslint/eslint-plugin": "^7.8.0", "@typescript-eslint/parser": "^7.8.0", "@xenova/transformers": "2.14.0", @@ -68,9 +65,13 @@ "@biomejs/biome": "1.6.4", "@google/generative-ai": "^0.11.4", "@types/follow-redirects": "^1.14.4", + "@types/isomorphic-fetch": "^0.0.39", "@types/jest": "^29.5.12", "@types/jquery": "^3.5.29", + "@types/jsdom": "^21.1.6", + "@types/mozilla-readability": "^0.2.1", "@types/mustache": "^4.2.5", + "@types/node-fetch": "^2.6.11", "@types/pg": "^8.11.6", "@types/request": "^2.48.12", "@types/uuid": "^9.0.7", @@ -79,7 +80,9 @@ "esbuild": "0.17.19", "eslint": "^8", "eslint-plugin-import": "^2.29.1", + "isomorphic-fetch": "^3.0.0", "jest": "^29.7.0", + "jest-environment-jsdom": "^29.7.0", "myers-diff": "^2.1.0", "onnxruntime-common": "1.14.0", "onnxruntime-web": "1.14.0", @@ -4360,6 +4363,12 @@ "@types/node": "*" } }, + "node_modules/@types/isomorphic-fetch": { + "version": "0.0.39", + "resolved": "https://registry.npmjs.org/@types/isomorphic-fetch/-/isomorphic-fetch-0.0.39.tgz", + "integrity": "sha512-I0gou/ZdA1vMG7t7gMzL7VYu2xAKU78rW9U1l10MI0nn77pEHq3tQqHQ8hMmXdMpBlkxZOorjI4sO594Z3kKJw==", + "dev": true + }, "node_modules/@types/istanbul-lib-coverage": { "version": "2.0.6", "resolved": "https://registry.npmjs.org/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.6.tgz", @@ -4407,6 +4416,7 @@ "version": "21.1.6", "resolved": "https://registry.npmjs.org/@types/jsdom/-/jsdom-21.1.6.tgz", "integrity": "sha512-/7kkMsC+/kMs7gAYmmBR9P0vGTnOoLhQhyhQJSlXGI5bzTHp6xdo0TtKWQAsz6pmSAeVqKSbqeyP6hytqr9FDw==", + "dev": true, "dependencies": { "@types/node": "*", "@types/tough-cookie": "*", @@ -4426,7 +4436,8 @@ "node_modules/@types/mozilla-readability": { "version": "0.2.1", "resolved": "https://registry.npmjs.org/@types/mozilla-readability/-/mozilla-readability-0.2.1.tgz", - "integrity": "sha512-RjLpe3MIpj53L+q50DTNlhv6KjHjgajFQwAF4KuxVZTa2+6Cs2UNAxS5awxABfZEHRYjGKeRDB21Zrtnsi911w==" + "integrity": "sha512-RjLpe3MIpj53L+q50DTNlhv6KjHjgajFQwAF4KuxVZTa2+6Cs2UNAxS5awxABfZEHRYjGKeRDB21Zrtnsi911w==", + "dev": true }, "node_modules/@types/mustache": { "version": "4.2.5", @@ -4572,7 +4583,8 @@ "node_modules/@types/tough-cookie": { "version": "4.0.5", "resolved": "https://registry.npmjs.org/@types/tough-cookie/-/tough-cookie-4.0.5.tgz", - "integrity": "sha512-/Ad8+nIOV7Rl++6f1BdKxFSMgmoqEoYbHRpPcx3JEfv8VRsQe9Z4mCXeJBzxs7mbHY/XOZZuXlRNfhpVPbs6ZA==" + "integrity": "sha512-/Ad8+nIOV7Rl++6f1BdKxFSMgmoqEoYbHRpPcx3JEfv8VRsQe9Z4mCXeJBzxs7mbHY/XOZZuXlRNfhpVPbs6ZA==", + "dev": true }, "node_modules/@types/uuid": { "version": "9.0.8", @@ -4805,6 +4817,13 @@ "resolved": "https://registry.npmjs.org/@yomguithereal/helpers/-/helpers-1.1.1.tgz", "integrity": "sha512-UYvAq/XCA7xoh1juWDYsq3W0WywOB+pz8cgVnE1b45ZfdMhBvHDrgmSFG3jXeZSr2tMTYLGHFHON+ekG05Jebg==" }, + "node_modules/abab": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/abab/-/abab-2.0.6.tgz", + "integrity": "sha512-j2afSsaIENvHZN2B8GOpF566vZ5WVk5opAiMTvWgaQT8DkbOqsTfvNAvHoRGU2zzP8cPoqys+xHTRDWW8L+/BA==", + "deprecated": "Use your platform's native atob() and btoa() methods instead", + "dev": true + }, "node_modules/abbrev": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz", @@ -4833,6 +4852,16 @@ "node": ">=0.4.0" } }, + "node_modules/acorn-globals": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/acorn-globals/-/acorn-globals-7.0.1.tgz", + "integrity": "sha512-umOSDSDrfHbTNPuNpC2NSnnA3LUrqpevPb4T9jRx4MagXNS0rs+gwiTcAvqCRmsD6utzsrzNt+ebm00SNWiC3Q==", + "dev": true, + "dependencies": { + "acorn": "^8.1.0", + "acorn-walk": "^8.0.2" + } + }, "node_modules/acorn-jsx": { "version": "5.3.2", "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz", @@ -4841,6 +4870,18 @@ "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" } }, + "node_modules/acorn-walk": { + "version": "8.3.3", + "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.3.3.tgz", + "integrity": "sha512-MxXdReSRhGO7VlFe1bRG/oI7/mdLV9B9JJT0N8vZOhF7gFRR5l3M8W9G8JxmKV+JC5mGqJ0QvqfSOLsCPa4nUw==", + "dev": true, + "dependencies": { + "acorn": "^8.11.0" + }, + "engines": { + "node": ">=0.4.0" + } + }, "node_modules/adf-to-md": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/adf-to-md/-/adf-to-md-1.1.0.tgz", @@ -6131,6 +6172,12 @@ "url": "https://github.com/sponsors/fb55" } }, + "node_modules/cssom": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/cssom/-/cssom-0.5.0.tgz", + "integrity": "sha512-iKuQcq+NdHqlAcwUY0o/HL69XQrUaQdMjmStJ8JFmUaiiQErlhrmuigkg/CU4E2J0IyUKUrMAgl36TvN67MqTw==", + "dev": true + }, "node_modules/cssstyle": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/cssstyle/-/cssstyle-4.0.1.tgz", @@ -6433,6 +6480,19 @@ } ] }, + "node_modules/domexception": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/domexception/-/domexception-4.0.0.tgz", + "integrity": "sha512-A2is4PLG+eeSfoTMA95/s4pvAoSo2mKtiM5jlHkAVewmiO8ISFTFKZjH7UAM1Atli/OT/7JHOrJRJiMKUZKYBw==", + "deprecated": "Use your platform's native DOMException instead", + "dev": true, + "dependencies": { + "webidl-conversions": "^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, "node_modules/domhandler": { "version": "5.0.3", "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-5.0.3.tgz", @@ -6784,6 +6844,27 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/escodegen": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/escodegen/-/escodegen-2.1.0.tgz", + "integrity": "sha512-2NlIDTwUWJN0mRPQOdtQBzbUHvdGY2P1VXSyU83Q3xKxM7WHX2Ql8dKq782Q9TgQUNOLEzEYu9bzLNj1q88I5w==", + "dev": true, + "dependencies": { + "esprima": "^4.0.1", + "estraverse": "^5.2.0", + "esutils": "^2.0.2" + }, + "bin": { + "escodegen": "bin/escodegen.js", + "esgenerate": "bin/esgenerate.js" + }, + "engines": { + "node": ">=6.0" + }, + "optionalDependencies": { + "source-map": "~0.6.1" + } + }, "node_modules/eslint": { "version": "8.57.0", "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.57.0.tgz", @@ -8044,9 +8125,9 @@ } }, "node_modules/https-proxy-agent": { - "version": "7.0.4", - "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.4.tgz", - "integrity": "sha512-wlwpilI7YdjSkWaQ/7omYBMTliDcmCN8OLihO6I9B86g06lMyAoqgoDpV0XqoaPOKj+0DIdAvnsWfyAAhmimcg==", + "version": "7.0.5", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.5.tgz", + "integrity": "sha512-1e4Wqeblerz+tMKPIq2EMGiiWW1dIjZOksyHWSUm1rmuvw/how9hBHZ38lAGj5ID4Ik6EdkOw7NmWPy6LAwalw==", "dependencies": { "agent-base": "^7.0.2", "debug": "4" @@ -8517,6 +8598,58 @@ "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==" }, + "node_modules/isomorphic-fetch": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/isomorphic-fetch/-/isomorphic-fetch-3.0.0.tgz", + "integrity": "sha512-qvUtwJ3j6qwsF3jLxkZ72qCgjMysPzDfeV240JHiGZsANBYd+EEuu35v7dfrJ9Up0Ak07D7GGSkGhCHTqg/5wA==", + "dev": true, + "dependencies": { + "node-fetch": "^2.6.1", + "whatwg-fetch": "^3.4.1" + } + }, + "node_modules/isomorphic-fetch/node_modules/node-fetch": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", + "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==", + "dev": true, + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "engines": { + "node": "4.x || >=6.0.0" + }, + "peerDependencies": { + "encoding": "^0.1.0" + }, + "peerDependenciesMeta": { + "encoding": { + "optional": true + } + } + }, + "node_modules/isomorphic-fetch/node_modules/tr46": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", + "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==", + "dev": true + }, + "node_modules/isomorphic-fetch/node_modules/webidl-conversions": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", + "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==", + "dev": true + }, + "node_modules/isomorphic-fetch/node_modules/whatwg-url": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", + "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", + "dev": true, + "dependencies": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + } + }, "node_modules/isstream": { "version": "0.1.2", "resolved": "https://registry.npmjs.org/isstream/-/isstream-0.1.2.tgz", @@ -8780,6 +8913,248 @@ "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, + "node_modules/jest-environment-jsdom": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-environment-jsdom/-/jest-environment-jsdom-29.7.0.tgz", + "integrity": "sha512-k9iQbsf9OyOfdzWH8HDmrRT0gSIcX+FLNW7IQq94tFX0gynPwqDTW0Ho6iMVNjGz/nb+l/vW3dWM2bbLLpkbXA==", + "dev": true, + "dependencies": { + "@jest/environment": "^29.7.0", + "@jest/fake-timers": "^29.7.0", + "@jest/types": "^29.6.3", + "@types/jsdom": "^20.0.0", + "@types/node": "*", + "jest-mock": "^29.7.0", + "jest-util": "^29.7.0", + "jsdom": "^20.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "peerDependencies": { + "canvas": "^2.5.0" + }, + "peerDependenciesMeta": { + "canvas": { + "optional": true + } + } + }, + "node_modules/jest-environment-jsdom/node_modules/@tootallnate/once": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@tootallnate/once/-/once-2.0.0.tgz", + "integrity": "sha512-XCuKFP5PS55gnMVu3dty8KPatLqUoy/ZYzDzAGCQ8JNFCkLXzmI7vNHCR+XpbZaMWQK/vQubr7PkYq8g470J/A==", + "dev": true, + "engines": { + "node": ">= 10" + } + }, + "node_modules/jest-environment-jsdom/node_modules/@types/jsdom": { + "version": "20.0.1", + "resolved": "https://registry.npmjs.org/@types/jsdom/-/jsdom-20.0.1.tgz", + "integrity": "sha512-d0r18sZPmMQr1eG35u12FZfhIXNrnsPU/g5wvRKCUf/tOGilKKwYMYGqh33BNR6ba+2gkHw1EUiHoN3mn7E5IQ==", + "dev": true, + "dependencies": { + "@types/node": "*", + "@types/tough-cookie": "*", + "parse5": "^7.0.0" + } + }, + "node_modules/jest-environment-jsdom/node_modules/agent-base": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", + "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", + "dev": true, + "dependencies": { + "debug": "4" + }, + "engines": { + "node": ">= 6.0.0" + } + }, + "node_modules/jest-environment-jsdom/node_modules/cssstyle": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/cssstyle/-/cssstyle-2.3.0.tgz", + "integrity": "sha512-AZL67abkUzIuvcHqk7c09cezpGNcxUxU4Ioi/05xHk4DQeTkWmGYftIE6ctU6AEt+Gn4n1lDStOtj7FKycP71A==", + "dev": true, + "dependencies": { + "cssom": "~0.3.6" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/jest-environment-jsdom/node_modules/cssstyle/node_modules/cssom": { + "version": "0.3.8", + "resolved": "https://registry.npmjs.org/cssom/-/cssom-0.3.8.tgz", + "integrity": "sha512-b0tGHbfegbhPJpxpiBPU2sCkigAqtM9O121le6bbOlgyV+NyGyCmVfJ6QW9eRjz8CpNfWEOYBIMIGRYkLwsIYg==", + "dev": true + }, + "node_modules/jest-environment-jsdom/node_modules/data-urls": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-3.0.2.tgz", + "integrity": "sha512-Jy/tj3ldjZJo63sVAvg6LHt2mHvl4V6AgRAmNDtLdm7faqtsx+aJG42rsyCo9JCoRVKwPFzKlIPx3DIibwSIaQ==", + "dev": true, + "dependencies": { + "abab": "^2.0.6", + "whatwg-mimetype": "^3.0.0", + "whatwg-url": "^11.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/jest-environment-jsdom/node_modules/html-encoding-sniffer": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-3.0.0.tgz", + "integrity": "sha512-oWv4T4yJ52iKrufjnyZPkrN0CH3QnrUqdB6In1g5Fe1mia8GmF36gnfNySxoZtxD5+NmYw1EElVXiBk93UeskA==", + "dev": true, + "dependencies": { + "whatwg-encoding": "^2.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/jest-environment-jsdom/node_modules/http-proxy-agent": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-5.0.0.tgz", + "integrity": "sha512-n2hY8YdoRE1i7r6M0w9DIw5GgZN0G25P8zLCRQ8rjXtTU3vsNFBI/vWK/UIeE6g5MUUz6avwAPXmL6Fy9D/90w==", + "dev": true, + "dependencies": { + "@tootallnate/once": "2", + "agent-base": "6", + "debug": "4" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/jest-environment-jsdom/node_modules/https-proxy-agent": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz", + "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==", + "dev": true, + "dependencies": { + "agent-base": "6", + "debug": "4" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/jest-environment-jsdom/node_modules/jsdom": { + "version": "20.0.3", + "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-20.0.3.tgz", + "integrity": "sha512-SYhBvTh89tTfCD/CRdSOm13mOBa42iTaTyfyEWBdKcGdPxPtLFBXuHR8XHb33YNYaP+lLbmSvBTsnoesCNJEsQ==", + "dev": true, + "dependencies": { + "abab": "^2.0.6", + "acorn": "^8.8.1", + "acorn-globals": "^7.0.0", + "cssom": "^0.5.0", + "cssstyle": "^2.3.0", + "data-urls": "^3.0.2", + "decimal.js": "^10.4.2", + "domexception": "^4.0.0", + "escodegen": "^2.0.0", + "form-data": "^4.0.0", + "html-encoding-sniffer": "^3.0.0", + "http-proxy-agent": "^5.0.0", + "https-proxy-agent": "^5.0.1", + "is-potential-custom-element-name": "^1.0.1", + "nwsapi": "^2.2.2", + "parse5": "^7.1.1", + "saxes": "^6.0.0", + "symbol-tree": "^3.2.4", + "tough-cookie": "^4.1.2", + "w3c-xmlserializer": "^4.0.0", + "webidl-conversions": "^7.0.0", + "whatwg-encoding": "^2.0.0", + "whatwg-mimetype": "^3.0.0", + "whatwg-url": "^11.0.0", + "ws": "^8.11.0", + "xml-name-validator": "^4.0.0" + }, + "engines": { + "node": ">=14" + }, + "peerDependencies": { + "canvas": "^2.5.0" + }, + "peerDependenciesMeta": { + "canvas": { + "optional": true + } + } + }, + "node_modules/jest-environment-jsdom/node_modules/tr46": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-3.0.0.tgz", + "integrity": "sha512-l7FvfAHlcmulp8kr+flpQZmVwtu7nfRV7NZujtN0OqES8EL4O4e0qqzL0DC5gAvx/ZC/9lk6rhcUwYvkBnBnYA==", + "dev": true, + "dependencies": { + "punycode": "^2.1.1" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/jest-environment-jsdom/node_modules/w3c-xmlserializer": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-4.0.0.tgz", + "integrity": "sha512-d+BFHzbiCx6zGfz0HyQ6Rg69w9k19nviJspaj4yNscGjrHu94sVP+aRm75yEbCh+r2/yR+7q6hux9LVtbuTGBw==", + "dev": true, + "dependencies": { + "xml-name-validator": "^4.0.0" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/jest-environment-jsdom/node_modules/whatwg-encoding": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/whatwg-encoding/-/whatwg-encoding-2.0.0.tgz", + "integrity": "sha512-p41ogyeMUrw3jWclHWTQg1k05DSVXPLcVxRTYsXUk+ZooOCZLcoYgPZ/HL/D/N+uQPOtcp1me1WhBEaX02mhWg==", + "dev": true, + "dependencies": { + "iconv-lite": "0.6.3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/jest-environment-jsdom/node_modules/whatwg-mimetype": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-3.0.0.tgz", + "integrity": "sha512-nt+N2dzIutVRxARx1nghPKGv1xHikU7HKdfafKkLNLindmPU/ch3U31NOCGGA/dmPcmb1VlofO0vnKAcsm0o/Q==", + "dev": true, + "engines": { + "node": ">=12" + } + }, + "node_modules/jest-environment-jsdom/node_modules/whatwg-url": { + "version": "11.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-11.0.0.tgz", + "integrity": "sha512-RKT8HExMpoYx4igMiVMY83lN6UeITKJlBQ+vR/8ZJ8OCdSiN3RwCq+9gH0+Xzj0+5IrM6i4j/6LuvzbZIQgEcQ==", + "dev": true, + "dependencies": { + "tr46": "^3.0.0", + "webidl-conversions": "^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/jest-environment-jsdom/node_modules/xml-name-validator": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-4.0.0.tgz", + "integrity": "sha512-ICP2e+jsHvAj2E2lIHxa5tjXRlKDJo4IdvPvCXbXQGdzSfmSpNVyIKMvoZHjDY9DP0zV17iI85o90vRFXNccRw==", + "dev": true, + "engines": { + "node": ">=12" + } + }, "node_modules/jest-environment-node": { "version": "29.7.0", "resolved": "https://registry.npmjs.org/jest-environment-node/-/jest-environment-node-29.7.0.tgz", @@ -9175,30 +9550,30 @@ "optional": true }, "node_modules/jsdom": { - "version": "24.0.0", - "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-24.0.0.tgz", - "integrity": "sha512-UDS2NayCvmXSXVP6mpTj+73JnNQadZlr9N68189xib2tx5Mls7swlTNao26IoHv46BZJFvXygyRtyXd1feAk1A==", + "version": "24.1.1", + "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-24.1.1.tgz", + "integrity": "sha512-5O1wWV99Jhq4DV7rCLIoZ/UIhyQeDR7wHVyZAHAshbrvZsLs+Xzz7gtwnlJTJDjleiTKh54F4dXrX70vJQTyJQ==", "dependencies": { "cssstyle": "^4.0.1", "data-urls": "^5.0.0", "decimal.js": "^10.4.3", "form-data": "^4.0.0", "html-encoding-sniffer": "^4.0.0", - "http-proxy-agent": "^7.0.0", - "https-proxy-agent": "^7.0.2", + "http-proxy-agent": "^7.0.2", + "https-proxy-agent": "^7.0.5", "is-potential-custom-element-name": "^1.0.1", - "nwsapi": "^2.2.7", + "nwsapi": "^2.2.12", "parse5": "^7.1.2", - "rrweb-cssom": "^0.6.0", + "rrweb-cssom": "^0.7.1", "saxes": "^6.0.0", "symbol-tree": "^3.2.4", - "tough-cookie": "^4.1.3", + "tough-cookie": "^4.1.4", "w3c-xmlserializer": "^5.0.0", "webidl-conversions": "^7.0.0", "whatwg-encoding": "^3.1.1", "whatwg-mimetype": "^4.0.0", "whatwg-url": "^14.0.0", - "ws": "^8.16.0", + "ws": "^8.18.0", "xml-name-validator": "^5.0.0" }, "engines": { @@ -9213,6 +9588,11 @@ } } }, + "node_modules/jsdom/node_modules/rrweb-cssom": { + "version": "0.7.1", + "resolved": "https://registry.npmjs.org/rrweb-cssom/-/rrweb-cssom-0.7.1.tgz", + "integrity": "sha512-TrEMa7JGdVm0UThDJSx7ddw5nVm3UJS9o9CCIZ72B1vSyEZoziDqBYP3XIoi/12lKrJR8rE3jeFHMok2F/Mnsg==" + }, "node_modules/jsesc": { "version": "2.5.2", "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-2.5.2.tgz", @@ -10099,9 +10479,9 @@ } }, "node_modules/nwsapi": { - "version": "2.2.10", - "resolved": "https://registry.npmjs.org/nwsapi/-/nwsapi-2.2.10.tgz", - "integrity": "sha512-QK0sRs7MKv0tKe1+5uZIQk/C8XGza4DAnztJG8iD+TpJIORARrCxczA738awHrZoHeTjSSoHqao2teO0dC/gFQ==" + "version": "2.2.12", + "resolved": "https://registry.npmjs.org/nwsapi/-/nwsapi-2.2.12.tgz", + "integrity": "sha512-qXDmcVlZV4XRtKFzddidpfVP4oMSGhga+xdMc25mv8kaLUHtgzCDhUxkrN8exkGdTlLNaXj7CV3GtON7zuGZ+w==" }, "node_modules/oauth-sign": { "version": "0.9.0", @@ -12946,9 +13326,9 @@ } }, "node_modules/ws": { - "version": "8.17.0", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.17.0.tgz", - "integrity": "sha512-uJq6108EgZMAl20KagGkzCKfMEjxmKvZHG7Tlq0Z6nOky7YF7aq4mOx6xK8TJ/i1LeK4Qus7INktacctDgY8Ow==", + "version": "8.18.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.18.0.tgz", + "integrity": "sha512-8VbfWfHLbbwu3+N6OKsOMpBdT4kXPDDB9cJk2bJ6mh9ucxdlnNvH1e+roYkKmN9Nxw2yjz7VzeO9oOz2zJ04Pw==", "engines": { "node": ">=10.0.0" }, diff --git a/core/package.json b/core/package.json index b3f2e0c72..bc9236403 100644 --- a/core/package.json +++ b/core/package.json @@ -1,7 +1,7 @@ { "name": "@continuedev/core", "version": "1.0.13", - "description": "The Continue Core contains functionality that can be shared across web, VS Code, or Node.js server. It is written in TypeScript and contains much of the functionality that was previously inside of the legacy Continue Python Server.", + "description": "The Continue Core contains functionality that can be shared across web, VS Code, or Node.js", "scripts": { "test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest", "build:npm": "tsc -p ./tsconfig.npm.json", @@ -9,7 +9,7 @@ "lint:fix": "eslint . --ext ts --fix" }, "type": "module", - "author": "Nate Sesti and Ty Dunn", + "author": "Continue Dev, Inc", "license": "Apache-2.0", "devDependencies": { "@babel/preset-env": "^7.24.7", @@ -18,7 +18,10 @@ "@types/follow-redirects": "^1.14.4", "@types/jest": "^29.5.12", "@types/jquery": "^3.5.29", + "@types/jsdom": "^21.1.6", + "@types/mozilla-readability": "^0.2.1", "@types/mustache": "^4.2.5", + "@types/node-fetch": "^2.6.11", "@types/pg": "^8.11.6", "@types/request": "^2.48.12", "@types/uuid": "^9.0.7", @@ -28,6 +31,7 @@ "eslint": "^8", "eslint-plugin-import": "^2.29.1", "jest": "^29.7.0", + "jest-environment-jsdom": "^29.7.0", "myers-diff": "^2.1.0", "onnxruntime-common": "1.14.0", "onnxruntime-web": "1.14.0", @@ -40,9 +44,6 @@ "@continuedev/llm-info": "^1.0.1", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.0.2", - "@types/jsdom": "^21.1.6", - "@types/mozilla-readability": "^0.2.1", - "@types/node-fetch": "^2.6.11", "@typescript-eslint/eslint-plugin": "^7.8.0", "@typescript-eslint/parser": "^7.8.0", "@xenova/transformers": "2.14.0", diff --git a/core/protocol/core.ts b/core/protocol/core.ts index b50bd4936..6d96ec685 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -68,7 +68,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { "context/loadSubmenuItems": [{ title: string }, ContextSubmenuItem[]]; "autocomplete/complete": [AutocompleteInput, string[]]; "context/addDocs": [SiteIndexingConfig, void]; - "context/removeDocs": [{ baseUrl: string }, void]; + "context/removeDocs": [Pick, void]; "context/indexDocs": [{ reIndex: boolean }, void]; "autocomplete/cancel": [undefined, void]; "autocomplete/accept": [{ completionId: string }, void]; diff --git a/core/test/indexing/DocsService.test.ts b/core/test/indexing/DocsService.test.ts new file mode 100644 index 000000000..6770ced9b --- /dev/null +++ b/core/test/indexing/DocsService.test.ts @@ -0,0 +1,183 @@ +/** + * @jest-environment jsdom + */ +import FileSystemIde from "../../util/filesystem.js"; +import { ContinueConfig, SiteIndexingConfig } from "../../index.js"; +import DocsService from "../../indexing/docs/DocsService.js"; +import { editConfigJson, getConfigJsonPath } from "../../util/paths.js"; +import { ConfigHandler } from "../../config/ConfigHandler.js"; +import { ControlPlaneClient } from "../../control-plane/client.js"; +import * as path from "path"; +import * as fs from "fs"; +import FreeTrialEmbeddingsProvider from "../../indexing/embeddings/FreeTrialEmbeddingsProvider.js"; +import preIndexedDocs from "../../indexing/docs/preIndexedDocs.js"; + +describe("DocsService Integration Tests", () => { + let ide: FileSystemIde; + let configHandler: ConfigHandler; + let docsService: DocsService; + + const mockSiteConfig: SiteIndexingConfig = { + startUrl: "https://amplified.dev/", + title: "Test repo", + faviconUrl: "https://github.com/favicon.ico", + }; + + async function clearConfigDir() { + const configFolder = path.dirname(getConfigJsonPath()); + if (fs.existsSync(configFolder)) { + fs.rmSync(configFolder, { recursive: true, force: true }); + } + } + + /** + * We need to reload config explicitly to handle the scenario where the + * config file update listeners are not called before we attempt to + * use the new config + */ + async function getReloadedConfig() { + await configHandler.reloadConfig(); + const latestConfig = await configHandler.loadConfig(); + + return latestConfig; + } + + beforeEach(async () => { + await clearConfigDir(); + + ide = new FileSystemIde(process.cwd()); + + configHandler = new ConfigHandler( + ide, + Promise.resolve({ + remoteConfigSyncPeriod: 60, + userToken: "", + enableControlServerBeta: false, + pauseCodebaseIndexOnStart: false, + ideSettings: {} as any, + enableDebugLogs: false, + remoteConfigServerUrl: "", + }), + async () => {}, + new ControlPlaneClient( + Promise.resolve({ + accessToken: "", + account: { + id: "", + label: "", + }, + }), + ), + ); + + docsService = DocsService.createSingleton(configHandler, ide); + + await docsService.isInitialized; + }); + + afterAll(async () => { + await clearConfigDir(); + }); + + test("Indexing, retrieval, and deletion of a new documentation site", async () => { + const generator = docsService.indexAndAdd(mockSiteConfig); + while (!(await generator.next()).done) {} + + let latestConfig = await getReloadedConfig(); + + // Sqlite check + expect(await docsService.has(mockSiteConfig.startUrl)).toBe(true); + + // config.json check + expect(latestConfig.docs).toContainEqual(mockSiteConfig); + + // Lance DB check + const embeddingsProvider = await docsService.getEmbeddingsProvider(); + const [mockVector] = await embeddingsProvider.embed(["test"]); + let retrievedChunks = await docsService.retrieveChunks( + mockSiteConfig.startUrl, + mockVector, + 5, + ); + + expect(retrievedChunks.length).toBeGreaterThan(0); + + await docsService.delete(mockSiteConfig.startUrl); + + // Sqlite check + expect(await docsService.has(mockSiteConfig.startUrl)).toBe(false); + + // config.json check + latestConfig = await getReloadedConfig(); + expect(latestConfig.docs).not.toContainEqual( + expect.objectContaining(mockSiteConfig), + ); + + // LanceDB check + retrievedChunks = await docsService.retrieveChunks( + mockSiteConfig.startUrl, + mockVector, + 5, + ); + expect(retrievedChunks.length).toBe(0); + }); + + test("Reindexes when changing embeddings provider", async () => { + const originalEmbeddingsProvider = + await docsService.getEmbeddingsProvider(); + + // Change embeddings provider + editConfigJson((config) => ({ + ...config, + embeddingsProvider: { + provider: FreeTrialEmbeddingsProvider.providerName, + }, + })); + + await getReloadedConfig(); + + const newEmbeddingsProvider = await docsService.getEmbeddingsProvider(); + + // Verify reindexing + const [originalVector] = await originalEmbeddingsProvider.embed(["test"]); + const [newMockVector] = await newEmbeddingsProvider.embed(["test"]); + + expect(originalVector).not.toEqual(newMockVector); + }); + + test("Handles pulling down and adding pre-indexed docs", async () => { + const preIndexedDoc = Object.values(preIndexedDocs)[0]; + const generator = docsService.indexAndAdd(preIndexedDoc); + while (!(await generator.next()).done) {} + }); + + test("Config synchronization with SQLite", async () => { + const generator = docsService.indexAndAdd(mockSiteConfig); + while (!(await generator.next()).done) {} + + await getReloadedConfig(); + + expect(await docsService.has(mockSiteConfig.startUrl)).toBe(true); + + editConfigJson((config) => { + const { docs, ...restConfig } = config; + return restConfig; + }); + + await getReloadedConfig(); + + const startTime = Date.now(); + const maxWaitTimeMs = 10_000; + + while (docsService.isSyncing) { + if (Date.now() - startTime > maxWaitTimeMs) { + throw new Error( + `Timeout: docsService.isSyncing did not complete within within ${maxWaitTimeMs}ms`, + ); + } + await new Promise((resolve) => setTimeout(resolve, 100)); + } + + expect(await docsService.has(mockSiteConfig.startUrl)).toBe(false); + }); +}); diff --git a/core/test/indexing/crawl.test.ts b/core/test/indexing/crawl.test.ts new file mode 100644 index 000000000..2f4b18817 --- /dev/null +++ b/core/test/indexing/crawl.test.ts @@ -0,0 +1,51 @@ +import { crawlPage, PageData } from "../../indexing/docs/crawl"; + +describe("crawlPage - GitHub repository", () => { + const repoUrl = new URL( + "https://github.com/Patrick-Erichsen/test-github-repo-for-crawling", + ); + const maxDepth = 3; + let crawlResults: PageData[]; + + beforeAll(async () => { + crawlResults = []; + for await (const page of crawlPage(repoUrl, maxDepth)) { + crawlResults.push(page); + } + }, 30000); + + test("finds expected markdown files", async () => { + expect(crawlResults.some((page) => page.path.endsWith("README.md"))).toBe( + true, + ); + + expect( + crawlResults.some((page) => page.path.endsWith("docs-depth-1.md")), + ).toBe(true); + }); + + test("html includes the correct content", async () => { + const doc = crawlResults.find((page) => + page.path.endsWith("docs-depth-1.md"), + ); + + expect(doc?.html.includes("Test body")).toBe(true); + expect(doc?.html.includes("Test H2 Header")).toBe(true); + }); + + // This test is currently failing, `maxDepth` does not appear to be followed right now + test.todo( + "ignores files past the max depth", + // , () => { + // expect( + // crawlResults.some((page) => page.path.includes("docs-depth-3")), + // ).toBe(false); + // } + ); + + test("ignores non-markdown files, e.g. `test.js` at the root", async () => { + expect(crawlResults.some((page) => page.path.endsWith("test.js"))).toBe( + false, + ); + }); +}); diff --git a/core/tsconfig.json b/core/tsconfig.json index fdb4b3b86..69966e2de 100644 --- a/core/tsconfig.json +++ b/core/tsconfig.json @@ -9,8 +9,8 @@ "allowSyntheticDefaultImports": true, "strict": true, "forceConsistentCasingInFileNames": true, - "module": "NodeNext", - "moduleResolution": "NodeNext", + "module": "ESNext", + "moduleResolution": "Bundler", "resolveJsonModule": true, "isolatedModules": true, "noEmit": true, diff --git a/core/util/paths.ts b/core/util/paths.ts index cec9b0a95..7c208f92c 100644 --- a/core/util/paths.ts +++ b/core/util/paths.ts @@ -205,8 +205,10 @@ export async function migrate( if (!fs.existsSync(migrationPath)) { try { - await Promise.resolve(callback()); + console.log(`Running migration: ${id}`); + fs.writeFileSync(migrationPath, ""); + await Promise.resolve(callback()); } catch (e) { console.warn(`Migration ${id} failed`, e); } diff --git a/docs/docs/customization/slash-commands.md b/docs/docs/customization/slash-commands.md index da46f106c..661f7e5e6 100644 --- a/docs/docs/customization/slash-commands.md +++ b/docs/docs/customization/slash-commands.md @@ -44,11 +44,11 @@ Type "/share" to generate a shareable markdown transcript of your current chat h { "name": "share", "description": "Export the current chat session to markdown", - "params": { "ouputDir": "~/.continue/session-transcripts" } + "params": { "outputDir": "~/.continue/session-transcripts" } } ``` -Use the `ouputDir` parameter to specify where you want to the markdown file to be saved. +Use the `outputDir` parameter to specify where you want to the markdown file to be saved. ### `/cmd` diff --git a/docs/docs/reference/Model Providers/assets/Watsonx1.gif b/docs/docs/reference/Model Providers/assets/Watsonx1.gif new file mode 100644 index 000000000..4d12fd7b4 Binary files /dev/null and b/docs/docs/reference/Model Providers/assets/Watsonx1.gif differ diff --git a/docs/docs/reference/Model Providers/watsonx.md b/docs/docs/reference/Model Providers/watsonx.md new file mode 100644 index 000000000..1d672fee3 --- /dev/null +++ b/docs/docs/reference/Model Providers/watsonx.md @@ -0,0 +1,15 @@ +# WatsonX + +Watsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks. + +## Setup + +To access the Watsonx models, create an instance in the [IBM cloud](https://cloud.ibm.com) which supports watsonx studio. Then to create a project refer [this](https://www.ibm.com/docs/en/watsonx/saas?topic=projects-creating-project). + +You can set it up in two different ways : +1. **Using API** : Create Your IBM cloud API key by referring [this](https://www.ibm.com/docs/en/mas-cd/continuous-delivery?topic=cli-creating-your-cloud-api-key). +2. **Using Credentials** : Use your Username and Password to authenticate + + +## Usage +![usage-gif](../Model%20Providers/assets/Watsonx1.gif) \ No newline at end of file diff --git a/docs/docs/setup/model-providers.md b/docs/docs/setup/model-providers.md index c43f1bf28..cf265c7b6 100644 --- a/docs/docs/setup/model-providers.md +++ b/docs/docs/setup/model-providers.md @@ -45,6 +45,7 @@ You can run a model on your local computer using: - [TensorRT-LLM](https://github.com/NVIDIA/trt-llm-as-openai-windows?tab=readme-ov-file#examples) (OpenAI compatible server) - [IPEX-LLM](../reference/Model%20Providers/ipex_llm.md) (Local LLM on Intel GPU) - [Msty](../reference/Model%20Providers/msty.md) +- [WatsonX](../reference/Model%20Providers/watsonx.md) ### Remote diff --git a/docs/package.json b/docs/package.json index a3ae7a2d3..d37e79266 100644 --- a/docs/package.json +++ b/docs/package.json @@ -1,6 +1,7 @@ { "name": "continue-docs", "version": "0.0.0", + "author": "Continue Dev, Inc", "private": true, "scripts": { "docusaurus": "docusaurus", diff --git a/docs/static/schemas/config.json b/docs/static/schemas/config.json index 3d8f848bb..e9d6e375e 100644 --- a/docs/static/schemas/config.json +++ b/docs/static/schemas/config.json @@ -187,7 +187,8 @@ "cloudflare", "deepseek", "azure", - "msty" + "msty", + "watsonx" ], "markdownEnumDescriptions": [ "### OpenAI\nUse gpt-4, gpt-3.5-turbo, or any other OpenAI model. See [here](https://openai.com/product#made-for-developers) to obtain an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/openai)", @@ -211,7 +212,8 @@ "### Cloudflare Workers AI\n\n[Reference](https://developers.cloudflare.com/workers-ai/)", "### Deepseek\n Deepseek's API provides the best pricing for their state-of-the-art Deepseek Coder models. To get started, obtain an API key from [their console](https://platform.deepseek.com/api_keys)", "### Azure OpenAI\n Azure OpenAI lets you securely run OpenAI's models on Azure. To get started, follow the steps [here](https://docs.continue.dev/reference/Model%20Providers/azure)", - "### Msty\nMsty is the simplest way to get started with online or local LLMs on all desktop platforms - Windows, Mac, and Linux. No fussing around, one-click and you are up and running. To get started, follow these steps:\n1. Download from [Msty.app](https://msty.app/), open the application, and click 'Setup Local AI'.\n2. Go to the Local AI Module page and download a model of your choice.\n3. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/Msty)" + "### Msty\nMsty is the simplest way to get started with online or local LLMs on all desktop platforms - Windows, Mac, and Linux. No fussing around, one-click and you are up and running. To get started, follow these steps:\n1. Download from [Msty.app](https://msty.app/), open the application, and click 'Setup Local AI'.\n2. Go to the Local AI Module page and download a model of your choice.\n3. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/Msty)", + "### WatsonX\nWatsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks." ], "type": "string" }, @@ -1185,6 +1187,48 @@ } } } + }, + { + "if": { + "properties": { + "provider": { + "enum": ["watsonx"] + } + }, + "required": ["provider"] + }, + "then": { + "properties": { + "watsonxUrl": { + "type": "string" + }, + "watsonxApiKey": { + "type": "string" + }, + "watsonxZenApiKeyBase64": { + "type": "string" + }, + "watsonxUsername": { + "type": "string" + }, + "watsonxPassword": { + "type": "string" + }, + "watsonxProjectId": { + "type": "string" + }, + "model": { + "enum": [ + "ibm/granite-13b-chat-v2", + "ibm/granite-13b-instruct-v2", + "mistralai/mistral-large", + "meta-llama/llama-3-8b-instruct", + "meta-llama/llama-3-70b-instruct" + ] + } + }, + "required": ["watsonxUrl", "watsonxProjectId"] + } } ] }, @@ -1427,46 +1471,6 @@ } }, "allOf": [ - { - "if": { - "properties": { - "name": { - "enum": ["docs"] - } - } - }, - "then": { - "properties": { - "params": { - "properties": { - "sites": { - "type": "array", - "items": { - "type": "object", - "properties": { - "title": { - "type": "string" - }, - "startUrl": { - "type": "string" - }, - "rootUrl": { - "type": "string" - }, - "maxDepth": { - "type": "integer" - } - }, - "required": ["title", "startUrl"] - } - } - }, - "required": ["sites"] - } - }, - "required": ["params"] - } - }, { "if": { "properties": { @@ -1859,6 +1863,10 @@ "maxDepth": { "type": "integer", "description": "The maximum depth to crawl the documentation site" + }, + "favicon": { + "type": "string", + "description": "The URL path to a favicon for the site - by default, it will be `/favicon.ico` path from the Start URL" } }, "required": ["title", "startUrl"] @@ -1956,18 +1964,6 @@ "description": "An optional token to identify the user.", "type": "string" }, - "dataServerUrl": { - "title": "Data Server Url", - "description": "The URL of the server where development data is sent. No data is sent unless a valid user token is provided.", - "default": "https://us-west1-autodebug.cloudfunctions.net", - "type": "string" - }, - "disableSummaries": { - "title": "Disable Summaries", - "markdownDescription": "If set to `true`, Continue will not generate summaries for each Step. This can be useful if you want to save on compute.", - "default": false, - "type": "boolean" - }, "disableIndexing": { "title": "Disable Indexing", "markdownDescription": "If set to `true`, Continue will not index the codebase. This is mainly used for debugging purposes.", @@ -2299,6 +2295,56 @@ } } }, + "analytics": { + "type": "object", + "properties": { + "provider": { + "type": "string", + "enum": ["posthog", "logstash"], + "description": "The 3rd party analytics provider to use.", + "default": "posthog", + "markdownEnumDescriptions": [ + "### Posthog\nTo use Posthog, set up an account, obtain your client key, and enter it in the client key field.", + "### Logstash\nContinue's Logstash integration uses the TCP input at the specified URL" + ] + }, + "url": { + "type": "string", + "description": "The URL to which analytics will be sent" + }, + "clientKey": { + "type": "string", + "description": "The client key to use for analytics" + } + }, + "required": ["provider"], + "allOf": [ + { + "if": { + "properties": { + "provider": { + "enum": ["posthog"] + } + } + }, + "then": { + "required": ["clientKey"] + } + }, + { + "if": { + "properties": { + "provider": { + "enum": ["logstash"] + } + } + }, + "then": { + "required": ["url"] + } + } + ] + }, "experimental": { "type": "object", "title": "Experimental", diff --git a/extensions/intellij/src/main/resources/config_schema.json b/extensions/intellij/src/main/resources/config_schema.json index ba281395e..e9d6e375e 100644 --- a/extensions/intellij/src/main/resources/config_schema.json +++ b/extensions/intellij/src/main/resources/config_schema.json @@ -187,7 +187,8 @@ "cloudflare", "deepseek", "azure", - "msty" + "msty", + "watsonx" ], "markdownEnumDescriptions": [ "### OpenAI\nUse gpt-4, gpt-3.5-turbo, or any other OpenAI model. See [here](https://openai.com/product#made-for-developers) to obtain an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/openai)", @@ -211,7 +212,8 @@ "### Cloudflare Workers AI\n\n[Reference](https://developers.cloudflare.com/workers-ai/)", "### Deepseek\n Deepseek's API provides the best pricing for their state-of-the-art Deepseek Coder models. To get started, obtain an API key from [their console](https://platform.deepseek.com/api_keys)", "### Azure OpenAI\n Azure OpenAI lets you securely run OpenAI's models on Azure. To get started, follow the steps [here](https://docs.continue.dev/reference/Model%20Providers/azure)", - "### Msty\nMsty is the simplest way to get started with online or local LLMs on all desktop platforms - Windows, Mac, and Linux. No fussing around, one-click and you are up and running. To get started, follow these steps:\n1. Download from [Msty.app](https://msty.app/), open the application, and click 'Setup Local AI'.\n2. Go to the Local AI Module page and download a model of your choice.\n3. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/Msty)" + "### Msty\nMsty is the simplest way to get started with online or local LLMs on all desktop platforms - Windows, Mac, and Linux. No fussing around, one-click and you are up and running. To get started, follow these steps:\n1. Download from [Msty.app](https://msty.app/), open the application, and click 'Setup Local AI'.\n2. Go to the Local AI Module page and download a model of your choice.\n3. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/Msty)", + "### WatsonX\nWatsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks." ], "type": "string" }, @@ -1185,6 +1187,48 @@ } } } + }, + { + "if": { + "properties": { + "provider": { + "enum": ["watsonx"] + } + }, + "required": ["provider"] + }, + "then": { + "properties": { + "watsonxUrl": { + "type": "string" + }, + "watsonxApiKey": { + "type": "string" + }, + "watsonxZenApiKeyBase64": { + "type": "string" + }, + "watsonxUsername": { + "type": "string" + }, + "watsonxPassword": { + "type": "string" + }, + "watsonxProjectId": { + "type": "string" + }, + "model": { + "enum": [ + "ibm/granite-13b-chat-v2", + "ibm/granite-13b-instruct-v2", + "mistralai/mistral-large", + "meta-llama/llama-3-8b-instruct", + "meta-llama/llama-3-70b-instruct" + ] + } + }, + "required": ["watsonxUrl", "watsonxProjectId"] + } } ] }, @@ -1427,46 +1471,6 @@ } }, "allOf": [ - { - "if": { - "properties": { - "name": { - "enum": ["docs"] - } - } - }, - "then": { - "properties": { - "params": { - "properties": { - "sites": { - "type": "array", - "items": { - "type": "object", - "properties": { - "title": { - "type": "string" - }, - "startUrl": { - "type": "string" - }, - "rootUrl": { - "type": "string" - }, - "maxDepth": { - "type": "integer" - } - }, - "required": ["title", "startUrl"] - } - } - }, - "required": ["sites"] - } - }, - "required": ["params"] - } - }, { "if": { "properties": { @@ -1859,6 +1863,10 @@ "maxDepth": { "type": "integer", "description": "The maximum depth to crawl the documentation site" + }, + "favicon": { + "type": "string", + "description": "The URL path to a favicon for the site - by default, it will be `/favicon.ico` path from the Start URL" } }, "required": ["title", "startUrl"] @@ -1956,18 +1964,6 @@ "description": "An optional token to identify the user.", "type": "string" }, - "dataServerUrl": { - "title": "Data Server Url", - "description": "The URL of the server where development data is sent. No data is sent unless a valid user token is provided.", - "default": "https://us-west1-autodebug.cloudfunctions.net", - "type": "string" - }, - "disableSummaries": { - "title": "Disable Summaries", - "markdownDescription": "If set to `true`, Continue will not generate summaries for each Step. This can be useful if you want to save on compute.", - "default": false, - "type": "boolean" - }, "disableIndexing": { "title": "Disable Indexing", "markdownDescription": "If set to `true`, Continue will not index the codebase. This is mainly used for debugging purposes.", @@ -1982,7 +1978,7 @@ }, "embeddingsProvider": { "title": "Embeddings Provider", - "markdownDescription": "The method that will be used to generate codebase embeddings. The default is transformers.js, which will run locally in the browser. Learn about the other options [here](https://docs.continue.dev/walkthroughs/codebase-embeddings#embeddings-providers).", + "markdownDescription": "The method that will be used to generate codebase embeddings. The default is transformers.js, which will run locally in the browser. Learn about the other options [here](https://docs.continue.dev/features/codebase-embeddings#embeddings-providers).", "type": "object", "properties": { "provider": { @@ -2220,7 +2216,7 @@ "tabAutocompleteOptions": { "title": "TabAutocompleteOptions", "type": "object", - "markdownDescription": "These options let you customize your tab-autocomplete experience. Read about all options in [the docs](https://docs.continue.dev/walkthroughs/tab-autocomplete#configuration-options).", + "markdownDescription": "These options let you customize your tab-autocomplete experience. Read about all options in [the docs](https://docs.continue.dev/features/tab-autocomplete#configuration-options).", "properties": { "disable": { "type": "boolean", @@ -2299,6 +2295,56 @@ } } }, + "analytics": { + "type": "object", + "properties": { + "provider": { + "type": "string", + "enum": ["posthog", "logstash"], + "description": "The 3rd party analytics provider to use.", + "default": "posthog", + "markdownEnumDescriptions": [ + "### Posthog\nTo use Posthog, set up an account, obtain your client key, and enter it in the client key field.", + "### Logstash\nContinue's Logstash integration uses the TCP input at the specified URL" + ] + }, + "url": { + "type": "string", + "description": "The URL to which analytics will be sent" + }, + "clientKey": { + "type": "string", + "description": "The client key to use for analytics" + } + }, + "required": ["provider"], + "allOf": [ + { + "if": { + "properties": { + "provider": { + "enum": ["posthog"] + } + } + }, + "then": { + "required": ["clientKey"] + } + }, + { + "if": { + "properties": { + "provider": { + "enum": ["logstash"] + } + } + }, + "then": { + "required": ["url"] + } + } + ] + }, "experimental": { "type": "object", "title": "Experimental", diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index 3d8f848bb..e9d6e375e 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -187,7 +187,8 @@ "cloudflare", "deepseek", "azure", - "msty" + "msty", + "watsonx" ], "markdownEnumDescriptions": [ "### OpenAI\nUse gpt-4, gpt-3.5-turbo, or any other OpenAI model. See [here](https://openai.com/product#made-for-developers) to obtain an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/openai)", @@ -211,7 +212,8 @@ "### Cloudflare Workers AI\n\n[Reference](https://developers.cloudflare.com/workers-ai/)", "### Deepseek\n Deepseek's API provides the best pricing for their state-of-the-art Deepseek Coder models. To get started, obtain an API key from [their console](https://platform.deepseek.com/api_keys)", "### Azure OpenAI\n Azure OpenAI lets you securely run OpenAI's models on Azure. To get started, follow the steps [here](https://docs.continue.dev/reference/Model%20Providers/azure)", - "### Msty\nMsty is the simplest way to get started with online or local LLMs on all desktop platforms - Windows, Mac, and Linux. No fussing around, one-click and you are up and running. To get started, follow these steps:\n1. Download from [Msty.app](https://msty.app/), open the application, and click 'Setup Local AI'.\n2. Go to the Local AI Module page and download a model of your choice.\n3. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/Msty)" + "### Msty\nMsty is the simplest way to get started with online or local LLMs on all desktop platforms - Windows, Mac, and Linux. No fussing around, one-click and you are up and running. To get started, follow these steps:\n1. Download from [Msty.app](https://msty.app/), open the application, and click 'Setup Local AI'.\n2. Go to the Local AI Module page and download a model of your choice.\n3. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/Msty)", + "### WatsonX\nWatsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks." ], "type": "string" }, @@ -1185,6 +1187,48 @@ } } } + }, + { + "if": { + "properties": { + "provider": { + "enum": ["watsonx"] + } + }, + "required": ["provider"] + }, + "then": { + "properties": { + "watsonxUrl": { + "type": "string" + }, + "watsonxApiKey": { + "type": "string" + }, + "watsonxZenApiKeyBase64": { + "type": "string" + }, + "watsonxUsername": { + "type": "string" + }, + "watsonxPassword": { + "type": "string" + }, + "watsonxProjectId": { + "type": "string" + }, + "model": { + "enum": [ + "ibm/granite-13b-chat-v2", + "ibm/granite-13b-instruct-v2", + "mistralai/mistral-large", + "meta-llama/llama-3-8b-instruct", + "meta-llama/llama-3-70b-instruct" + ] + } + }, + "required": ["watsonxUrl", "watsonxProjectId"] + } } ] }, @@ -1427,46 +1471,6 @@ } }, "allOf": [ - { - "if": { - "properties": { - "name": { - "enum": ["docs"] - } - } - }, - "then": { - "properties": { - "params": { - "properties": { - "sites": { - "type": "array", - "items": { - "type": "object", - "properties": { - "title": { - "type": "string" - }, - "startUrl": { - "type": "string" - }, - "rootUrl": { - "type": "string" - }, - "maxDepth": { - "type": "integer" - } - }, - "required": ["title", "startUrl"] - } - } - }, - "required": ["sites"] - } - }, - "required": ["params"] - } - }, { "if": { "properties": { @@ -1859,6 +1863,10 @@ "maxDepth": { "type": "integer", "description": "The maximum depth to crawl the documentation site" + }, + "favicon": { + "type": "string", + "description": "The URL path to a favicon for the site - by default, it will be `/favicon.ico` path from the Start URL" } }, "required": ["title", "startUrl"] @@ -1956,18 +1964,6 @@ "description": "An optional token to identify the user.", "type": "string" }, - "dataServerUrl": { - "title": "Data Server Url", - "description": "The URL of the server where development data is sent. No data is sent unless a valid user token is provided.", - "default": "https://us-west1-autodebug.cloudfunctions.net", - "type": "string" - }, - "disableSummaries": { - "title": "Disable Summaries", - "markdownDescription": "If set to `true`, Continue will not generate summaries for each Step. This can be useful if you want to save on compute.", - "default": false, - "type": "boolean" - }, "disableIndexing": { "title": "Disable Indexing", "markdownDescription": "If set to `true`, Continue will not index the codebase. This is mainly used for debugging purposes.", @@ -2299,6 +2295,56 @@ } } }, + "analytics": { + "type": "object", + "properties": { + "provider": { + "type": "string", + "enum": ["posthog", "logstash"], + "description": "The 3rd party analytics provider to use.", + "default": "posthog", + "markdownEnumDescriptions": [ + "### Posthog\nTo use Posthog, set up an account, obtain your client key, and enter it in the client key field.", + "### Logstash\nContinue's Logstash integration uses the TCP input at the specified URL" + ] + }, + "url": { + "type": "string", + "description": "The URL to which analytics will be sent" + }, + "clientKey": { + "type": "string", + "description": "The client key to use for analytics" + } + }, + "required": ["provider"], + "allOf": [ + { + "if": { + "properties": { + "provider": { + "enum": ["posthog"] + } + } + }, + "then": { + "required": ["clientKey"] + } + }, + { + "if": { + "properties": { + "provider": { + "enum": ["logstash"] + } + } + }, + "then": { + "required": ["url"] + } + } + ] + }, "experimental": { "type": "object", "title": "Experimental", diff --git a/extensions/vscode/continue_rc_schema.json b/extensions/vscode/continue_rc_schema.json index df79fbfde..180908ddb 100644 --- a/extensions/vscode/continue_rc_schema.json +++ b/extensions/vscode/continue_rc_schema.json @@ -190,7 +190,8 @@ "cloudflare", "deepseek", "azure", - "msty" + "msty", + "watsonx" ], "markdownEnumDescriptions": [ "### OpenAI\nUse gpt-4, gpt-3.5-turbo, or any other OpenAI model. See [here](https://openai.com/product#made-for-developers) to obtain an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/openai)", @@ -214,7 +215,8 @@ "### Cloudflare Workers AI\n\n[Reference](https://developers.cloudflare.com/workers-ai/)", "### Deepseek\n Deepseek's API provides the best pricing for their state-of-the-art Deepseek Coder models. To get started, obtain an API key from [their console](https://platform.deepseek.com/api_keys)", "### Azure OpenAI\n Azure OpenAI lets you securely run OpenAI's models on Azure. To get started, follow the steps [here](https://docs.continue.dev/reference/Model%20Providers/azure)", - "### Msty\nMsty is the simplest way to get started with online or local LLMs on all desktop platforms - Windows, Mac, and Linux. No fussing around, one-click and you are up and running. To get started, follow these steps:\n1. Download from [Msty.app](https://msty.app/), open the application, and click 'Setup Local AI'.\n2. Go to the Local AI Module page and download a model of your choice.\n3. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/Msty)" + "### Msty\nMsty is the simplest way to get started with online or local LLMs on all desktop platforms - Windows, Mac, and Linux. No fussing around, one-click and you are up and running. To get started, follow these steps:\n1. Download from [Msty.app](https://msty.app/), open the application, and click 'Setup Local AI'.\n2. Go to the Local AI Module page and download a model of your choice.\n3. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/Msty)", + "### WatsonX\nWatsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks." ], "type": "string" }, @@ -1312,6 +1314,55 @@ } } } + }, + { + "if": { + "properties": { + "provider": { + "enum": [ + "watsonx" + ] + } + }, + "required": [ + "provider" + ] + }, + "then": { + "properties": { + "watsonxUrl": { + "type": "string" + }, + "watsonxApiKey": { + "type": "string" + }, + "watsonxZenApiKeyBase64": { + "type": "string" + }, + "watsonxUsername": { + "type": "string" + }, + "watsonxPassword": { + "type": "string" + }, + "watsonxProjectId": { + "type": "string" + }, + "model": { + "enum": [ + "ibm/granite-13b-chat-v2", + "ibm/granite-13b-instruct-v2", + "mistralai/mistral-large", + "meta-llama/llama-3-8b-instruct", + "meta-llama/llama-3-70b-instruct" + ] + } + }, + "required": [ + "watsonxUrl", + "watsonxProjectId" + ] + } } ] }, @@ -1573,55 +1624,6 @@ } }, "allOf": [ - { - "if": { - "properties": { - "name": { - "enum": [ - "docs" - ] - } - } - }, - "then": { - "properties": { - "params": { - "properties": { - "sites": { - "type": "array", - "items": { - "type": "object", - "properties": { - "title": { - "type": "string" - }, - "startUrl": { - "type": "string" - }, - "rootUrl": { - "type": "string" - }, - "maxDepth": { - "type": "integer" - } - }, - "required": [ - "title", - "startUrl" - ] - } - } - }, - "required": [ - "sites" - ] - } - }, - "required": [ - "params" - ] - } - }, { "if": { "properties": { @@ -2081,6 +2083,10 @@ "maxDepth": { "type": "integer", "description": "The maximum depth to crawl the documentation site" + }, + "favicon": { + "type": "string", + "description": "The URL path to a favicon for the site - by default, it will be `/favicon.ico` path from the Start URL" } }, "required": [ @@ -2181,18 +2187,6 @@ "description": "An optional token to identify the user.", "type": "string" }, - "dataServerUrl": { - "title": "Data Server Url", - "description": "The URL of the server where development data is sent. No data is sent unless a valid user token is provided.", - "default": "https://us-west1-autodebug.cloudfunctions.net", - "type": "string" - }, - "disableSummaries": { - "title": "Disable Summaries", - "markdownDescription": "If set to `true`, Continue will not generate summaries for each Step. This can be useful if you want to save on compute.", - "default": false, - "type": "boolean" - }, "disableIndexing": { "title": "Disable Indexing", "markdownDescription": "If set to `true`, Continue will not index the codebase. This is mainly used for debugging purposes.", @@ -2207,7 +2201,7 @@ }, "embeddingsProvider": { "title": "Embeddings Provider", - "markdownDescription": "The method that will be used to generate codebase embeddings. The default is transformers.js, which will run locally in the browser. Learn about the other options [here](https://docs.continue.dev/walkthroughs/codebase-embeddings#embeddings-providers).", + "markdownDescription": "The method that will be used to generate codebase embeddings. The default is transformers.js, which will run locally in the browser. Learn about the other options [here](https://docs.continue.dev/features/codebase-embeddings#embeddings-providers).", "type": "object", "properties": { "provider": { @@ -2493,7 +2487,7 @@ "tabAutocompleteOptions": { "title": "TabAutocompleteOptions", "type": "object", - "markdownDescription": "These options let you customize your tab-autocomplete experience. Read about all options in [the docs](https://docs.continue.dev/walkthroughs/tab-autocomplete#configuration-options).", + "markdownDescription": "These options let you customize your tab-autocomplete experience. Read about all options in [the docs](https://docs.continue.dev/features/tab-autocomplete#configuration-options).", "properties": { "disable": { "type": "boolean", @@ -2579,6 +2573,69 @@ } } }, + "analytics": { + "type": "object", + "properties": { + "provider": { + "type": "string", + "enum": [ + "posthog", + "logstash" + ], + "description": "The 3rd party analytics provider to use.", + "default": "posthog", + "markdownEnumDescriptions": [ + "### Posthog\nTo use Posthog, set up an account, obtain your client key, and enter it in the client key field.", + "### Logstash\nContinue's Logstash integration uses the TCP input at the specified URL" + ] + }, + "url": { + "type": "string", + "description": "The URL to which analytics will be sent" + }, + "clientKey": { + "type": "string", + "description": "The client key to use for analytics" + } + }, + "required": [ + "provider" + ], + "allOf": [ + { + "if": { + "properties": { + "provider": { + "enum": [ + "posthog" + ] + } + } + }, + "then": { + "required": [ + "clientKey" + ] + } + }, + { + "if": { + "properties": { + "provider": { + "enum": [ + "logstash" + ] + } + } + }, + "then": { + "required": [ + "url" + ] + } + } + ] + }, "experimental": { "type": "object", "title": "Experimental", diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index ae3c57627..24512fd0e 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "0.9.192", + "version": "0.9.193", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "0.9.192", + "version": "0.9.193", "license": "Apache-2.0", "dependencies": { "@electron/rebuild": "^3.2.10", @@ -101,9 +101,6 @@ "@continuedev/llm-info": "^1.0.1", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.0.2", - "@types/jsdom": "^21.1.6", - "@types/mozilla-readability": "^0.2.1", - "@types/node-fetch": "^2.6.11", "@typescript-eslint/eslint-plugin": "^7.8.0", "@typescript-eslint/parser": "^7.8.0", "@xenova/transformers": "2.14.0", @@ -156,15 +153,20 @@ "@types/follow-redirects": "^1.14.4", "@types/jest": "^29.5.12", "@types/jquery": "^3.5.29", + "@types/jsdom": "^21.1.6", + "@types/mozilla-readability": "^0.2.1", "@types/mustache": "^4.2.5", + "@types/node-fetch": "^2.6.11", "@types/pg": "^8.11.6", "@types/request": "^2.48.12", "@types/uuid": "^9.0.7", "@types/win-ca": "^3.5.4", + "cross-env": "^7.0.3", "esbuild": "0.17.19", "eslint": "^8", "eslint-plugin-import": "^2.29.1", "jest": "^29.7.0", + "jest-environment-jsdom": "^29.7.0", "myers-diff": "^2.1.0", "onnxruntime-common": "1.14.0", "onnxruntime-web": "1.14.0", diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 776c037c8..9c47f34b0 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -1,7 +1,8 @@ { "name": "continue", "icon": "media/icon.png", - "version": "0.9.192", + "author": "Continue Dev, Inc", + "version": "0.9.193", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" diff --git a/extensions/vscode/src/quickEdit/ContextProvidersQuickPick.ts b/extensions/vscode/src/quickEdit/ContextProvidersQuickPick.ts index cf986c897..bcb1fdc45 100644 --- a/extensions/vscode/src/quickEdit/ContextProvidersQuickPick.ts +++ b/extensions/vscode/src/quickEdit/ContextProvidersQuickPick.ts @@ -39,6 +39,7 @@ export async function getContextProvidersString( } return provider.getContextItems("", { + config, ide, embeddingsProvider: config.embeddingsProvider, reranker: config.reranker, diff --git a/gui/package-lock.json b/gui/package-lock.json index 866d55389..d2cf7916d 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -94,9 +94,6 @@ "@continuedev/llm-info": "^1.0.1", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.0.2", - "@types/jsdom": "^21.1.6", - "@types/mozilla-readability": "^0.2.1", - "@types/node-fetch": "^2.6.11", "@typescript-eslint/eslint-plugin": "^7.8.0", "@typescript-eslint/parser": "^7.8.0", "@xenova/transformers": "2.14.0", @@ -149,15 +146,20 @@ "@types/follow-redirects": "^1.14.4", "@types/jest": "^29.5.12", "@types/jquery": "^3.5.29", + "@types/jsdom": "^21.1.6", + "@types/mozilla-readability": "^0.2.1", "@types/mustache": "^4.2.5", + "@types/node-fetch": "^2.6.11", "@types/pg": "^8.11.6", "@types/request": "^2.48.12", "@types/uuid": "^9.0.7", "@types/win-ca": "^3.5.4", + "cross-env": "^7.0.3", "esbuild": "0.17.19", "eslint": "^8", "eslint-plugin-import": "^2.29.1", "jest": "^29.7.0", + "jest-environment-jsdom": "^29.7.0", "myers-diff": "^2.1.0", "onnxruntime-common": "1.14.0", "onnxruntime-web": "1.14.0", @@ -5153,6 +5155,7 @@ }, "../core/node_modules/@types/jsdom": { "version": "21.1.6", + "dev": true, "license": "MIT", "dependencies": { "@types/node": "*", @@ -5170,6 +5173,7 @@ }, "../core/node_modules/@types/mozilla-readability": { "version": "0.2.1", + "dev": true, "license": "MIT" }, "../core/node_modules/@types/mustache": { @@ -5206,6 +5210,7 @@ }, "../core/node_modules/@types/tough-cookie": { "version": "4.0.5", + "dev": true, "license": "MIT" }, "../core/node_modules/@types/uuid": { diff --git a/gui/package.json b/gui/package.json index d96793531..0d4ab0fd5 100644 --- a/gui/package.json +++ b/gui/package.json @@ -2,6 +2,7 @@ "name": "gui", "private": true, "type": "module", + "author": "Continue Dev, Inc", "license": "Apache-2.0", "scripts": { "dev": "vite", diff --git a/gui/public/logos/WatsonX.png b/gui/public/logos/WatsonX.png new file mode 100644 index 000000000..66cf02a03 Binary files /dev/null and b/gui/public/logos/WatsonX.png differ diff --git a/gui/public/logos/ibm.png b/gui/public/logos/ibm.png new file mode 100644 index 000000000..be88ec2ed Binary files /dev/null and b/gui/public/logos/ibm.png differ diff --git a/gui/src/components/dialogs/AddDocsDialog.tsx b/gui/src/components/dialogs/AddDocsDialog.tsx index 2ea11c91f..51632d838 100644 --- a/gui/src/components/dialogs/AddDocsDialog.tsx +++ b/gui/src/components/dialogs/AddDocsDialog.tsx @@ -1,11 +1,11 @@ import { SiteIndexingConfig } from "core"; import { usePostHog } from "posthog-js/react"; -import React, { useContext, useLayoutEffect, useRef, useState } from "react"; +import { useContext, useLayoutEffect, useRef, useState } from "react"; import { useDispatch } from "react-redux"; -import { Button, Input } from ".."; +import { Button, HelperText, Input, lightGray } from ".."; import { IdeMessengerContext } from "../../context/IdeMessenger"; -import { SubmenuContextProvidersContext } from "../../context/SubmenuContextProviders"; import { setShowDialog } from "../../redux/slices/uiStateSlice"; +import { ChevronDownIcon, ChevronUpIcon } from "@heroicons/react/24/outline"; const DEFAULT_MAX_DEPTH = 3; @@ -15,15 +15,16 @@ function AddDocsDialog() { const ref = useRef(null); - const [docsUrl, setDocsUrl] = useState(""); - const [docsTitle, setDocsTitle] = useState(""); - const [urlValid, setUrlValid] = useState(false); + const [title, setTitle] = useState(""); + const [startUrl, setStartUrl] = useState(""); + const [rootUrl, setRootUrl] = useState(""); + const [faviconUrl, setFaviconUrl] = useState(""); const [maxDepth, setMaxDepth] = useState(""); + const [isOpen, setIsOpen] = useState(false); const ideMessenger = useContext(IdeMessengerContext); - const { addItem } = useContext(SubmenuContextProvidersContext); - const isFormValid = docsUrl && docsTitle && urlValid; + const isFormValid = startUrl && title; useLayoutEffect(() => { setTimeout(() => { @@ -37,34 +38,30 @@ function AddDocsDialog() { e.preventDefault(); const siteIndexingConfig: SiteIndexingConfig = { - startUrl: docsUrl, - rootUrl: docsUrl, - title: docsTitle, + startUrl, + rootUrl, + title, maxDepth: typeof maxDepth === "string" ? DEFAULT_MAX_DEPTH : maxDepth, - faviconUrl: new URL("/favicon.ico", docsUrl).toString(), + faviconUrl: new URL("/favicon.ico", startUrl).toString(), }; ideMessenger.post("context/addDocs", siteIndexingConfig); - setDocsTitle(""); - setDocsUrl(""); + setTitle(""); + setStartUrl(""); + setRootUrl(""); setMaxDepth(""); + setFaviconUrl(""); dispatch(setShowDialog(false)); - addItem("docs", { - id: docsUrl, - title: docsTitle, - description: new URL(docsUrl).hostname, - }); - - posthog.capture("add_docs", { url: docsUrl }); + posthog.capture("add_docs_gui", { url: startUrl }); } return (
-

Add Docs

+

Add a documentation site

Continue pre-indexes many common documentation sites, but if there's @@ -78,49 +75,114 @@ function AddDocsDialog() {

- - +
setIsOpen((prev) => !prev)} + > + {isOpen ? ( + + ) : ( + + )} + Advanced +
+ + {isOpen && ( +
+ + + + + +
+ )} +