| 1 | import fs from "fs"; |
| 2 | |
| 3 | import { |
| 4 | AssistantUnrolled, |
| 5 | ConfigResult, |
| 6 | ConfigValidationError, |
| 7 | ModelRole, |
| 8 | PackageIdentifier, |
| 9 | } from "@continuedev/config-yaml"; |
| 10 | |
| 11 | import { |
| 12 | ContinueConfig, |
| 13 | ContinueRcJson, |
| 14 | IDE, |
| 15 | IdeSettings, |
| 16 | ILLMLogger, |
| 17 | RuleWithSource, |
| 18 | SerializedContinueConfig, |
| 19 | Tool, |
| 20 | } from "../../"; |
| 21 | import { constructMcpSlashCommand } from "../../commands/slash/mcp"; |
| 22 | import { MCPManagerSingleton } from "../../context/mcp/MCPManagerSingleton"; |
| 23 | import MCPContextProvider from "../../context/providers/MCPContextProvider"; |
| 24 | import RulesContextProvider from "../../context/providers/RulesContextProvider"; |
| 25 | import { ControlPlaneProxyInfo } from "../../control-plane/analytics/IAnalyticsProvider.js"; |
| 26 | import { ControlPlaneClient } from "../../control-plane/client.js"; |
| 27 | import { getControlPlaneEnv } from "../../control-plane/env.js"; |
| 28 | import { TeamAnalytics } from "../../control-plane/TeamAnalytics.js"; |
| 29 | import ContinueProxy from "../../llm/llms/stubs/ContinueProxy"; |
| 30 | import { getConfigDependentToolDefinitions } from "../../tools"; |
| 31 | import { encodeMCPToolUri } from "../../tools/callTool"; |
| 32 | import { getMCPToolName } from "../../tools/mcpToolName"; |
| 33 | import { getConfigJsonPath, getConfigYamlPath } from "../../util/paths"; |
| 34 | import { localPathOrUriToPath } from "../../util/pathToUri"; |
| 35 | import { Telemetry } from "../../util/posthog"; |
| 36 | import { TTS } from "../../util/tts"; |
| 37 | import { getWorkspaceContinueRuleDotFiles } from "../getWorkspaceContinueRuleDotFiles"; |
| 38 | import { loadContinueConfigFromJson } from "../load"; |
| 39 | import { loadCodebaseRules } from "../markdown/loadCodebaseRules"; |
| 40 | import { loadMarkdownRules } from "../markdown/loadMarkdownRules"; |
| 41 | import { migrateJsonSharedConfig } from "../migrateSharedConfig"; |
| 42 | import { rectifySelectedModelsFromGlobalContext } from "../selectedModels"; |
| 43 | import { loadContinueConfigFromYaml } from "../yaml/loadYaml"; |
| 44 | |
| 45 | async function loadRules(ide: IDE) { |
| 46 | const rules: RuleWithSource[] = []; |
| 47 | const errors = []; |
| 48 | |
| 49 | // Add rules from .continuerules files |
| 50 | const { rules: yamlRules, errors: continueRulesErrors } = |
| 51 | await getWorkspaceContinueRuleDotFiles(ide); |
| 52 | rules.unshift(...yamlRules); |
| 53 | errors.push(...continueRulesErrors); |
| 54 | |
| 55 | // Add rules from markdown files in .continue/rules |
| 56 | const { rules: markdownRules, errors: markdownRulesErrors } = |
| 57 | await loadMarkdownRules(ide); |
| 58 | rules.unshift(...markdownRules); |
| 59 | errors.push(...markdownRulesErrors); |
| 60 | |
| 61 | return { rules, errors }; |
| 62 | } |
| 63 | export default async function doLoadConfig(options: { |
| 64 | ide: IDE; |
| 65 | ideSettingsPromise: Promise<IdeSettings>; |
| 66 | controlPlaneClient: ControlPlaneClient; |
| 67 | llmLogger: ILLMLogger; |
| 68 | overrideConfigJson?: SerializedContinueConfig; |
| 69 | overrideConfigYaml?: AssistantUnrolled; |
| 70 | profileId: string; |
| 71 | overrideConfigYamlByPath?: string; |
| 72 | orgScopeId: string | null; |
| 73 | packageIdentifier: PackageIdentifier; |
| 74 | }): Promise<ConfigResult<ContinueConfig>> { |
| 75 | const { |
| 76 | ide, |
| 77 | ideSettingsPromise, |
| 78 | controlPlaneClient, |
| 79 | llmLogger, |
| 80 | overrideConfigJson, |
| 81 | overrideConfigYaml, |
| 82 | profileId, |
| 83 | overrideConfigYamlByPath, |
| 84 | orgScopeId, |
| 85 | packageIdentifier, |
| 86 | } = options; |
| 87 | |
| 88 | const workspaceConfigs = await getWorkspaceConfigs(ide); |
| 89 | const ideInfo = await ide.getIdeInfo(); |
| 90 | const uniqueId = await ide.getUniqueId(); |
| 91 | const ideSettings = await ideSettingsPromise; |
| 92 | const workOsAccessToken = await controlPlaneClient.getAccessToken(); |
| 93 | |
| 94 | // Migrations for old config files |
| 95 | // Removes |
| 96 | const configJsonPath = getConfigJsonPath(); |
| 97 | if (fs.existsSync(configJsonPath)) { |
| 98 | migrateJsonSharedConfig(configJsonPath, ide); |
| 99 | } |
| 100 | |
| 101 | const configYamlPath = localPathOrUriToPath( |
| 102 | overrideConfigYamlByPath || getConfigYamlPath(ideInfo.ideType), |
| 103 | ); |
| 104 | |
| 105 | let newConfig: ContinueConfig | undefined; |
| 106 | let errors: ConfigValidationError[] | undefined; |
| 107 | let configLoadInterrupted = false; |
| 108 | |
| 109 | if (overrideConfigYaml || fs.existsSync(configYamlPath)) { |
| 110 | const result = await loadContinueConfigFromYaml({ |
| 111 | ide, |
| 112 | ideSettings, |
| 113 | ideInfo, |
| 114 | uniqueId, |
| 115 | llmLogger, |
| 116 | overrideConfigYaml, |
| 117 | controlPlaneClient, |
| 118 | orgScopeId, |
| 119 | packageIdentifier, |
| 120 | workOsAccessToken, |
| 121 | }); |
| 122 | newConfig = result.config; |
| 123 | errors = result.errors; |
| 124 | configLoadInterrupted = result.configLoadInterrupted; |
| 125 | } else { |
| 126 | const result = await loadContinueConfigFromJson( |
| 127 | ide, |
| 128 | workspaceConfigs, |
| 129 | ideSettings, |
| 130 | ideInfo, |
| 131 | uniqueId, |
| 132 | llmLogger, |
| 133 | workOsAccessToken, |
| 134 | overrideConfigJson, |
| 135 | ); |
| 136 | newConfig = result.config; |
| 137 | errors = result.errors; |
| 138 | configLoadInterrupted = result.configLoadInterrupted; |
| 139 | } |
| 140 | |
| 141 | if (configLoadInterrupted || !newConfig) { |
| 142 | return { errors, config: newConfig, configLoadInterrupted: true }; |
| 143 | } |
| 144 | |
| 145 | // TODO using config result but result with non-fatal errors is an antipattern? |
| 146 | // Remove ability have undefined errors, just have an array |
| 147 | errors = [...(errors ?? [])]; |
| 148 | |
| 149 | // Load rules and always include the RulesContextProvider |
| 150 | const { rules, errors: rulesErrors } = await loadRules(ide); |
| 151 | errors.push(...rulesErrors); |
| 152 | newConfig.rules.unshift(...rules); |
| 153 | newConfig.contextProviders.push(new RulesContextProvider({})); |
| 154 | |
| 155 | // Add rules from colocated rules.md files in the codebase |
| 156 | const { rules: codebaseRules, errors: codebaseRulesErrors } = |
| 157 | await loadCodebaseRules(ide); |
| 158 | newConfig.rules.unshift(...codebaseRules); |
| 159 | errors.push(...codebaseRulesErrors); |
| 160 | |
| 161 | // Rectify model selections for each role |
| 162 | newConfig = rectifySelectedModelsFromGlobalContext(newConfig, profileId); |
| 163 | |
| 164 | // Add things from MCP servers |
| 165 | const mcpManager = MCPManagerSingleton.getInstance(); |
| 166 | const mcpServerStatuses = mcpManager.getStatuses(); |
| 167 | |
| 168 | // Slightly hacky just need connection's client to make slash command for now |
| 169 | const serializableStatuses = mcpServerStatuses.map((server) => { |
| 170 | const { client, ...rest } = server; |
| 171 | return rest; |
| 172 | }); |
| 173 | newConfig.mcpServerStatuses = serializableStatuses; |
| 174 | |
| 175 | for (const server of mcpServerStatuses) { |
| 176 | if (server.status === "connected") { |
| 177 | const serverTools: Tool[] = server.tools.map((tool) => ({ |
| 178 | displayTitle: server.name + " " + tool.name, |
| 179 | function: { |
| 180 | description: tool.description, |
| 181 | name: getMCPToolName(server, tool), |
| 182 | parameters: tool.inputSchema, |
| 183 | }, |
| 184 | faviconUrl: server.faviconUrl, |
| 185 | readonly: false, |
| 186 | type: "function" as const, |
| 187 | uri: encodeMCPToolUri(server.id, tool.name), |
| 188 | group: server.name, |
| 189 | originalFunctionName: tool.name, |
| 190 | })); |
| 191 | newConfig.tools.push(...serverTools); |
| 192 | |
| 193 | const serverSlashCommands = server.prompts.map((prompt) => |
| 194 | constructMcpSlashCommand( |
| 195 | server.client, |
| 196 | prompt.name, |
| 197 | prompt.description, |
| 198 | prompt.arguments?.map((a: any) => a.name), |
| 199 | ), |
| 200 | ); |
| 201 | newConfig.slashCommands.push(...serverSlashCommands); |
| 202 | |
| 203 | const submenuItems = server.resources |
| 204 | .map((resource) => ({ |
| 205 | title: resource.name, |
| 206 | description: resource.description ?? resource.name, |
| 207 | id: resource.uri, |
| 208 | icon: server.faviconUrl, |
| 209 | })) |
| 210 | .concat( |
| 211 | server.resourceTemplates.map((template) => ({ |
| 212 | title: template.name, |
| 213 | description: template.description ?? template.name, |
| 214 | id: template.uriTemplate, |
| 215 | icon: server.faviconUrl, |
| 216 | })), |
| 217 | ); |
| 218 | if (submenuItems.length > 0) { |
| 219 | const serverContextProvider = new MCPContextProvider({ |
| 220 | submenuItems, |
| 221 | mcpId: server.id, |
| 222 | serverName: server.name, |
| 223 | }); |
| 224 | newConfig.contextProviders.push(serverContextProvider); |
| 225 | } |
| 226 | } |
| 227 | } |
| 228 | |
| 229 | newConfig.tools.push( |
| 230 | ...getConfigDependentToolDefinitions({ |
| 231 | rules: newConfig.rules, |
| 232 | }), |
| 233 | ); |
| 234 | |
| 235 | // Detect duplicate tool names |
| 236 | const counts: Record<string, number> = {}; |
| 237 | newConfig.tools.forEach((tool) => { |
| 238 | if (counts[tool.function.name]) { |
| 239 | counts[tool.function.name] = counts[tool.function.name] + 1; |
| 240 | } else { |
| 241 | counts[tool.function.name] = 1; |
| 242 | } |
| 243 | }); |
| 244 | |
| 245 | Object.entries(counts).forEach(([toolName, count]) => { |
| 246 | if (count > 1) { |
| 247 | errors!.push({ |
| 248 | fatal: false, |
| 249 | message: `Duplicate (${count}) tools named "${toolName}" detected. Permissions will conflict and usage may be unpredictable`, |
| 250 | }); |
| 251 | } |
| 252 | }); |
| 253 | |
| 254 | const ruleCounts: Record<string, number> = {}; |
| 255 | newConfig.rules.forEach((rule) => { |
| 256 | if (rule.name) { |
| 257 | if (ruleCounts[rule.name]) { |
| 258 | ruleCounts[rule.name] = ruleCounts[rule.name] + 1; |
| 259 | } else { |
| 260 | ruleCounts[rule.name] = 1; |
| 261 | } |
| 262 | } |
| 263 | }); |
| 264 | |
| 265 | Object.entries(ruleCounts).forEach(([ruleName, count]) => { |
| 266 | if (count > 1) { |
| 267 | errors!.push({ |
| 268 | fatal: false, |
| 269 | message: `Duplicate (${count}) rules named "${ruleName}" detected. This may cause unexpected behavior`, |
| 270 | }); |
| 271 | } |
| 272 | }); |
| 273 | |
| 274 | newConfig.allowAnonymousTelemetry = |
| 275 | newConfig.allowAnonymousTelemetry && (await ide.isTelemetryEnabled()); |
| 276 | |
| 277 | // Setup telemetry only after (and if) we know it is enabled |
| 278 | await Telemetry.setup( |
| 279 | newConfig.allowAnonymousTelemetry ?? true, |
| 280 | await ide.getUniqueId(), |
| 281 | ideInfo, |
| 282 | ); |
| 283 | |
| 284 | // TODO: pass config to pre-load non-system TTS models |
| 285 | await TTS.setup(); |
| 286 | |
| 287 | // Set up control plane proxy if configured |
| 288 | const controlPlane = (newConfig as any).controlPlane; |
| 289 | const useOnPremProxy = |
| 290 | controlPlane?.useContinueForTeamsProxy === false && controlPlane?.proxyUrl; |
| 291 | |
| 292 | const env = await getControlPlaneEnv(ideSettingsPromise); |
| 293 | let controlPlaneProxyUrl: string = useOnPremProxy |
| 294 | ? controlPlane?.proxyUrl |
| 295 | : env.DEFAULT_CONTROL_PLANE_PROXY_URL; |
| 296 | |
| 297 | if (!controlPlaneProxyUrl.endsWith("/")) { |
| 298 | controlPlaneProxyUrl += "/"; |
| 299 | } |
| 300 | const controlPlaneProxyInfo = { |
| 301 | profileId, |
| 302 | controlPlaneProxyUrl, |
| 303 | workOsAccessToken, |
| 304 | }; |
| 305 | |
| 306 | if (newConfig.analytics) { |
| 307 | // await TeamAnalytics.setup( |
| 308 | // newConfig.analytics, |
| 309 | // uniqueId, |
| 310 | // ideInfo.extensionVersion, |
| 311 | // controlPlaneClient, |
| 312 | // controlPlaneProxyInfo, |
| 313 | // ); |
| 314 | } else { |
| 315 | await TeamAnalytics.shutdown(); |
| 316 | } |
| 317 | |
| 318 | newConfig = await injectControlPlaneProxyInfo( |
| 319 | newConfig, |
| 320 | controlPlaneProxyInfo, |
| 321 | ); |
| 322 | |
| 323 | return { config: newConfig, errors, configLoadInterrupted: false }; |
| 324 | } |
| 325 | |
| 326 | // Pass ControlPlaneProxyInfo to objects that need it |
| 327 | async function injectControlPlaneProxyInfo( |
| 328 | config: ContinueConfig, |
| 329 | info: ControlPlaneProxyInfo, |
| 330 | ): Promise<ContinueConfig> { |
| 331 | Object.keys(config.modelsByRole).forEach((key) => { |
| 332 | config.modelsByRole[key as ModelRole].forEach((model) => { |
| 333 | if (model.providerName === "continue-proxy") { |
| 334 | (model as ContinueProxy).controlPlaneProxyInfo = info; |
| 335 | } |
| 336 | }); |
| 337 | }); |
| 338 | |
| 339 | Object.keys(config.selectedModelByRole).forEach((key) => { |
| 340 | const model = config.selectedModelByRole[key as ModelRole]; |
| 341 | if (model?.providerName === "continue-proxy") { |
| 342 | (model as ContinueProxy).controlPlaneProxyInfo = info; |
| 343 | } |
| 344 | }); |
| 345 | |
| 346 | config.modelsByRole.chat.forEach((model) => { |
| 347 | if (model.providerName === "continue-proxy") { |
| 348 | (model as ContinueProxy).controlPlaneProxyInfo = info; |
| 349 | } |
| 350 | }); |
| 351 | |
| 352 | return config; |
| 353 | } |
| 354 | |
| 355 | async function getWorkspaceConfigs(ide: IDE): Promise<ContinueRcJson[]> { |
| 356 | const ideInfo = await ide.getIdeInfo(); |
| 357 | let workspaceConfigs: ContinueRcJson[] = []; |
| 358 | |
| 359 | try { |
| 360 | workspaceConfigs = await ide.getWorkspaceConfigs(); |
| 361 | |
| 362 | // Config is sent over the wire from JB so we need to parse it |
| 363 | if (ideInfo.ideType === "jetbrains") { |
| 364 | workspaceConfigs = (workspaceConfigs as any).map(JSON.parse); |
| 365 | } |
| 366 | } catch (e) { |
| 367 | console.debug("Failed to load workspace configs: ", e); |
| 368 | } |
| 369 | |
| 370 | return workspaceConfigs; |
| 371 | } |