Elffuss BraidHub

kikocis/continue public

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