Elffuss BraidHub

kikocis/continue public

c04584525d2e · 14.0 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 ContinueProxyContextProvider from "../../context/providers/ContinueProxyContextProvider";
24import MCPContextProvider from "../../context/providers/MCPContextProvider";
25import { ControlPlaneProxyInfo } from "../../control-plane/analytics/IAnalyticsProvider.js";
26import { ControlPlaneClient } from "../../control-plane/client.js";
27import { getControlPlaneEnv } from "../../control-plane/env.js";
28import { PolicySingleton } from "../../control-plane/PolicySingleton";
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 { SentryLogger } from "../../util/sentry/SentryLogger";
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 // 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}
71export default async function doLoadConfig(options: {
72 ide: IDE;
73 ideSettingsPromise: Promise<IdeSettings>;
74 controlPlaneClient: ControlPlaneClient;
75 llmLogger: ILLMLogger;
76 overrideConfigJson?: SerializedContinueConfig;
77 overrideConfigYaml?: AssistantUnrolled;
78 profileId: string;
79 overrideConfigYamlByPath?: string;
80 orgScopeId: string | null;
81 packageIdentifier: PackageIdentifier;
82}): Promise<ConfigResult<ContinueConfig>> {
83 const {
84 ide,
85 ideSettingsPromise,
86 controlPlaneClient,
87 llmLogger,
88 overrideConfigJson,
89 overrideConfigYaml,
90 profileId,
91 overrideConfigYamlByPath,
92 orgScopeId,
93 packageIdentifier,
94 } = options;
95
96 const ideInfo = await ide.getIdeInfo();
97 const uniqueId = await ide.getUniqueId();
98 const ideSettings = await ideSettingsPromise;
99 const workOsAccessToken = await controlPlaneClient.getAccessToken();
100 const isSignedIn = await controlPlaneClient.isSignedIn();
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
161 const proxyContextProvider = newConfig.contextProviders?.find(
162 (cp) => cp.description.title === "continue-proxy",
163 );
164 if (proxyContextProvider) {
165 (proxyContextProvider as ContinueProxyContextProvider).workOsAccessToken =
166 workOsAccessToken;
167 }
168
169 // Show deprecation warnings for providers
170 const globalContext = new GlobalContext();
171 newConfig.contextProviders.forEach((provider) => {
172 if (provider.deprecationMessage) {
173 const providerTitle = provider.description.title;
174 const shownWarnings =
175 globalContext.get("shownDeprecatedProviderWarnings") ?? {};
176 if (!shownWarnings[providerTitle]) {
177 void ide.showToast("warning", provider.deprecationMessage);
178 globalContext.update("shownDeprecatedProviderWarnings", {
179 ...shownWarnings,
180 [providerTitle]: true,
181 });
182 }
183 }
184 });
185
186 // Rectify model selections for each role
187 newConfig = rectifySelectedModelsFromGlobalContext(newConfig, profileId);
188
189 // Add things from MCP servers
190 const mcpManager = MCPManagerSingleton.getInstance();
191 const mcpServerStatuses = mcpManager.getStatuses();
192
193 // Slightly hacky just need connection's client to make slash command for now
194 const serializableStatuses = mcpServerStatuses.map((server) => {
195 const { client, ...rest } = server;
196 return rest;
197 });
198 newConfig.mcpServerStatuses = serializableStatuses;
199
200 for (const server of mcpServerStatuses) {
201 if (server.status === "connected") {
202 const serverTools: Tool[] = server.tools.map((tool) => ({
203 displayTitle: server.name + " " + tool.name,
204 function: {
205 description: tool.description,
206 name: getMCPToolName(server, tool),
207 parameters: tool.inputSchema,
208 },
209 faviconUrl: server.faviconUrl,
210 readonly: false,
211 type: "function" as const,
212 uri: encodeMCPToolUri(server.id, tool.name),
213 group: server.name,
214 originalFunctionName: tool.name,
215 }));
216 newConfig.tools.push(...serverTools);
217
218 // Fetch MCP prompt content during config load
219 const serverSlashCommands: SlashCommandDescWithSource[] =
220 await Promise.all(
221 server.prompts.map(async (prompt) => {
222 let promptContent: string | undefined;
223
224 try {
225 // Fetch the actual prompt content from the MCP server
226 const mcpPromptResponse = await mcpManager.getPrompt(
227 server.name,
228 prompt.name,
229 {}, // Empty args for now - TODO: handle prompt arguments
230 );
231 promptContent = stringifyMcpPrompt(mcpPromptResponse);
232 } catch (error) {
233 console.warn(
234 `Failed to fetch MCP prompt content for ${prompt.name} from server ${server.name}:`,
235 error,
236 );
237 // Keep promptContent as undefined so the UI can show a fallback
238 }
239
240 return {
241 name: prompt.name,
242 description: prompt.description ?? "MCP Prompt",
243 source: "mcp-prompt",
244 isLegacy: false,
245 prompt: promptContent, // Store the actual prompt content
246 mcpServerName: server.name, // Used in client to retrieve prompt
247 mcpArgs: prompt.arguments,
248 };
249 }),
250 );
251 newConfig.slashCommands.push(...serverSlashCommands);
252
253 const submenuItems = server.resources
254 .map((resource) => ({
255 title: resource.name,
256 description: resource.description ?? resource.name,
257 id: resource.uri,
258 icon: server.faviconUrl,
259 }))
260 .concat(
261 server.resourceTemplates.map((template) => ({
262 title: template.name,
263 description: template.description ?? template.name,
264 id: template.uriTemplate,
265 icon: server.faviconUrl,
266 })),
267 );
268 if (submenuItems.length > 0) {
269 const serverContextProvider = new MCPContextProvider({
270 submenuItems,
271 mcpId: server.id,
272 serverName: server.name,
273 });
274 newConfig.contextProviders.push(serverContextProvider);
275 }
276 }
277 }
278
279 newConfig.tools.push(
280 ...getConfigDependentToolDefinitions({
281 rules: newConfig.rules,
282 enableExperimentalTools:
283 newConfig.experimental?.enableExperimentalTools ?? false,
284 isSignedIn,
285 }),
286 );
287
288 // Detect duplicate tool names
289 const counts: Record<string, number> = {};
290 newConfig.tools.forEach((tool) => {
291 if (counts[tool.function.name]) {
292 counts[tool.function.name] = counts[tool.function.name] + 1;
293 } else {
294 counts[tool.function.name] = 1;
295 }
296 });
297
298 Object.entries(counts).forEach(([toolName, count]) => {
299 if (count > 1) {
300 errors!.push({
301 fatal: false,
302 message: `Duplicate (${count}) tools named "${toolName}" detected. Permissions will conflict and usage may be unpredictable`,
303 });
304 }
305 });
306
307 const ruleCounts: Record<string, number> = {};
308 newConfig.rules.forEach((rule) => {
309 if (rule.name) {
310 if (ruleCounts[rule.name]) {
311 ruleCounts[rule.name] = ruleCounts[rule.name] + 1;
312 } else {
313 ruleCounts[rule.name] = 1;
314 }
315 }
316 });
317
318 Object.entries(ruleCounts).forEach(([ruleName, count]) => {
319 if (count > 1) {
320 errors!.push({
321 fatal: false,
322 message: `Duplicate (${count}) rules named "${ruleName}" detected. This may cause unexpected behavior`,
323 });
324 }
325 });
326
327 if (newConfig.allowAnonymousTelemetry !== false) {
328 if ((await ide.isTelemetryEnabled()) === false) {
329 newConfig.allowAnonymousTelemetry = false;
330 }
331 }
332
333 if (
334 PolicySingleton.getInstance().policy?.policy?.allowAnonymousTelemetry ===
335 false
336 ) {
337 newConfig.allowAnonymousTelemetry = false;
338 }
339
340 // Setup telemetry only after (and if) we know it is enabled
341 await Telemetry.setup(
342 newConfig.allowAnonymousTelemetry ?? true,
343 await ide.getUniqueId(),
344 ideInfo,
345 );
346
347 // Setup Sentry logger with same telemetry settings
348 // TODO: Remove Continue team member check once Sentry is ready for all users
349 let userEmail: string | undefined;
350 try {
351 // Access the session info to get user email for Continue team member check
352 const sessionInfo = await (controlPlaneClient as any).sessionInfoPromise;
353 userEmail = sessionInfo?.account?.id;
354 } catch (error) {
355 // Ignore errors getting session info, will default to no Sentry
356 }
357
358 await SentryLogger.setup(
359 newConfig.allowAnonymousTelemetry ?? false,
360 await ide.getUniqueId(),
361 ideInfo,
362 userEmail,
363 );
364
365 // TODO: pass config to pre-load non-system TTS models
366 await TTS.setup();
367
368 // Set up control plane proxy if configured
369 const controlPlane = (newConfig as any).controlPlane;
370 const useOnPremProxy =
371 controlPlane?.useContinueForTeamsProxy === false && controlPlane?.proxyUrl;
372
373 const env = await getControlPlaneEnv(ideSettingsPromise);
374 let controlPlaneProxyUrl: string = useOnPremProxy
375 ? controlPlane?.proxyUrl
376 : env.DEFAULT_CONTROL_PLANE_PROXY_URL;
377
378 if (!controlPlaneProxyUrl.endsWith("/")) {
379 controlPlaneProxyUrl += "/";
380 }
381 const controlPlaneProxyInfo = {
382 profileId,
383 controlPlaneProxyUrl,
384 workOsAccessToken,
385 };
386
387 if (newConfig.analytics) {
388 // FIXME before re-enabling TeamAnalytics.setup() populate workspaceId in
389 // controlPlaneProxyInfo to prevent /proxy/analytics/undefined/capture calls
390 // where undefined is :workspaceId
391 // await TeamAnalytics.setup(
392 // newConfig.analytics,
393 // uniqueId,
394 // ideInfo.extensionVersion,
395 // controlPlaneClient,
396 // controlPlaneProxyInfo,
397 // );
398 } else {
399 await TeamAnalytics.shutdown();
400 }
401
402 newConfig = await injectControlPlaneProxyInfo(
403 newConfig,
404 controlPlaneProxyInfo,
405 );
406
407 return { config: newConfig, errors, configLoadInterrupted: false };
408}
409
410// Pass ControlPlaneProxyInfo to objects that need it
411async function injectControlPlaneProxyInfo(
412 config: ContinueConfig,
413 info: ControlPlaneProxyInfo,
414): Promise<ContinueConfig> {
415 Object.keys(config.modelsByRole).forEach((key) => {
416 config.modelsByRole[key as ModelRole].forEach((model) => {
417 if (model.providerName === "continue-proxy") {
418 (model as ContinueProxy).controlPlaneProxyInfo = info;
419 }
420 });
421 });
422
423 Object.keys(config.selectedModelByRole).forEach((key) => {
424 const model = config.selectedModelByRole[key as ModelRole];
425 if (model?.providerName === "continue-proxy") {
426 (model as ContinueProxy).controlPlaneProxyInfo = info;
427 }
428 });
429
430 config.modelsByRole.chat.forEach((model) => {
431 if (model.providerName === "continue-proxy") {
432 (model as ContinueProxy).controlPlaneProxyInfo = info;
433 }
434 });
435
436 return config;
437}