Elffuss BraidHub

kikocis/continue public

19cfb6ec829a · 14.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 { 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 return { rules, errors };
66}
67export default async function doLoadConfig(options: {
68 ide: IDE;
69 ideSettingsPromise: Promise<IdeSettings>;
70 controlPlaneClient: ControlPlaneClient;
71 llmLogger: ILLMLogger;
72 overrideConfigJson?: SerializedContinueConfig;
73 overrideConfigYaml?: AssistantUnrolled;
74 profileId: string;
75 overrideConfigYamlByPath?: string;
76 orgScopeId: string | null;
77 packageIdentifier: PackageIdentifier;
78}): Promise<ConfigResult<ContinueConfig>> {
79 const {
80 ide,
81 ideSettingsPromise,
82 controlPlaneClient,
83 llmLogger,
84 overrideConfigJson,
85 overrideConfigYaml,
86 profileId,
87 overrideConfigYamlByPath,
88 orgScopeId,
89 packageIdentifier,
90 } = options;
91
92 const ideInfo = await ide.getIdeInfo();
93 const uniqueId = await ide.getUniqueId();
94 const ideSettings = await ideSettingsPromise;
95 const workOsAccessToken = await controlPlaneClient.getAccessToken();
96
97 // Migrations for old config files
98 // Removes
99 const configJsonPath = getConfigJsonPath();
100 if (fs.existsSync(configJsonPath)) {
101 migrateJsonSharedConfig(configJsonPath, ide);
102 }
103
104 const configYamlPath = localPathOrUriToPath(
105 overrideConfigYamlByPath || getConfigYamlPath(ideInfo.ideType),
106 );
107
108 let newConfig: ContinueConfig | undefined;
109 let errors: ConfigValidationError[] | undefined;
110 let configLoadInterrupted = false;
111
112 if (overrideConfigYaml || fs.existsSync(configYamlPath)) {
113 const result = await loadContinueConfigFromYaml({
114 ide,
115 ideSettings,
116 ideInfo,
117 uniqueId,
118 llmLogger,
119 overrideConfigYaml,
120 controlPlaneClient,
121 orgScopeId,
122 packageIdentifier,
123 workOsAccessToken,
124 });
125 newConfig = result.config;
126 errors = result.errors;
127 configLoadInterrupted = result.configLoadInterrupted;
128 } else {
129 const result = await loadContinueConfigFromJson(
130 ide,
131 ideSettings,
132 ideInfo,
133 uniqueId,
134 llmLogger,
135 workOsAccessToken,
136 overrideConfigJson,
137 );
138 newConfig = result.config;
139 errors = result.errors;
140 configLoadInterrupted = result.configLoadInterrupted;
141 }
142
143 if (configLoadInterrupted || !newConfig) {
144 return { errors, config: newConfig, configLoadInterrupted: true };
145 }
146
147 // TODO using config result but result with non-fatal errors is an antipattern?
148 // Remove ability have undefined errors, just have an array
149 errors = [...(errors ?? [])];
150
151 // Load rules and always include the RulesContextProvider
152 const { rules, errors: rulesErrors } = await loadRules(ide);
153 errors.push(...rulesErrors);
154 newConfig.rules.unshift(...rules);
155 newConfig.contextProviders.push(new RulesContextProvider({}));
156
157 // Add current file as context if setting is enabled
158 if (
159 newConfig.experimental?.useCurrentFileAsContext === true &&
160 !newConfig.contextProviders.find(
161 (c) =>
162 c.description.title === CurrentFileContextProvider.description.title,
163 )
164 ) {
165 newConfig.contextProviders.push(new CurrentFileContextProvider({}));
166 }
167
168 // Show deprecation warnings for providers
169 const globalContext = new GlobalContext();
170 newConfig.contextProviders.forEach((provider) => {
171 if (provider.deprecationMessage) {
172 const providerTitle = provider.description.title;
173 const shownWarnings =
174 globalContext.get("shownDeprecatedProviderWarnings") ?? {};
175 if (!shownWarnings[providerTitle]) {
176 void ide.showToast("warning", provider.deprecationMessage);
177 globalContext.update("shownDeprecatedProviderWarnings", {
178 ...shownWarnings,
179 [providerTitle]: true,
180 });
181 }
182 }
183 });
184
185 // Add rules from colocated rules.md files in the codebase
186 const codebaseRulesCache = CodebaseRulesCache.getInstance();
187 newConfig.rules.unshift(...codebaseRulesCache.rules);
188 errors.push(...codebaseRulesCache.errors);
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}