Elffuss BraidHub

kikocis/continue public

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