| 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 | IDE, |
| 14 | ILLMLogger, |
| 15 | RuleWithSource, |
| 16 | SerializedContinueConfig, |
| 17 | SlashCommandDescWithSource, |
| 18 | Tool, |
| 19 | } from "../../"; |
| 20 | import { stringifyMcpPrompt } from "../../commands/slash/mcpSlashCommand"; |
| 21 | import { convertRuleBlockToSlashCommand } from "../../commands/slash/ruleBlockSlashCommand"; |
| 22 | import { MCPManagerSingleton } from "../../context/mcp/MCPManagerSingleton"; |
| 23 | import ContinueProxyContextProvider from "../../context/providers/ContinueProxyContextProvider"; |
| 24 | import MCPContextProvider from "../../context/providers/MCPContextProvider"; |
| 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 { PolicySingleton } from "../../control-plane/PolicySingleton"; |
| 29 | import { TeamAnalytics } from "../../control-plane/TeamAnalytics.js"; |
| 30 | import ContinueProxy from "../../llm/llms/stubs/ContinueProxy"; |
| 31 | import { getConfigDependentToolDefinitions } from "../../tools"; |
| 32 | import { encodeMCPToolUri } from "../../tools/callTool"; |
| 33 | import { getMCPToolName } from "../../tools/mcpToolName"; |
| 34 | import { GlobalContext } from "../../util/GlobalContext"; |
| 35 | import { getConfigJsonPath, getConfigYamlPath } from "../../util/paths"; |
| 36 | import { localPathOrUriToPath } from "../../util/pathToUri"; |
| 37 | import { Telemetry } from "../../util/posthog"; |
| 38 | import { SentryLogger } from "../../util/sentry/SentryLogger"; |
| 39 | import { TTS } from "../../util/tts"; |
| 40 | import { getWorkspaceContinueRuleDotFiles } from "../getWorkspaceContinueRuleDotFiles"; |
| 41 | import { loadContinueConfigFromJson } from "../load"; |
| 42 | import { CodebaseRulesCache } from "../markdown/loadCodebaseRules"; |
| 43 | import { loadMarkdownRules } from "../markdown/loadMarkdownRules"; |
| 44 | import { migrateJsonSharedConfig } from "../migrateSharedConfig"; |
| 45 | import { rectifySelectedModelsFromGlobalContext } from "../selectedModels"; |
| 46 | import { loadContinueConfigFromYaml } from "../yaml/loadYaml"; |
| 47 | |
| 48 | async function loadRules(ide: IDE) { |
| 49 | const rules: RuleWithSource[] = []; |
| 50 | const errors = []; |
| 51 | |
| 52 | // Add rules from .continuerules files |
| 53 | const { rules: yamlRules, errors: continueRulesErrors } = |
| 54 | await getWorkspaceContinueRuleDotFiles(ide); |
| 55 | rules.unshift(...yamlRules); |
| 56 | errors.push(...continueRulesErrors); |
| 57 | |
| 58 | // Add rules from markdown files in .continue/rules |
| 59 | const { rules: markdownRules, errors: markdownRulesErrors } = |
| 60 | await loadMarkdownRules(ide); |
| 61 | rules.unshift(...markdownRules); |
| 62 | errors.push(...markdownRulesErrors); |
| 63 | |
| 64 | // Add colocated rules from CodebaseRulesCache |
| 65 | const codebaseRulesCache = CodebaseRulesCache.getInstance(); |
| 66 | rules.unshift(...codebaseRulesCache.rules); |
| 67 | errors.push(...codebaseRulesCache.errors); |
| 68 | |
| 69 | return { rules, errors }; |
| 70 | } |
| 71 | export default async function doLoadConfig(options: { |
| 72 | ide: IDE; |
| 73 | controlPlaneClient: ControlPlaneClient; |
| 74 | llmLogger: ILLMLogger; |
| 75 | overrideConfigJson?: SerializedContinueConfig; |
| 76 | overrideConfigYaml?: AssistantUnrolled; |
| 77 | profileId: string; |
| 78 | overrideConfigYamlByPath?: string; |
| 79 | orgScopeId: string | null; |
| 80 | packageIdentifier: PackageIdentifier; |
| 81 | }): Promise<ConfigResult<ContinueConfig>> { |
| 82 | const { |
| 83 | ide, |
| 84 | controlPlaneClient, |
| 85 | llmLogger, |
| 86 | overrideConfigJson, |
| 87 | overrideConfigYaml, |
| 88 | profileId, |
| 89 | overrideConfigYamlByPath, |
| 90 | orgScopeId, |
| 91 | packageIdentifier, |
| 92 | } = options; |
| 93 | |
| 94 | const ideInfo = await ide.getIdeInfo(); |
| 95 | const uniqueId = await ide.getUniqueId(); |
| 96 | const ideSettings = await ide.getIdeSettings(); |
| 97 | const workOsAccessToken = await controlPlaneClient.getAccessToken(); |
| 98 | const isSignedIn = await controlPlaneClient.isSignedIn(); |
| 99 | |
| 100 | // Migrations for old config files |
| 101 | // Removes |
| 102 | const configJsonPath = getConfigJsonPath(); |
| 103 | if (fs.existsSync(configJsonPath)) { |
| 104 | migrateJsonSharedConfig(configJsonPath, ide); |
| 105 | } |
| 106 | |
| 107 | const configYamlPath = localPathOrUriToPath( |
| 108 | overrideConfigYamlByPath || getConfigYamlPath(ideInfo.ideType), |
| 109 | ); |
| 110 | |
| 111 | let newConfig: ContinueConfig | undefined; |
| 112 | let errors: ConfigValidationError[] | undefined; |
| 113 | let configLoadInterrupted = false; |
| 114 | |
| 115 | if (overrideConfigYaml || fs.existsSync(configYamlPath)) { |
| 116 | const result = await loadContinueConfigFromYaml({ |
| 117 | ide, |
| 118 | ideSettings, |
| 119 | ideInfo, |
| 120 | uniqueId, |
| 121 | llmLogger, |
| 122 | overrideConfigYaml, |
| 123 | controlPlaneClient, |
| 124 | orgScopeId, |
| 125 | packageIdentifier, |
| 126 | workOsAccessToken, |
| 127 | }); |
| 128 | newConfig = result.config; |
| 129 | errors = result.errors; |
| 130 | configLoadInterrupted = result.configLoadInterrupted; |
| 131 | } else { |
| 132 | const result = await loadContinueConfigFromJson( |
| 133 | ide, |
| 134 | ideSettings, |
| 135 | ideInfo, |
| 136 | uniqueId, |
| 137 | llmLogger, |
| 138 | workOsAccessToken, |
| 139 | overrideConfigJson, |
| 140 | ); |
| 141 | newConfig = result.config; |
| 142 | errors = result.errors; |
| 143 | configLoadInterrupted = result.configLoadInterrupted; |
| 144 | } |
| 145 | |
| 146 | if (configLoadInterrupted || !newConfig) { |
| 147 | return { errors, config: newConfig, configLoadInterrupted: true }; |
| 148 | } |
| 149 | |
| 150 | // TODO using config result but result with non-fatal errors is an antipattern? |
| 151 | // Remove ability have undefined errors, just have an array |
| 152 | errors = [...(errors ?? [])]; |
| 153 | |
| 154 | // Load rules and always include the RulesContextProvider |
| 155 | const { rules, errors: rulesErrors } = await loadRules(ide); |
| 156 | errors.push(...rulesErrors); |
| 157 | newConfig.rules.unshift(...rules); |
| 158 | |
| 159 | // Convert invokable rules to slash commands |
| 160 | for (const rule of newConfig.rules) { |
| 161 | if (rule.invokable) { |
| 162 | try { |
| 163 | const slashCommand = convertRuleBlockToSlashCommand(rule); |
| 164 | (newConfig.slashCommands ??= []).push(slashCommand); |
| 165 | } catch (e) { |
| 166 | errors.push({ |
| 167 | message: `Error converting invokable rule ${rule.name} to slash command: ${e instanceof Error ? e.message : e}`, |
| 168 | fatal: false, |
| 169 | }); |
| 170 | } |
| 171 | } |
| 172 | } |
| 173 | |
| 174 | const proxyContextProvider = newConfig.contextProviders?.find( |
| 175 | (cp) => cp.description.title === "continue-proxy", |
| 176 | ); |
| 177 | if (proxyContextProvider) { |
| 178 | (proxyContextProvider as ContinueProxyContextProvider).workOsAccessToken = |
| 179 | workOsAccessToken; |
| 180 | } |
| 181 | |
| 182 | // Show deprecation warnings for providers |
| 183 | const globalContext = new GlobalContext(); |
| 184 | newConfig.contextProviders.forEach((provider) => { |
| 185 | if (provider.deprecationMessage) { |
| 186 | const providerTitle = provider.description.title; |
| 187 | const shownWarnings = |
| 188 | globalContext.get("shownDeprecatedProviderWarnings") ?? {}; |
| 189 | if (!shownWarnings[providerTitle]) { |
| 190 | void ide.showToast("warning", provider.deprecationMessage); |
| 191 | globalContext.update("shownDeprecatedProviderWarnings", { |
| 192 | ...shownWarnings, |
| 193 | [providerTitle]: true, |
| 194 | }); |
| 195 | } |
| 196 | } |
| 197 | }); |
| 198 | |
| 199 | // Rectify model selections for each role |
| 200 | newConfig = rectifySelectedModelsFromGlobalContext(newConfig, profileId); |
| 201 | |
| 202 | // Add things from MCP servers |
| 203 | const mcpManager = MCPManagerSingleton.getInstance(); |
| 204 | const mcpServerStatuses = mcpManager.getStatuses(); |
| 205 | |
| 206 | const serializableStatuses = mcpServerStatuses.map((server) => { |
| 207 | const { client, ...rest } = server; |
| 208 | return rest; |
| 209 | }); |
| 210 | newConfig.mcpServerStatuses = serializableStatuses; |
| 211 | |
| 212 | for (const server of mcpServerStatuses) { |
| 213 | if (server.status === "connected") { |
| 214 | const serverTools: Tool[] = server.tools.map((tool) => ({ |
| 215 | displayTitle: server.name + " " + tool.name, |
| 216 | function: { |
| 217 | description: tool.description, |
| 218 | name: getMCPToolName(server, tool), |
| 219 | parameters: tool.inputSchema, |
| 220 | }, |
| 221 | faviconUrl: server.faviconUrl, |
| 222 | readonly: false, |
| 223 | type: "function" as const, |
| 224 | uri: encodeMCPToolUri(server.id, tool.name), |
| 225 | group: server.name, |
| 226 | originalFunctionName: tool.name, |
| 227 | })); |
| 228 | newConfig.tools.push(...serverTools); |
| 229 | |
| 230 | // Fetch MCP prompt content during config load |
| 231 | const serverSlashCommands: SlashCommandDescWithSource[] = |
| 232 | await Promise.all( |
| 233 | server.prompts.map(async (prompt) => { |
| 234 | let promptContent: string | undefined; |
| 235 | |
| 236 | try { |
| 237 | // Fetch the actual prompt content from the MCP server |
| 238 | const mcpPromptResponse = await mcpManager.getPrompt( |
| 239 | server.name, |
| 240 | prompt.name, |
| 241 | {}, // Empty args for now - TODO: handle prompt arguments |
| 242 | ); |
| 243 | promptContent = stringifyMcpPrompt(mcpPromptResponse); |
| 244 | } catch (error) { |
| 245 | console.warn( |
| 246 | `Failed to fetch MCP prompt content for ${prompt.name} from server ${server.name}:`, |
| 247 | error, |
| 248 | ); |
| 249 | // Keep promptContent as undefined so the UI can show a fallback |
| 250 | } |
| 251 | |
| 252 | return { |
| 253 | name: prompt.name, |
| 254 | description: prompt.description ?? "MCP Prompt", |
| 255 | source: "mcp-prompt", |
| 256 | isLegacy: false, |
| 257 | prompt: promptContent, // Store the actual prompt content |
| 258 | mcpServerName: server.name, // Used in client to retrieve prompt |
| 259 | mcpArgs: prompt.arguments, |
| 260 | }; |
| 261 | }), |
| 262 | ); |
| 263 | newConfig.slashCommands.push(...serverSlashCommands); |
| 264 | |
| 265 | const submenuItems = server.resources |
| 266 | .map((resource) => ({ |
| 267 | title: resource.name, |
| 268 | description: resource.description ?? resource.name, |
| 269 | id: resource.uri, |
| 270 | icon: server.faviconUrl, |
| 271 | })) |
| 272 | .concat( |
| 273 | server.resourceTemplates.map((template) => ({ |
| 274 | title: template.name, |
| 275 | description: template.description ?? template.name, |
| 276 | id: template.uriTemplate, |
| 277 | icon: server.faviconUrl, |
| 278 | })), |
| 279 | ); |
| 280 | if (submenuItems.length > 0) { |
| 281 | const serverContextProvider = new MCPContextProvider({ |
| 282 | submenuItems, |
| 283 | mcpId: server.id, |
| 284 | serverName: server.name, |
| 285 | }); |
| 286 | newConfig.contextProviders.push(serverContextProvider); |
| 287 | } |
| 288 | } |
| 289 | } |
| 290 | |
| 291 | newConfig.tools.push( |
| 292 | ...getConfigDependentToolDefinitions({ |
| 293 | rules: newConfig.rules, |
| 294 | enableExperimentalTools: |
| 295 | newConfig.experimental?.enableExperimentalTools ?? false, |
| 296 | isSignedIn, |
| 297 | isRemote: await ide.isWorkspaceRemote(), |
| 298 | modelName: newConfig.selectedModelByRole.chat?.model, |
| 299 | }), |
| 300 | ); |
| 301 | |
| 302 | // Detect duplicate tool names |
| 303 | const counts: Record<string, number> = {}; |
| 304 | newConfig.tools.forEach((tool) => { |
| 305 | if (counts[tool.function.name]) { |
| 306 | counts[tool.function.name] = counts[tool.function.name] + 1; |
| 307 | } else { |
| 308 | counts[tool.function.name] = 1; |
| 309 | } |
| 310 | }); |
| 311 | |
| 312 | Object.entries(counts).forEach(([toolName, count]) => { |
| 313 | if (count > 1) { |
| 314 | errors!.push({ |
| 315 | fatal: false, |
| 316 | message: `Duplicate (${count}) tools named "${toolName}" detected. Permissions will conflict and usage may be unpredictable`, |
| 317 | }); |
| 318 | } |
| 319 | }); |
| 320 | |
| 321 | const ruleCounts: Record<string, number> = {}; |
| 322 | newConfig.rules.forEach((rule) => { |
| 323 | if (rule.name) { |
| 324 | if (ruleCounts[rule.name]) { |
| 325 | ruleCounts[rule.name] = ruleCounts[rule.name] + 1; |
| 326 | } else { |
| 327 | ruleCounts[rule.name] = 1; |
| 328 | } |
| 329 | } |
| 330 | }); |
| 331 | |
| 332 | Object.entries(ruleCounts).forEach(([ruleName, count]) => { |
| 333 | if (count > 1) { |
| 334 | errors!.push({ |
| 335 | fatal: false, |
| 336 | message: `Duplicate (${count}) rules named "${ruleName}" detected. This may cause unexpected behavior`, |
| 337 | }); |
| 338 | } |
| 339 | }); |
| 340 | |
| 341 | if (newConfig.allowAnonymousTelemetry !== false) { |
| 342 | if ((await ide.isTelemetryEnabled()) === false) { |
| 343 | newConfig.allowAnonymousTelemetry = false; |
| 344 | } |
| 345 | } |
| 346 | |
| 347 | // Org policies |
| 348 | const policy = PolicySingleton.getInstance().policy?.policy; |
| 349 | if (policy?.allowAnonymousTelemetry === false) { |
| 350 | newConfig.allowAnonymousTelemetry = false; |
| 351 | } |
| 352 | if (policy?.allowCodebaseIndexing === false) { |
| 353 | newConfig.disableIndexing = true; |
| 354 | } |
| 355 | |
| 356 | // Setup telemetry only after (and if) we know it is enabled |
| 357 | await Telemetry.setup( |
| 358 | newConfig.allowAnonymousTelemetry ?? true, |
| 359 | await ide.getUniqueId(), |
| 360 | ideInfo, |
| 361 | ); |
| 362 | |
| 363 | // Setup Sentry logger with same telemetry settings |
| 364 | // TODO: Remove Continue team member check once Sentry is ready for all users |
| 365 | let userEmail: string | undefined; |
| 366 | try { |
| 367 | // Access the session info to get user email for Continue team member check |
| 368 | const sessionInfo = await (controlPlaneClient as any).sessionInfoPromise; |
| 369 | userEmail = sessionInfo?.account?.id; |
| 370 | } catch (error) { |
| 371 | // Ignore errors getting session info, will default to no Sentry |
| 372 | } |
| 373 | |
| 374 | await SentryLogger.setup( |
| 375 | newConfig.allowAnonymousTelemetry ?? false, |
| 376 | await ide.getUniqueId(), |
| 377 | ideInfo, |
| 378 | userEmail, |
| 379 | ); |
| 380 | |
| 381 | // TODO: pass config to pre-load non-system TTS models |
| 382 | await TTS.setup(); |
| 383 | |
| 384 | // Set up control plane proxy if configured |
| 385 | const controlPlane = (newConfig as any).controlPlane; |
| 386 | const useOnPremProxy = |
| 387 | controlPlane?.useContinueForTeamsProxy === false && controlPlane?.proxyUrl; |
| 388 | |
| 389 | const env = await getControlPlaneEnv(Promise.resolve(ideSettings)); |
| 390 | let controlPlaneProxyUrl: string = useOnPremProxy |
| 391 | ? controlPlane?.proxyUrl |
| 392 | : env.DEFAULT_CONTROL_PLANE_PROXY_URL; |
| 393 | |
| 394 | if (!controlPlaneProxyUrl.endsWith("/")) { |
| 395 | controlPlaneProxyUrl += "/"; |
| 396 | } |
| 397 | const controlPlaneProxyInfo = { |
| 398 | profileId, |
| 399 | controlPlaneProxyUrl, |
| 400 | workOsAccessToken, |
| 401 | }; |
| 402 | |
| 403 | if (newConfig.analytics) { |
| 404 | // FIXME before re-enabling TeamAnalytics.setup() populate workspaceId in |
| 405 | // controlPlaneProxyInfo to prevent /proxy/analytics/undefined/capture calls |
| 406 | // where undefined is :workspaceId |
| 407 | // await TeamAnalytics.setup( |
| 408 | // newConfig.analytics, |
| 409 | // uniqueId, |
| 410 | // ideInfo.extensionVersion, |
| 411 | // controlPlaneClient, |
| 412 | // controlPlaneProxyInfo, |
| 413 | // ); |
| 414 | } else { |
| 415 | await TeamAnalytics.shutdown(); |
| 416 | } |
| 417 | |
| 418 | newConfig = await injectControlPlaneProxyInfo( |
| 419 | newConfig, |
| 420 | controlPlaneProxyInfo, |
| 421 | ); |
| 422 | |
| 423 | return { config: newConfig, errors, configLoadInterrupted: false }; |
| 424 | } |
| 425 | |
| 426 | // Pass ControlPlaneProxyInfo to objects that need it |
| 427 | async function injectControlPlaneProxyInfo( |
| 428 | config: ContinueConfig, |
| 429 | info: ControlPlaneProxyInfo, |
| 430 | ): Promise<ContinueConfig> { |
| 431 | Object.keys(config.modelsByRole).forEach((key) => { |
| 432 | config.modelsByRole[key as ModelRole].forEach((model) => { |
| 433 | if (model.providerName === "continue-proxy") { |
| 434 | (model as ContinueProxy).controlPlaneProxyInfo = info; |
| 435 | } |
| 436 | }); |
| 437 | }); |
| 438 | |
| 439 | Object.keys(config.selectedModelByRole).forEach((key) => { |
| 440 | const model = config.selectedModelByRole[key as ModelRole]; |
| 441 | if (model?.providerName === "continue-proxy") { |
| 442 | (model as ContinueProxy).controlPlaneProxyInfo = info; |
| 443 | } |
| 444 | }); |
| 445 | |
| 446 | config.modelsByRole.chat.forEach((model) => { |
| 447 | if (model.providerName === "continue-proxy") { |
| 448 | (model as ContinueProxy).controlPlaneProxyInfo = info; |
| 449 | } |
| 450 | }); |
| 451 | |
| 452 | return config; |
| 453 | } |