Elffuss BraidHub

kikocis/continue public

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