Elffuss BraidHub

kikocis/continue public

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