Elffuss BraidHub

kikocis/continue public

dfc814e4318e · 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 ILLMLogger,
15 RuleWithSource,
16 SerializedContinueConfig,
17 SlashCommandDescWithSource,
18 Tool,
19} from "../../";
20import { stringifyMcpPrompt } from "../../commands/slash/mcpSlashCommand";
21import { MCPManagerSingleton } from "../../context/mcp/MCPManagerSingleton";
22import ContinueProxyContextProvider from "../../context/providers/ContinueProxyContextProvider";
23import MCPContextProvider from "../../context/providers/MCPContextProvider";
24import { ControlPlaneProxyInfo } from "../../control-plane/analytics/IAnalyticsProvider.js";
25import { ControlPlaneClient } from "../../control-plane/client.js";
26import { getControlPlaneEnv } from "../../control-plane/env.js";
27import { PolicySingleton } from "../../control-plane/PolicySingleton";
28import { TeamAnalytics } from "../../control-plane/TeamAnalytics.js";
29import ContinueProxy from "../../llm/llms/stubs/ContinueProxy";
30import { getConfigDependentToolDefinitions } from "../../tools";
31import { encodeMCPToolUri } from "../../tools/callTool";
32import { getMCPToolName } from "../../tools/mcpToolName";
33import { GlobalContext } from "../../util/GlobalContext";
34import { getConfigJsonPath, getConfigYamlPath } from "../../util/paths";
35import { localPathOrUriToPath } from "../../util/pathToUri";
36import { Telemetry } from "../../util/posthog";
37import { SentryLogger } from "../../util/sentry/SentryLogger";
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 // Add colocated rules from CodebaseRulesCache
64 const codebaseRulesCache = CodebaseRulesCache.getInstance();
65 rules.unshift(...codebaseRulesCache.rules);
66 errors.push(...codebaseRulesCache.errors);
67
68 return { rules, errors };
69}
70export default async function doLoadConfig(options: {
71 ide: IDE;
72 controlPlaneClient: ControlPlaneClient;
73 llmLogger: ILLMLogger;
74 overrideConfigJson?: SerializedContinueConfig;
75 overrideConfigYaml?: AssistantUnrolled;
76 profileId: string;
77 overrideConfigYamlByPath?: string;
78 orgScopeId: string | null;
79 packageIdentifier: PackageIdentifier;
80}): Promise<ConfigResult<ContinueConfig>> {
81 const {
82 ide,
83 controlPlaneClient,
84 llmLogger,
85 overrideConfigJson,
86 overrideConfigYaml,
87 profileId,
88 overrideConfigYamlByPath,
89 orgScopeId,
90 packageIdentifier,
91 } = options;
92
93 const ideInfo = await ide.getIdeInfo();
94 const uniqueId = await ide.getUniqueId();
95 const ideSettings = await ide.getIdeSettings();
96 const workOsAccessToken = await controlPlaneClient.getAccessToken();
97 const isSignedIn = await controlPlaneClient.isSignedIn();
98
99 // Migrations for old config files
100 // Removes
101 const configJsonPath = getConfigJsonPath();
102 if (fs.existsSync(configJsonPath)) {
103 migrateJsonSharedConfig(configJsonPath, ide);
104 }
105
106 const configYamlPath = localPathOrUriToPath(
107 overrideConfigYamlByPath || getConfigYamlPath(ideInfo.ideType),
108 );
109
110 let newConfig: ContinueConfig | undefined;
111 let errors: ConfigValidationError[] | undefined;
112 let configLoadInterrupted = false;
113
114 if (overrideConfigYaml || fs.existsSync(configYamlPath)) {
115 const result = await loadContinueConfigFromYaml({
116 ide,
117 ideSettings,
118 ideInfo,
119 uniqueId,
120 llmLogger,
121 overrideConfigYaml,
122 controlPlaneClient,
123 orgScopeId,
124 packageIdentifier,
125 workOsAccessToken,
126 });
127 newConfig = result.config;
128 errors = result.errors;
129 configLoadInterrupted = result.configLoadInterrupted;
130 } else {
131 const result = await loadContinueConfigFromJson(
132 ide,
133 ideSettings,
134 ideInfo,
135 uniqueId,
136 llmLogger,
137 workOsAccessToken,
138 overrideConfigJson,
139 );
140 newConfig = result.config;
141 errors = result.errors;
142 configLoadInterrupted = result.configLoadInterrupted;
143 }
144
145 if (configLoadInterrupted || !newConfig) {
146 return { errors, config: newConfig, configLoadInterrupted: true };
147 }
148
149 // TODO using config result but result with non-fatal errors is an antipattern?
150 // Remove ability have undefined errors, just have an array
151 errors = [...(errors ?? [])];
152
153 // Load rules and always include the RulesContextProvider
154 const { rules, errors: rulesErrors } = await loadRules(ide);
155 errors.push(...rulesErrors);
156 newConfig.rules.unshift(...rules);
157
158 const proxyContextProvider = newConfig.contextProviders?.find(
159 (cp) => cp.description.title === "continue-proxy",
160 );
161 if (proxyContextProvider) {
162 (proxyContextProvider as ContinueProxyContextProvider).workOsAccessToken =
163 workOsAccessToken;
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 // Rectify model selections for each role
184 newConfig = rectifySelectedModelsFromGlobalContext(newConfig, profileId);
185
186 // Add things from MCP servers
187 const mcpManager = MCPManagerSingleton.getInstance();
188 const mcpServerStatuses = mcpManager.getStatuses();
189
190 const serializableStatuses = mcpServerStatuses.map((server) => {
191 const { client, ...rest } = server;
192 return rest;
193 });
194 newConfig.mcpServerStatuses = serializableStatuses;
195
196 for (const server of mcpServerStatuses) {
197 if (server.status === "connected") {
198 const serverTools: Tool[] = server.tools.map((tool) => ({
199 displayTitle: server.name + " " + tool.name,
200 function: {
201 description: tool.description,
202 name: getMCPToolName(server, tool),
203 parameters: tool.inputSchema,
204 },
205 faviconUrl: server.faviconUrl,
206 readonly: false,
207 type: "function" as const,
208 uri: encodeMCPToolUri(server.id, tool.name),
209 group: server.name,
210 originalFunctionName: tool.name,
211 }));
212 newConfig.tools.push(...serverTools);
213
214 // Fetch MCP prompt content during config load
215 const serverSlashCommands: SlashCommandDescWithSource[] =
216 await Promise.all(
217 server.prompts.map(async (prompt) => {
218 let promptContent: string | undefined;
219
220 try {
221 // Fetch the actual prompt content from the MCP server
222 const mcpPromptResponse = await mcpManager.getPrompt(
223 server.name,
224 prompt.name,
225 {}, // Empty args for now - TODO: handle prompt arguments
226 );
227 promptContent = stringifyMcpPrompt(mcpPromptResponse);
228 } catch (error) {
229 console.warn(
230 `Failed to fetch MCP prompt content for ${prompt.name} from server ${server.name}:`,
231 error,
232 );
233 // Keep promptContent as undefined so the UI can show a fallback
234 }
235
236 return {
237 name: prompt.name,
238 description: prompt.description ?? "MCP Prompt",
239 source: "mcp-prompt",
240 isLegacy: false,
241 prompt: promptContent, // Store the actual prompt content
242 mcpServerName: server.name, // Used in client to retrieve prompt
243 mcpArgs: prompt.arguments,
244 };
245 }),
246 );
247 newConfig.slashCommands.push(...serverSlashCommands);
248
249 const submenuItems = server.resources
250 .map((resource) => ({
251 title: resource.name,
252 description: resource.description ?? resource.name,
253 id: resource.uri,
254 icon: server.faviconUrl,
255 }))
256 .concat(
257 server.resourceTemplates.map((template) => ({
258 title: template.name,
259 description: template.description ?? template.name,
260 id: template.uriTemplate,
261 icon: server.faviconUrl,
262 })),
263 );
264 if (submenuItems.length > 0) {
265 const serverContextProvider = new MCPContextProvider({
266 submenuItems,
267 mcpId: server.id,
268 serverName: server.name,
269 });
270 newConfig.contextProviders.push(serverContextProvider);
271 }
272 }
273 }
274
275 newConfig.tools.push(
276 ...getConfigDependentToolDefinitions({
277 rules: newConfig.rules,
278 enableExperimentalTools:
279 newConfig.experimental?.enableExperimentalTools ?? false,
280 isSignedIn,
281 isRemote: await ide.isWorkspaceRemote(),
282 modelName: newConfig.selectedModelByRole.chat?.model,
283 }),
284 );
285
286 // Detect duplicate tool names
287 const counts: Record<string, number> = {};
288 newConfig.tools.forEach((tool) => {
289 if (counts[tool.function.name]) {
290 counts[tool.function.name] = counts[tool.function.name] + 1;
291 } else {
292 counts[tool.function.name] = 1;
293 }
294 });
295
296 Object.entries(counts).forEach(([toolName, count]) => {
297 if (count > 1) {
298 errors!.push({
299 fatal: false,
300 message: `Duplicate (${count}) tools named "${toolName}" detected. Permissions will conflict and usage may be unpredictable`,
301 });
302 }
303 });
304
305 const ruleCounts: Record<string, number> = {};
306 newConfig.rules.forEach((rule) => {
307 if (rule.name) {
308 if (ruleCounts[rule.name]) {
309 ruleCounts[rule.name] = ruleCounts[rule.name] + 1;
310 } else {
311 ruleCounts[rule.name] = 1;
312 }
313 }
314 });
315
316 Object.entries(ruleCounts).forEach(([ruleName, count]) => {
317 if (count > 1) {
318 errors!.push({
319 fatal: false,
320 message: `Duplicate (${count}) rules named "${ruleName}" detected. This may cause unexpected behavior`,
321 });
322 }
323 });
324
325 if (newConfig.allowAnonymousTelemetry !== false) {
326 if ((await ide.isTelemetryEnabled()) === false) {
327 newConfig.allowAnonymousTelemetry = false;
328 }
329 }
330
331 // Org policies
332 const policy = PolicySingleton.getInstance().policy?.policy;
333 if (policy?.allowAnonymousTelemetry === false) {
334 newConfig.allowAnonymousTelemetry = false;
335 }
336 if (policy?.allowCodebaseIndexing === false) {
337 newConfig.disableIndexing = true;
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(Promise.resolve(ideSettings));
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}