Elffuss BraidHub

kikocis/continue public

825624809c09 · 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 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 isRemote: await ide.isWorkspaceRemote(),
286 modelName: newConfig.selectedModelByRole.chat?.model,
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 // Org policies
336 const policy = PolicySingleton.getInstance().policy?.policy;
337 if (policy?.allowAnonymousTelemetry === false) {
338 newConfig.allowAnonymousTelemetry = false;
339 }
340 if (policy?.allowCodebaseIndexing === false) {
341 newConfig.disableIndexing = true;
342 }
343
344 // Setup telemetry only after (and if) we know it is enabled
345 await Telemetry.setup(
346 newConfig.allowAnonymousTelemetry ?? true,
347 await ide.getUniqueId(),
348 ideInfo,
349 );
350
351 // Setup Sentry logger with same telemetry settings
352 // TODO: Remove Continue team member check once Sentry is ready for all users
353 let userEmail: string | undefined;
354 try {
355 // Access the session info to get user email for Continue team member check
356 const sessionInfo = await (controlPlaneClient as any).sessionInfoPromise;
357 userEmail = sessionInfo?.account?.id;
358 } catch (error) {
359 // Ignore errors getting session info, will default to no Sentry
360 }
361
362 await SentryLogger.setup(
363 newConfig.allowAnonymousTelemetry ?? false,
364 await ide.getUniqueId(),
365 ideInfo,
366 userEmail,
367 );
368
369 // TODO: pass config to pre-load non-system TTS models
370 await TTS.setup();
371
372 // Set up control plane proxy if configured
373 const controlPlane = (newConfig as any).controlPlane;
374 const useOnPremProxy =
375 controlPlane?.useContinueForTeamsProxy === false && controlPlane?.proxyUrl;
376
377 const env = await getControlPlaneEnv(ideSettingsPromise);
378 let controlPlaneProxyUrl: string = useOnPremProxy
379 ? controlPlane?.proxyUrl
380 : env.DEFAULT_CONTROL_PLANE_PROXY_URL;
381
382 if (!controlPlaneProxyUrl.endsWith("/")) {
383 controlPlaneProxyUrl += "/";
384 }
385 const controlPlaneProxyInfo = {
386 profileId,
387 controlPlaneProxyUrl,
388 workOsAccessToken,
389 };
390
391 if (newConfig.analytics) {
392 // FIXME before re-enabling TeamAnalytics.setup() populate workspaceId in
393 // controlPlaneProxyInfo to prevent /proxy/analytics/undefined/capture calls
394 // where undefined is :workspaceId
395 // await TeamAnalytics.setup(
396 // newConfig.analytics,
397 // uniqueId,
398 // ideInfo.extensionVersion,
399 // controlPlaneClient,
400 // controlPlaneProxyInfo,
401 // );
402 } else {
403 await TeamAnalytics.shutdown();
404 }
405
406 newConfig = await injectControlPlaneProxyInfo(
407 newConfig,
408 controlPlaneProxyInfo,
409 );
410
411 return { config: newConfig, errors, configLoadInterrupted: false };
412}
413
414// Pass ControlPlaneProxyInfo to objects that need it
415async function injectControlPlaneProxyInfo(
416 config: ContinueConfig,
417 info: ControlPlaneProxyInfo,
418): Promise<ContinueConfig> {
419 Object.keys(config.modelsByRole).forEach((key) => {
420 config.modelsByRole[key as ModelRole].forEach((model) => {
421 if (model.providerName === "continue-proxy") {
422 (model as ContinueProxy).controlPlaneProxyInfo = info;
423 }
424 });
425 });
426
427 Object.keys(config.selectedModelByRole).forEach((key) => {
428 const model = config.selectedModelByRole[key as ModelRole];
429 if (model?.providerName === "continue-proxy") {
430 (model as ContinueProxy).controlPlaneProxyInfo = info;
431 }
432 });
433
434 config.modelsByRole.chat.forEach((model) => {
435 if (model.providerName === "continue-proxy") {
436 (model as ContinueProxy).controlPlaneProxyInfo = info;
437 }
438 });
439
440 return config;
441}