From 04d73a8ac60c96bf2e84913fff049539732dda8e Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 7 Dec 2024 18:05:15 -0800 Subject: [PATCH] WIP load config.yaml --- core/config/loadYaml.ts | 846 --------------------- core/config/yaml/convertFromJson.ts | 30 + core/config/yaml/default.ts | 14 + core/config/yaml/loadYaml.ts | 317 ++++++++ core/config/yaml/models.ts | 104 +++ core/llm/llms/index.ts | 8 +- core/package-lock.json | 1 + core/util/paths.ts | 25 +- packages/config-yaml/src/index.ts | 5 +- packages/config-yaml/src/schemas/models.ts | 27 + packages/config-yaml/src/validation.ts | 71 ++ 11 files changed, 593 insertions(+), 855 deletions(-) delete mode 100644 core/config/loadYaml.ts create mode 100644 core/config/yaml/convertFromJson.ts create mode 100644 core/config/yaml/default.ts create mode 100644 core/config/yaml/loadYaml.ts create mode 100644 core/config/yaml/models.ts create mode 100644 packages/config-yaml/src/validation.ts diff --git a/core/config/loadYaml.ts b/core/config/loadYaml.ts deleted file mode 100644 index 1e16913e5..000000000 --- a/core/config/loadYaml.ts +++ /dev/null @@ -1,846 +0,0 @@ -import { execSync } from "child_process"; -import * as fs from "fs"; -import os from "os"; -import path from "path"; - -import * as JSONC from "comment-json"; -import * as tar from "tar"; - -import { - BrowserSerializedContinueConfig, - Config, - ContextProviderWithParams, - ContinueConfig, - ContinueRcJson, - CustomContextProvider, - CustomLLM, - EmbeddingsProviderDescription, - IContextProvider, - IDE, - IdeSettings, - IdeType, - ModelDescription, - Reranker, - RerankerDescription, - SerializedContinueConfig, - SlashCommand, -} from ".."; -import { - slashCommandFromDescription, - slashFromCustomCommand, -} from "../commands/index.js"; -import MCPConnectionSingleton from "../context/mcp"; -import CodebaseContextProvider from "../context/providers/CodebaseContextProvider"; -import ContinueProxyContextProvider from "../context/providers/ContinueProxyContextProvider"; -import CustomContextProviderClass from "../context/providers/CustomContextProvider"; -import FileContextProvider from "../context/providers/FileContextProvider"; -import { contextProviderClassFromName } from "../context/providers/index"; -import PromptFilesContextProvider from "../context/providers/PromptFilesContextProvider"; -import { AllRerankers } from "../context/rerankers/index"; -import { LLMReranker } from "../context/rerankers/llm"; -import { allEmbeddingsProviders } from "../indexing/embeddings"; -import TransformersJsEmbeddingsProvider from "../indexing/embeddings/TransformersJsEmbeddingsProvider"; -import { BaseLLM } from "../llm"; -import { llmFromDescription } from "../llm/llms"; -import CustomLLMClass from "../llm/llms/CustomLLM"; -import FreeTrial from "../llm/llms/FreeTrial"; -import { allTools } from "../tools"; -import { copyOf } from "../util"; -import { fetchwithRequestOptions } from "../util/fetchWithOptions"; -import { GlobalContext } from "../util/GlobalContext"; -import mergeJson from "../util/merge"; -import { - DEFAULT_CONFIG_TS_CONTENTS, - getConfigJsPath, - getConfigJsPathForRemote, - getConfigJsonPath, - getConfigJsonPathForRemote, - getConfigTsPath, - getContinueDotEnv, - getEsbuildBinaryPath, - readAllGlobalPromptFiles, -} from "../util/paths"; -import { - defaultContextProvidersJetBrains, - defaultContextProvidersVsCode, - defaultSlashCommandsJetBrains, - defaultSlashCommandsVscode, -} from "./default"; -import { getSystemPromptDotFile } from "./getSystemPromptDotFile"; -import { - DEFAULT_PROMPTS_FOLDER, - getPromptFiles, - slashCommandFromPromptFile, -} from "./promptFile.js"; -import { ConfigValidationError, validateConfig } from "./validation.js"; - -export interface ConfigResult { - config: T | undefined; - errors: ConfigValidationError[] | undefined; - configLoadInterrupted: boolean; -} - -function resolveSerializedConfig(filepath: string): SerializedContinueConfig { - let content = fs.readFileSync(filepath, "utf8"); - const config = JSONC.parse(content) as unknown as SerializedContinueConfig; - if (config.env && Array.isArray(config.env)) { - const env = { - ...process.env, - ...getContinueDotEnv(), - }; - - config.env.forEach((envVar) => { - if (envVar in env) { - content = (content as any).replaceAll( - new RegExp(`"${envVar}"`, "g"), - `"${env[envVar]}"`, - ); - } - }); - } - - return JSONC.parse(content) as unknown as SerializedContinueConfig; -} - -const configMergeKeys = { - models: (a: any, b: any) => a.title === b.title, - contextProviders: (a: any, b: any) => a.name === b.name, - slashCommands: (a: any, b: any) => a.name === b.name, - customCommands: (a: any, b: any) => a.name === b.name, -}; - -function loadSerializedConfig( - workspaceConfigs: ContinueRcJson[], - ideSettings: IdeSettings, - ideType: IdeType, - overrideConfigJson: SerializedContinueConfig | undefined, -): ConfigResult { - const configPath = getConfigJsonPath(ideType); - let config: SerializedContinueConfig = overrideConfigJson!; - if (!config) { - try { - config = resolveSerializedConfig(configPath); - } catch (e) { - throw new Error(`Failed to parse config.json: ${e}`); - } - } - - const errors = validateConfig(config); - - if (errors?.some((error) => error.fatal)) { - return { - errors, - config: undefined, - configLoadInterrupted: true, - }; - } - - if (config.allowAnonymousTelemetry === undefined) { - config.allowAnonymousTelemetry = true; - } - - if (config.ui?.getChatTitles === undefined) { - config.ui = { - ...config.ui, - getChatTitles: true, - }; - } - - if (ideSettings.remoteConfigServerUrl) { - try { - const remoteConfigJson = resolveSerializedConfig( - getConfigJsonPathForRemote(ideSettings.remoteConfigServerUrl), - ); - config = mergeJson(config, remoteConfigJson, "merge", configMergeKeys); - } catch (e) { - console.warn("Error loading remote config: ", e); - } - } - - for (const workspaceConfig of workspaceConfigs) { - config = mergeJson( - config, - workspaceConfig, - workspaceConfig.mergeBehavior, - configMergeKeys, - ); - } - - // Set defaults if undefined (this lets us keep config.json uncluttered for new users) - config.contextProviders ??= - ideType === "vscode" - ? [...defaultContextProvidersVsCode] - : [...defaultContextProvidersJetBrains]; - config.slashCommands ??= - ideType === "vscode" - ? [...defaultSlashCommandsVscode] - : [...defaultSlashCommandsJetBrains]; - - return { config, errors, configLoadInterrupted: false }; -} - -async function serializedToIntermediateConfig( - initial: SerializedContinueConfig, - ide: IDE, - loadPromptFiles: boolean = true, -): Promise { - const slashCommands: SlashCommand[] = []; - for (const command of initial.slashCommands || []) { - const newCommand = slashCommandFromDescription(command); - if (newCommand) { - slashCommands.push(newCommand); - } - } - for (const command of initial.customCommands || []) { - slashCommands.push(slashFromCustomCommand(command)); - } - - const workspaceDirs = await ide.getWorkspaceDirs(); - const promptFolder = initial.experimental?.promptPath; - - if (loadPromptFiles) { - // v1 prompt files - let promptFiles: { path: string; content: string }[] = []; - promptFiles = ( - await Promise.all( - workspaceDirs.map((dir) => - getPromptFiles( - ide, - path.join(dir, promptFolder ?? DEFAULT_PROMPTS_FOLDER), - ), - ), - ) - ) - .flat() - .filter(({ path }) => path.endsWith(".prompt")); - - // Also read from ~/.continue/.prompts - promptFiles.push(...readAllGlobalPromptFiles()); - - for (const file of promptFiles) { - const slashCommand = slashCommandFromPromptFile(file.path, file.content); - if (slashCommand) { - slashCommands.push(slashCommand); - } - } - } - - const config: Config = { - ...initial, - slashCommands, - contextProviders: initial.contextProviders || [], - }; - - return config; -} - -function isModelDescription( - llm: ModelDescription | CustomLLM, -): llm is ModelDescription { - return (llm as ModelDescription).title !== undefined; -} - -function isContextProviderWithParams( - contextProvider: CustomContextProvider | ContextProviderWithParams, -): contextProvider is ContextProviderWithParams { - return (contextProvider as ContextProviderWithParams).name !== undefined; -} - -/** Only difference between intermediate and final configs is the `models` array */ -async function intermediateToFinalConfig( - config: Config, - ide: IDE, - ideSettings: IdeSettings, - uniqueId: string, - writeLog: (log: string) => Promise, - workOsAccessToken: string | undefined, - loadPromptFiles: boolean = true, - allowFreeTrial: boolean = true, -): Promise { - // Auto-detect models - let models: BaseLLM[] = []; - for (const desc of config.models) { - if (isModelDescription(desc)) { - const llm = await llmFromDescription( - desc, - ide.readFile.bind(ide), - uniqueId, - ideSettings, - writeLog, - config.completionOptions, - config.systemMessage, - ); - if (!llm) { - continue; - } - - if (llm.model === "AUTODETECT") { - try { - const modelNames = await llm.listModels(); - const detectedModels = await Promise.all( - modelNames.map(async (modelName) => { - return await llmFromDescription( - { - ...desc, - model: modelName, - title: `${llm.title} - ${modelName}`, - }, - ide.readFile.bind(ide), - uniqueId, - ideSettings, - writeLog, - copyOf(config.completionOptions), - config.systemMessage, - ); - }), - ); - models.push( - ...(detectedModels.filter( - (x) => typeof x !== "undefined", - ) as BaseLLM[]), - ); - } catch (e) { - console.warn("Error listing models: ", e); - } - } else { - models.push(llm); - } - } else { - const llm = new CustomLLMClass({ - ...desc, - options: { ...desc.options, writeLog } as any, - }); - if (llm.model === "AUTODETECT") { - try { - const modelNames = await llm.listModels(); - const models = modelNames.map( - (modelName) => - new CustomLLMClass({ - ...desc, - options: { ...desc.options, model: modelName, writeLog }, - }), - ); - - models.push(...models); - } catch (e) { - console.warn("Error listing models: ", e); - } - } else { - models.push(llm); - } - } - } - - // Prepare models - for (const model of models) { - model.requestOptions = { - ...model.requestOptions, - ...config.requestOptions, - }; - } - - if (allowFreeTrial) { - // Obtain auth token (iff free trial being used) - const freeTrialModels = models.filter( - (model) => model.providerName === "free-trial", - ); - if (freeTrialModels.length > 0) { - const ghAuthToken = await ide.getGitHubAuthToken({}); - for (const model of freeTrialModels) { - (model as FreeTrial).setupGhAuthToken(ghAuthToken); - } - } - } else { - // Remove free trial models - models = models.filter((model) => model.providerName !== "free-trial"); - } - - // Tab autocomplete model - let tabAutocompleteModels: BaseLLM[] = []; - if (config.tabAutocompleteModel) { - tabAutocompleteModels = ( - await Promise.all( - (Array.isArray(config.tabAutocompleteModel) - ? config.tabAutocompleteModel - : [config.tabAutocompleteModel] - ).map(async (desc) => { - if (isModelDescription(desc)) { - const llm = await llmFromDescription( - desc, - ide.readFile.bind(ide), - uniqueId, - ideSettings, - writeLog, - config.completionOptions, - config.systemMessage, - ); - - if (llm?.providerName === "free-trial") { - if (!allowFreeTrial) { - // This shouldn't happen - throw new Error("Free trial cannot be used with control plane"); - } - const ghAuthToken = await ide.getGitHubAuthToken({}); - (llm as FreeTrial).setupGhAuthToken(ghAuthToken); - } - return llm; - } else { - return new CustomLLMClass(desc); - } - }), - ) - ).filter((x) => x !== undefined) as BaseLLM[]; - } - - // These context providers are always included, regardless of what, if anything, - // the user has configured in config.json - - const codebaseContextParams = - ( - (config.contextProviders || []) - .filter(isContextProviderWithParams) - .find((cp) => cp.name === "codebase") as - | ContextProviderWithParams - | undefined - )?.params || {}; - const DEFAULT_CONTEXT_PROVIDERS = [ - new FileContextProvider({}), - new CodebaseContextProvider(codebaseContextParams), - ...(loadPromptFiles ? [new PromptFilesContextProvider({})] : []), - ]; - - const DEFAULT_CONTEXT_PROVIDERS_TITLES = DEFAULT_CONTEXT_PROVIDERS.map( - ({ description: { title } }) => title, - ); - - // Context providers - const contextProviders: IContextProvider[] = DEFAULT_CONTEXT_PROVIDERS; - - for (const provider of config.contextProviders || []) { - if (isContextProviderWithParams(provider)) { - const cls = contextProviderClassFromName(provider.name) as any; - if (!cls) { - if (!DEFAULT_CONTEXT_PROVIDERS_TITLES.includes(provider.name)) { - console.warn(`Unknown context provider ${provider.name}`); - } - - continue; - } - const instance: IContextProvider = new cls(provider.params); - - // Handle continue-proxy - if (instance.description.title === "continue-proxy") { - (instance as ContinueProxyContextProvider).workOsAccessToken = - workOsAccessToken; - } - - contextProviders.push(instance); - } else { - contextProviders.push(new CustomContextProviderClass(provider)); - } - } - - // Embeddings Provider - const embeddingsProviderDescription = config.embeddingsProvider as - | EmbeddingsProviderDescription - | undefined; - if (embeddingsProviderDescription?.provider) { - const { provider, ...options } = embeddingsProviderDescription; - const embeddingsProviderClass = allEmbeddingsProviders[provider]; - if (embeddingsProviderClass) { - if ( - embeddingsProviderClass.name === "_TransformersJsEmbeddingsProvider" - ) { - config.embeddingsProvider = new embeddingsProviderClass(); - } else { - config.embeddingsProvider = new embeddingsProviderClass( - options, - (url: string | URL, init: any) => - fetchwithRequestOptions(url, init, { - ...config.requestOptions, - ...options.requestOptions, - }), - ); - } - } - } - - if (!config.embeddingsProvider) { - config.embeddingsProvider = new TransformersJsEmbeddingsProvider(); - } - - // Reranker - if (config.reranker && !(config.reranker as Reranker | undefined)?.rerank) { - const { name, params } = config.reranker as RerankerDescription; - const rerankerClass = AllRerankers[name]; - - if (name === "llm") { - const llm = models.find((model) => model.title === params?.modelTitle); - if (!llm) { - console.warn(`Unknown model ${params?.modelTitle}`); - } else { - config.reranker = new LLMReranker(llm); - } - } else if (rerankerClass) { - config.reranker = new rerankerClass(params); - } - } - - let continueConfig: ContinueConfig = { - ...config, - contextProviders, - models, - embeddingsProvider: config.embeddingsProvider as any, - tabAutocompleteModels, - reranker: config.reranker as any, - tools: allTools, - }; - - // Apply MCP if specified - if (config.experimental?.modelContextProtocolServer) { - const mcpConnection = await MCPConnectionSingleton.getInstance( - config.experimental.modelContextProtocolServer, - ); - continueConfig = await Promise.race([ - mcpConnection.modifyConfig(continueConfig), - new Promise((_, reject) => - setTimeout( - () => reject(new Error("MCP connection timed out after 2000ms")), - 2000, - ), - ), - ]).catch((error) => { - console.warn("MCP connection error:", error); - return continueConfig; // Return original config if timeout occurs - }); - } - - return continueConfig; -} - -function finalToBrowserConfig( - final: ContinueConfig, -): BrowserSerializedContinueConfig { - return { - allowAnonymousTelemetry: final.allowAnonymousTelemetry, - models: final.models.map((m) => ({ - provider: m.providerName, - model: m.model, - title: m.title ?? m.model, - apiKey: m.apiKey, - apiBase: m.apiBase, - contextLength: m.contextLength, - template: m.template, - completionOptions: m.completionOptions, - systemMessage: m.systemMessage, - requestOptions: m.requestOptions, - promptTemplates: m.promptTemplates as any, - capabilities: m.capabilities, - })), - systemMessage: final.systemMessage, - completionOptions: final.completionOptions, - slashCommands: final.slashCommands?.map((s) => ({ - name: s.name, - description: s.description, - params: s.params, //PZTODO: is this why params aren't referenced properly by slash commands? - })), - contextProviders: final.contextProviders?.map((c) => c.description), - disableIndexing: final.disableIndexing, - disableSessionTitles: final.disableSessionTitles, - userToken: final.userToken, - embeddingsProvider: final.embeddingsProvider?.id, - ui: final.ui, - experimental: final.experimental, - docs: final.docs, - tools: final.tools, - }; -} - -function escapeSpacesInPath(p: string): string { - return p.replace(/ /g, "\\ "); -} - -async function handleEsbuildInstallation(ide: IDE, ideType: IdeType) { - // JetBrains is currently the only IDE that we've reached the plugin size limit and - // therefore need to install esbuild manually to reduce the size - if (ideType !== "jetbrains") { - return; - } - - const globalContext = new GlobalContext(); - if (globalContext.get("hasDismissedConfigTsNoticeJetBrains")) { - return; - } - - const esbuildPath = getEsbuildBinaryPath(); - - if (fs.existsSync(esbuildPath)) { - return; - } - - console.debug("No esbuild binary detected"); - - const shouldInstall = await promptEsbuildInstallation(ide); - - if (shouldInstall) { - await downloadAndInstallEsbuild(ide); - } -} - -async function promptEsbuildInstallation(ide: IDE): Promise { - const installMsg = "Install esbuild"; - const dismissMsg = "Dismiss"; - - const res = await ide.showToast( - "warning", - "You're using a custom 'config.ts' file, which requires 'esbuild' to be installed. Would you like to install it now?", - dismissMsg, - installMsg, - ); - - if (res === dismissMsg) { - const globalContext = new GlobalContext(); - globalContext.update("hasDismissedConfigTsNoticeJetBrains", true); - return false; - } - - return res === installMsg; -} - -/** - * The download logic is adapted from here: https://esbuild.github.io/getting-started/#download-a-build - */ -async function downloadAndInstallEsbuild(ide: IDE) { - const esbuildPath = getEsbuildBinaryPath(); - const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "esbuild-")); - - try { - const target = `${os.platform()}-${os.arch()}`; - const version = "0.19.11"; - const url = `https://registry.npmjs.org/@esbuild/${target}/-/${target}-${version}.tgz`; - const tgzPath = path.join(tempDir, `esbuild-${version}.tgz`); - - console.debug(`Downloading esbuild from: ${url}`); - execSync(`curl -fo "${tgzPath}" "${url}"`); - - console.debug(`Extracting tgz file to: ${tempDir}`); - await tar.x({ - file: tgzPath, - cwd: tempDir, - strip: 2, // Remove the top two levels of directories - }); - - // Ensure the destination directory exists - const destDir = path.dirname(esbuildPath); - if (!fs.existsSync(destDir)) { - fs.mkdirSync(destDir, { recursive: true }); - } - - // Move the file - const extractedBinaryPath = path.join(tempDir, "esbuild"); - fs.renameSync(extractedBinaryPath, esbuildPath); - - // Ensure the binary is executable (not needed on Windows) - if (os.platform() !== "win32") { - fs.chmodSync(esbuildPath, 0o755); - } - - // Clean up - fs.unlinkSync(tgzPath); - fs.rmSync(tempDir, { recursive: true }); - - await ide.showToast( - "info", - `'esbuild' successfully installed to ${esbuildPath}`, - ); - } catch (error) { - console.error("Error downloading or saving esbuild binary:", error); - throw error; - } -} - -async function tryBuildConfigTs() { - try { - if (process.env.IS_BINARY === "true") { - await buildConfigTsWithBinary(); - } else { - await buildConfigTsWithNodeModule(); - } - } catch (e) { - console.log( - `Build error. Please check your ~/.continue/config.ts file: ${e}`, - ); - } -} - -async function buildConfigTsWithBinary() { - const cmd = [ - escapeSpacesInPath(getEsbuildBinaryPath()), - escapeSpacesInPath(getConfigTsPath()), - "--bundle", - `--outfile=${escapeSpacesInPath(getConfigJsPath())}`, - "--platform=node", - "--format=cjs", - "--sourcemap", - "--external:fetch", - "--external:fs", - "--external:path", - "--external:os", - "--external:child_process", - ].join(" "); - - execSync(cmd); -} - -async function buildConfigTsWithNodeModule() { - const { build } = await import("esbuild"); - - await build({ - entryPoints: [getConfigTsPath()], - bundle: true, - platform: "node", - format: "cjs", - outfile: getConfigJsPath(), - external: ["fetch", "fs", "path", "os", "child_process"], - sourcemap: true, - }); -} - -function readConfigJs(): string | undefined { - const configJsPath = getConfigJsPath(); - - if (!fs.existsSync(configJsPath)) { - return undefined; - } - - return fs.readFileSync(configJsPath, "utf8"); -} - -async function buildConfigTsandReadConfigJs(ide: IDE, ideType: IdeType) { - const configTsPath = getConfigTsPath(); - - if (!fs.existsSync(configTsPath)) { - return; - } - - const currentContent = fs.readFileSync(configTsPath, "utf8"); - - // If the user hasn't modified the default config.ts, don't bother building - if (currentContent.trim() === DEFAULT_CONFIG_TS_CONTENTS.trim()) { - return; - } - - await handleEsbuildInstallation(ide, ideType); - await tryBuildConfigTs(); - - return readConfigJs(); -} - -async function loadFullConfigNode( - ide: IDE, - workspaceConfigs: ContinueRcJson[], - ideSettings: IdeSettings, - ideType: IdeType, - uniqueId: string, - writeLog: (log: string) => Promise, - workOsAccessToken: string | undefined, - overrideConfigJson: SerializedContinueConfig | undefined, -): Promise> { - // Serialized config - let { - config: serialized, - errors, - configLoadInterrupted, - } = loadSerializedConfig( - workspaceConfigs, - ideSettings, - ideType, - overrideConfigJson, - ); - - if (!serialized || configLoadInterrupted) { - return { errors, config: undefined, configLoadInterrupted: true }; - } - - const systemPromptDotFile = await getSystemPromptDotFile(ide); - if (systemPromptDotFile) { - serialized.systemMessage = systemPromptDotFile; - } - - // Convert serialized to intermediate config - let intermediate = await serializedToIntermediateConfig(serialized, ide); - - // Apply config.ts to modify intermediate config - const configJsContents = await buildConfigTsandReadConfigJs(ide, ideType); - if (configJsContents) { - try { - // Try config.ts first - const configJsPath = getConfigJsPath(); - let module: any; - - try { - module = await import(configJsPath); - } catch (e) { - console.log(e); - console.log( - "Could not load config.ts as absolute path, retrying as file url ...", - ); - try { - module = await import(`file://${configJsPath}`); - } catch (e) { - throw new Error("Could not load config.ts as file url either", { - cause: e, - }); - } - } - - if (typeof require !== "undefined") { - delete require.cache[require.resolve(configJsPath)]; - } - if (!module.modifyConfig) { - throw new Error("config.ts does not export a modifyConfig function."); - } - intermediate = module.modifyConfig(intermediate); - } catch (e) { - console.log("Error loading config.ts: ", e); - } - } - - // Apply remote config.js to modify intermediate config - if (ideSettings.remoteConfigServerUrl) { - try { - const configJsPathForRemote = getConfigJsPathForRemote( - ideSettings.remoteConfigServerUrl, - ); - const module = await import(configJsPathForRemote); - if (typeof require !== "undefined") { - delete require.cache[require.resolve(configJsPathForRemote)]; - } - if (!module.modifyConfig) { - throw new Error("config.ts does not export a modifyConfig function."); - } - intermediate = module.modifyConfig(intermediate); - } catch (e) { - console.log("Error loading remotely set config.js: ", e); - } - } - - // Convert to final config format - const finalConfig = await intermediateToFinalConfig( - intermediate, - ide, - ideSettings, - uniqueId, - writeLog, - workOsAccessToken, - ); - return { config: finalConfig, errors, configLoadInterrupted: false }; -} - -export { - finalToBrowserConfig, - intermediateToFinalConfig, - loadFullConfigNode, - serializedToIntermediateConfig, - type BrowserSerializedContinueConfig, -}; diff --git a/core/config/yaml/convertFromJson.ts b/core/config/yaml/convertFromJson.ts new file mode 100644 index 000000000..59482b5c3 --- /dev/null +++ b/core/config/yaml/convertFromJson.ts @@ -0,0 +1,30 @@ +import { ModelConfig } from "@continuedev/config-yaml"; +import { ConfigYaml } from "@continuedev/config-yaml/dist/schemas"; + +import { SerializedContinueConfig } from "../.."; + +export function convertConfigJsonToConfigYaml( + configJson: SerializedContinueConfig, +): ConfigYaml { + return { + name: "Local Config", + models: [ + ...configJson.models.map( + (model): ModelConfig => ({ + model: model.model, + name: model.title, + // defaultCompletionOptions: model.completionOptions, + provider: model.provider, + roles: ["chat"], + }), + ), + // ... tabAutocompleteModels + // embeddingsModels + // rerankModels + ], + context: configJson.contextProviders?.map((provider) => ({ + uses: provider.name, + with: provider.params, + })), + }; +} diff --git a/core/config/yaml/default.ts b/core/config/yaml/default.ts new file mode 100644 index 000000000..f991561df --- /dev/null +++ b/core/config/yaml/default.ts @@ -0,0 +1,14 @@ +import { ConfigYaml } from "@continuedev/config-yaml/dist/schemas"; + +// TODO +export const defaultConfigYaml: ConfigYaml = { + models: [], + context: [], + name: "Local Config", +}; + +export const defaultConfigYamlJetBrains: ConfigYaml = { + models: [], + context: [], + name: "Local Config", +}; diff --git a/core/config/yaml/loadYaml.ts b/core/config/yaml/loadYaml.ts new file mode 100644 index 000000000..d6e75cc81 --- /dev/null +++ b/core/config/yaml/loadYaml.ts @@ -0,0 +1,317 @@ +import fs from "node:fs"; +import path from "path"; +import * as YAML from "yaml"; + +import { + extendConfig, + fillTemplateVariables, + validateConfigYaml, +} from "@continuedev/config-yaml"; +import { ConfigYaml } from "@continuedev/config-yaml/dist/schemas"; +import { ValidationLevel } from "@continuedev/config-yaml/dist/validation"; +import { + BrowserSerializedContinueConfig, + ContinueConfig, + IContextProvider, + IDE, + IdeSettings, + IdeType, + SlashCommand, +} from "../.."; +import MCPConnectionSingleton from "../../context/mcp"; +import { contextProviderClassFromName } from "../../context/providers/index"; +import { BaseLLM } from "../../llm"; +import FreeTrial from "../../llm/llms/FreeTrial"; +import { allTools } from "../../tools"; +import { + getConfigYamlPath, + getContinueDotEnv, + readAllGlobalPromptFiles, +} from "../../util/paths"; +import { getSystemPromptDotFile } from "../getSystemPromptDotFile"; +import { + DEFAULT_PROMPTS_FOLDER, + getPromptFiles, + slashCommandFromPromptFile, +} from "../promptFile.js"; +import { ConfigValidationError } from "../validation.js"; +import { llmsFromModelConfig } from "./models"; + +export interface ConfigResult { + config: T | undefined; + errors: ConfigValidationError[] | undefined; + configLoadInterrupted: boolean; +} + +function renderTemplateVars(configYaml: string): string { + const data: Record = {}; + + // env.* + const envVars = getContinueDotEnv(); + Object.entries(envVars).forEach(([key, value]) => { + data[`env.${key}`] = value; + }); + + // secrets.* not filled in + + return fillTemplateVariables(configYaml, data); +} + +function loadConfigYaml( + workspaceConfigs: string[], + ideSettings: IdeSettings, + ideType: IdeType, + rawYaml: string, +): ConfigResult { + const renderedYaml = renderTemplateVars(rawYaml); + let config = YAML.parse(renderedYaml) as ConfigYaml; + const errors = validateConfigYaml(config); + + if (errors?.some((error) => error.level === ValidationLevel.Error)) { + return { + errors: errors.map((error) => ({ + message: error.message, + fatal: error.level === ValidationLevel.Error, + })), + config: undefined, + configLoadInterrupted: true, + }; + } + + for (const workspaceConfig of workspaceConfigs) { + const rendered = renderTemplateVars(workspaceConfig); + config = extendConfig(config, YAML.parse(rendered) as ConfigYaml); + } + + // Set defaults if undefined (this lets us keep config.json uncluttered for new users) + return { + config, + errors: errors.map((error) => ({ + message: error.message, + fatal: error.level === ValidationLevel.Error, + })), + configLoadInterrupted: false, + }; +} + +async function slashCommandsFromV1PromptFiles( + ide: IDE, +): Promise { + const slashCommands: SlashCommand[] = []; + const workspaceDirs = await ide.getWorkspaceDirs(); + + // v1 prompt files + let promptFiles: { path: string; content: string }[] = []; + promptFiles = ( + await Promise.all( + workspaceDirs.map((dir) => + getPromptFiles(ide, path.join(dir, DEFAULT_PROMPTS_FOLDER)), + ), + ) + ) + .flat() + .filter(({ path }) => path.endsWith(".prompt")); + + // Also read from ~/.continue/.prompts + promptFiles.push(...readAllGlobalPromptFiles()); + + for (const file of promptFiles) { + const slashCommand = slashCommandFromPromptFile(file.path, file.content); + if (slashCommand) { + slashCommands.push(slashCommand); + } + } + + return slashCommands; +} + +async function configYamlToContinueConfig( + config: ConfigYaml, + ide: IDE, + ideSettings: IdeSettings, + uniqueId: string, + writeLog: (log: string) => Promise, + workOsAccessToken: string | undefined, + allowFreeTrial: boolean = true, +): Promise { + const slashCommands = await slashCommandsFromV1PromptFiles(ide); + + // Models + let models: BaseLLM[] = []; + for (const model of config.models ?? []) { + const llms = await llmsFromModelConfig( + model, + ide, + uniqueId, + ideSettings, + writeLog, + ); + models.push(...llms); + } + + if (allowFreeTrial) { + // Obtain auth token (iff free trial being used) + const freeTrialModels = models.filter( + (model) => model.providerName === "free-trial", + ); + if (freeTrialModels.length > 0) { + const ghAuthToken = await ide.getGitHubAuthToken({}); + for (const model of freeTrialModels) { + (model as FreeTrial).setupGhAuthToken(ghAuthToken); + } + } + } else { + // Remove free trial models + models = models.filter((model) => model.providerName !== "free-trial"); + } + + // TODO: Split into model roles. + + // Context + const contextProviders = config.context + ?.map((context) => { + const cls = contextProviderClassFromName(context.uses) as any; + if (!cls) { + console.warn(`Unknown context provider ${context.uses}`); + return undefined; + } + const instance: IContextProvider = new cls(context.with ?? {}); + return instance; + }) + .filter((p) => !!p) as IContextProvider[]; + + // Embeddings Provider - TODO + // const embeddingsProviderDescription = config.embeddingsProvider as + // | EmbeddingsProviderDescription + // | undefined; + // if (embeddingsProviderDescription?.provider) { + // const { provider, ...options } = embeddingsProviderDescription; + // const embeddingsProviderClass = allEmbeddingsProviders[provider]; + // if (embeddingsProviderClass) { + // if ( + // embeddingsProviderClass.name === "_TransformersJsEmbeddingsProvider" + // ) { + // config.embeddingsProvider = new embeddingsProviderClass(); + // } else { + // config.embeddingsProvider = new embeddingsProviderClass( + // options, + // (url: string | URL, init: any) => + // fetchwithRequestOptions(url, init, { + // ...config.requestOptions, + // ...options.requestOptions, + // }), + // ); + // } + // } + // } + + // if (!config.embeddingsProvider) { + // config.embeddingsProvider = new TransformersJsEmbeddingsProvider(); + // } + + // Reranker + // if (config.reranker && !(config.reranker as Reranker | undefined)?.rerank) { + // const { name, params } = config.reranker as RerankerDescription; + // const rerankerClass = AllRerankers[name]; + + // if (name === "llm") { + // const llm = models.find((model) => model.title === params?.modelTitle); + // if (!llm) { + // console.warn(`Unknown model ${params?.modelTitle}`); + // } else { + // config.reranker = new LLMReranker(llm); + // } + // } else if (rerankerClass) { + // config.reranker = new rerankerClass(params); + // } + // } + + let continueConfig: ContinueConfig = { + ...config, + contextProviders, + models, + embeddingsProvider: config.embeddingsProvider as any, + tabAutocompleteModels, + reranker: config.reranker as any, + tools: allTools, + }; + + // Apply MCP if specified + if (config.experimental?.modelContextProtocolServer) { + const mcpConnection = await MCPConnectionSingleton.getInstance( + config.experimental.modelContextProtocolServer, + ); + continueConfig = await Promise.race([ + mcpConnection.modifyConfig(continueConfig), + new Promise((_, reject) => + setTimeout( + () => reject(new Error("MCP connection timed out after 2000ms")), + 2000, + ), + ), + ]).catch((error) => { + console.warn("MCP connection error:", error); + return continueConfig; // Return original config if timeout occurs + }); + } + + return continueConfig; +} + +export async function loadContinueConfig( + ide: IDE, + workspaceConfigs: string[], + ideSettings: IdeSettings, + ideType: IdeType, + uniqueId: string, + writeLog: (log: string) => Promise, + workOsAccessToken: string | undefined, + overrideConfigYaml: string | undefined, +): Promise> { + const configYamlPath = getConfigYamlPath(ideType); + const rawYaml = fs.readFileSync(configYamlPath, "utf-8"); + + const configYamlResult = await loadConfigYaml( + workspaceConfigs, + ideSettings, + ideType, + overrideConfigYaml ?? rawYaml, + ); + + if (!configYamlResult.config || configYamlResult.configLoadInterrupted) { + return { + errors: configYamlResult.errors, + config: undefined, + configLoadInterrupted: true, + }; + } + + const continueConfig = await configYamlToContinueConfig( + configYamlResult.config, + ide, + ideSettings, + uniqueId, + writeLog, + workOsAccessToken, + ); + + const systemPromptDotFile = await getSystemPromptDotFile(ide); + if (systemPromptDotFile) { + if (continueConfig.systemMessage) { + continueConfig.systemMessage += "\n\n" + systemPromptDotFile; + } else { + continueConfig.systemMessage = systemPromptDotFile; + } + } + + return { + config: continueConfig, + errors: configYamlResult.errors, + configLoadInterrupted: false, + }; +} + +export { + loadContinueConfig as loadFullConfigNode, + type BrowserSerializedContinueConfig, +}; diff --git a/core/config/yaml/models.ts b/core/config/yaml/models.ts new file mode 100644 index 000000000..7ee91f0c6 --- /dev/null +++ b/core/config/yaml/models.ts @@ -0,0 +1,104 @@ +import { ModelConfig } from "@continuedev/config-yaml"; + +import { IDE, IdeSettings, LLMOptions } from "../.."; +import { BaseLLM } from "../../llm"; +import { LLMClasses } from "../../llm/llms"; + +const AUTODETECT = "AUTODETECT"; + +async function modelConfigToBaseLLM( + model: ModelConfig, + uniqueId: string, + ideSettings: IdeSettings, + writeLog: (log: string) => Promise, +): Promise { + const cls = LLMClasses.find((llm) => llm.providerName === model.provider); + + if (!cls) { + return undefined; + } + + let options: LLMOptions = { + ...model, + completionOptions: { + ...(model.defaultCompletionOptions ?? {}), + model: model.model, + maxTokens: + model.defaultCompletionOptions?.maxTokens ?? + cls.defaultOptions?.completionOptions?.maxTokens, + }, + writeLog, + uniqueId, + }; + + const llm = new cls(options); + return llm; +} + +async function autodetectModels( + llm: BaseLLM, + model: ModelConfig, + ide: IDE, + uniqueId: string, + ideSettings: IdeSettings, + writeLog: (log: string) => Promise, +): Promise { + try { + const modelNames = await llm.listModels(); + const detectedModels = await Promise.all( + modelNames.map(async (modelName) => { + // To ensure there are no infinite loops + if (modelName === AUTODETECT) { + return undefined; + } + + return await modelConfigToBaseLLM( + { + ...model, + model: modelName, + name: `${llm.title} - ${modelName}`, + }, + uniqueId, + ideSettings, + writeLog, + ); + }), + ); + return detectedModels.filter((x) => typeof x !== "undefined"); + } catch (e) { + console.warn("Error listing models: ", e); + return []; + } +} + +export async function llmsFromModelConfig( + model: ModelConfig, + ide: IDE, + uniqueId: string, + ideSettings: IdeSettings, + writeLog: (log: string) => Promise, +): Promise { + const baseLlm = await modelConfigToBaseLLM( + model, + uniqueId, + ideSettings, + writeLog, + ); + if (!baseLlm) { + return []; + } + + if (model.model === AUTODETECT) { + const models = await autodetectModels( + baseLlm, + model, + ide, + uniqueId, + ideSettings, + writeLog, + ); + return models; + } else { + return [baseLlm]; + } +} diff --git a/core/llm/llms/index.ts b/core/llm/llms/index.ts index 632607ed1..991b760ec 100644 --- a/core/llm/llms/index.ts +++ b/core/llm/llms/index.ts @@ -42,6 +42,7 @@ import OpenRouter from "./OpenRouter"; import Replicate from "./Replicate"; import SageMaker from "./SageMaker"; import SambaNova from "./SambaNova"; +import SiliconFlow from "./SiliconFlow"; import ContinueProxy from "./stubs/ContinueProxy"; import TextGenWebUI from "./TextGenWebUI"; import Together from "./Together"; @@ -49,9 +50,8 @@ import VertexAI from "./VertexAI"; import Vllm from "./Vllm"; import WatsonX from "./WatsonX"; import xAI from "./xAI"; -import SiliconFlow from "./SiliconFlow"; -const LLMs = [ +export const LLMClasses = [ Anthropic, Cohere, FreeTrial, @@ -105,7 +105,7 @@ export async function llmFromDescription( completionOptions?: BaseCompletionOptions, systemMessage?: string, ): Promise { - const cls = LLMs.find((llm) => llm.providerName === desc.provider); + const cls = LLMClasses.find((llm) => llm.providerName === desc.provider); if (!cls) { return undefined; @@ -152,7 +152,7 @@ export function llmFromProviderAndOptions( providerName: string, llmOptions: LLMOptions, ): ILLM { - const cls = LLMs.find((llm) => llm.providerName === providerName); + const cls = LLMClasses.find((llm) => llm.providerName === providerName); if (!cls) { throw new Error(`Unknown LLM provider type "${providerName}"`); diff --git a/core/package-lock.json b/core/package-lock.json index 25dd82180..f681b24f4 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -104,6 +104,7 @@ } }, "../packages/config-yaml": { + "name": "@continuedev/config-yaml", "version": "1.0.0", "license": "Apache-2.0", "dependencies": { diff --git a/core/util/paths.ts b/core/util/paths.ts index 3ff5251e6..384a9e77b 100644 --- a/core/util/paths.ts +++ b/core/util/paths.ts @@ -1,13 +1,18 @@ -import * as fs from "fs"; -import * as os from "os"; -import { pathToFileURL } from "url"; -import * as path from "path"; import * as JSONC from "comment-json"; import dotenv from "dotenv"; +import * as fs from "fs"; +import * as os from "os"; +import * as path from "path"; +import { pathToFileURL } from "url"; +import * as YAML from "yaml"; import { IdeType, SerializedContinueConfig } from "../"; import { defaultConfig, defaultConfigJetBrains } from "../config/default"; import Types from "../config/types"; +import { + defaultConfigYaml, + defaultConfigYamlJetBrains, +} from "../config/yaml/default"; dotenv.config(); @@ -101,6 +106,18 @@ export function getConfigJsonPath(ideType: IdeType = "vscode"): string { return p; } +export function getConfigYamlPath(ideType: IdeType): string { + const p = path.join(getContinueGlobalPath(), "config.yaml"); + if (!fs.existsSync(p)) { + if (ideType === "jetbrains") { + fs.writeFileSync(p, YAML.stringify(defaultConfigYamlJetBrains)); + } else { + fs.writeFileSync(p, YAML.stringify(defaultConfigYaml)); + } + } + return p; +} + export function getConfigJsonUri(): string { return getContinueGlobalUri() + "/config.json"; } diff --git a/packages/config-yaml/src/index.ts b/packages/config-yaml/src/index.ts index 8e67bee70..c229f147b 100644 --- a/packages/config-yaml/src/index.ts +++ b/packages/config-yaml/src/index.ts @@ -18,7 +18,7 @@ function parseUses(uses: string): { }; } -function extendConfig(config: ConfigYaml, pkg: ConfigYaml): ConfigYaml { +export function extendConfig(config: ConfigYaml, pkg: ConfigYaml): ConfigYaml { return { ...config, models: [...(config.models ?? []), ...(pkg.models ?? [])], @@ -90,3 +90,6 @@ export function fillTemplateVariables( return match; }); } + +export type { ModelConfig } from "./schemas/models.js"; +export { validateConfigYaml } from "./validation.js"; diff --git a/packages/config-yaml/src/schemas/models.ts b/packages/config-yaml/src/schemas/models.ts index 29c534943..8bf39594c 100644 --- a/packages/config-yaml/src/schemas/models.ts +++ b/packages/config-yaml/src/schemas/models.ts @@ -1,6 +1,33 @@ import { z } from "zod"; +export const modelRolesSchema = z.enum([ + "chat", + "autocomplete", + "embed", + "rerank", + "edit", + "apply", + "summarize", +]); +export type ModelRoles = z.infer; + +export const completionOptionsSchema = z.object({ + contextLength: z.number().optional(), + maxTokens: z.number().optional(), + temperature: z.number().optional(), + topP: z.number().optional(), + topK: z.number().optional(), + stop: z.array(z.string()).optional(), + n: z.number().optional(), +}); +export type CompletionOptions = z.infer; + export const modelSchema = z.object({ + name: z.string(), provider: z.string(), model: z.string(), + roles: modelRolesSchema.array().optional(), + defaultCompletionOptions: completionOptionsSchema.optional(), }); + +export type ModelConfig = z.infer; diff --git a/packages/config-yaml/src/validation.ts b/packages/config-yaml/src/validation.ts new file mode 100644 index 000000000..223764e71 --- /dev/null +++ b/packages/config-yaml/src/validation.ts @@ -0,0 +1,71 @@ +import { ConfigYaml, configYamlSchema } from "./schemas/index.js"; + +export enum ValidationLevel { + Warning, + Error, +} + +export interface ConfigValidationError { + level: ValidationLevel; + message: string; +} + +export function validateConfigYaml( + config: ConfigYaml, +): ConfigValidationError[] { + const errors: ConfigValidationError[] = []; + + try { + configYamlSchema.parse(config); + } catch (e: any) { + return [ + { + level: ValidationLevel.Error, + message: e.message, + }, + ]; + } + + config.models?.forEach((model) => { + // Max tokens not too close to context length + if ( + model.defaultCompletionOptions?.contextLength && + model.defaultCompletionOptions?.maxTokens + ) { + const difference = + model.defaultCompletionOptions?.contextLength - + model.defaultCompletionOptions?.maxTokens; + + if (difference < 1000) { + errors.push({ + level: ValidationLevel.Warning, + message: `Model "${model.name}" has a contextLength of ${model.defaultCompletionOptions?.contextLength} and a maxTokens of ${model.defaultCompletionOptions?.maxTokens}. This leaves only ${difference} tokens for input context and will likely result in your inputs being truncated.`, + }); + } + } + + if (model.roles?.includes("autocomplete")) { + const modelName = model.model.toLocaleLowerCase(); + const nonAutocompleteModels = [ + // "gpt", + // "claude", + "mistral", + "instruct", + ]; + + if ( + nonAutocompleteModels.some((m) => modelName.includes(m)) && + !modelName.includes("deepseek") && + !modelName.includes("codestral") && + !modelName.toLowerCase().includes("coder") + ) { + errors.push({ + level: ValidationLevel.Warning, + message: `${model.model} is not trained for tab-autocomplete, and will result in low-quality suggestions. See the docs to learn more about why: https://docs.continue.dev/features/tab-autocomplete#i-want-better-completions-should-i-use-gpt-4`, + }); + } + } + }); + + return errors; +}