Elffuss BraidHub

kikocis/continue public

6d66081d22d3 · 12.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 ContinueRcJson,
14 IDE,
15 IdeSettings,
16 ILLMLogger,
17 RuleWithSource,
18 SerializedContinueConfig,
19 SlashCommandDescWithSource,
20 Tool,
21} from "../../";
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 { 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 { getConfigJsonPath, getConfigYamlPath } from "../../util/paths";
35import { localPathOrUriToPath } from "../../util/pathToUri";
36import { Telemetry } from "../../util/posthog";
37import { TTS } from "../../util/tts";
38import { getWorkspaceContinueRuleDotFiles } from "../getWorkspaceContinueRuleDotFiles";
39import { loadContinueConfigFromJson } from "../load";
40import { loadCodebaseRules } from "../markdown/loadCodebaseRules";
41import { loadMarkdownRules } from "../markdown/loadMarkdownRules";
42import { migrateJsonSharedConfig } from "../migrateSharedConfig";
43import { rectifySelectedModelsFromGlobalContext } from "../selectedModels";
44import { loadContinueConfigFromYaml } from "../yaml/loadYaml";
45
46async function loadRules(ide: IDE) {
47 const rules: RuleWithSource[] = [];
48 const errors = [];
49
50 // Add rules from .continuerules files
51 const { rules: yamlRules, errors: continueRulesErrors } =
52 await getWorkspaceContinueRuleDotFiles(ide);
53 rules.unshift(...yamlRules);
54 errors.push(...continueRulesErrors);
55
56 // Add rules from markdown files in .continue/rules
57 const { rules: markdownRules, errors: markdownRulesErrors } =
58 await loadMarkdownRules(ide);
59 rules.unshift(...markdownRules);
60 errors.push(...markdownRulesErrors);
61
62 return { rules, errors };
63}
64export default async function doLoadConfig(options: {
65 ide: IDE;
66 ideSettingsPromise: Promise<IdeSettings>;
67 controlPlaneClient: ControlPlaneClient;
68 llmLogger: ILLMLogger;
69 overrideConfigJson?: SerializedContinueConfig;
70 overrideConfigYaml?: AssistantUnrolled;
71 profileId: string;
72 overrideConfigYamlByPath?: string;
73 orgScopeId: string | null;
74 packageIdentifier: PackageIdentifier;
75}): Promise<ConfigResult<ContinueConfig>> {
76 const {
77 ide,
78 ideSettingsPromise,
79 controlPlaneClient,
80 llmLogger,
81 overrideConfigJson,
82 overrideConfigYaml,
83 profileId,
84 overrideConfigYamlByPath,
85 orgScopeId,
86 packageIdentifier,
87 } = options;
88
89 const workspaceConfigs = await getWorkspaceConfigs(ide);
90 const ideInfo = await ide.getIdeInfo();
91 const uniqueId = await ide.getUniqueId();
92 const ideSettings = await ideSettingsPromise;
93 const workOsAccessToken = await controlPlaneClient.getAccessToken();
94
95 // Migrations for old config files
96 // Removes
97 const configJsonPath = getConfigJsonPath();
98 if (fs.existsSync(configJsonPath)) {
99 migrateJsonSharedConfig(configJsonPath, ide);
100 }
101
102 const configYamlPath = localPathOrUriToPath(
103 overrideConfigYamlByPath || getConfigYamlPath(ideInfo.ideType),
104 );
105
106 let newConfig: ContinueConfig | undefined;
107 let errors: ConfigValidationError[] | undefined;
108 let configLoadInterrupted = false;
109
110 if (overrideConfigYaml || fs.existsSync(configYamlPath)) {
111 const result = await loadContinueConfigFromYaml({
112 ide,
113 ideSettings,
114 ideInfo,
115 uniqueId,
116 llmLogger,
117 overrideConfigYaml,
118 controlPlaneClient,
119 orgScopeId,
120 packageIdentifier,
121 workOsAccessToken,
122 });
123 newConfig = result.config;
124 errors = result.errors;
125 configLoadInterrupted = result.configLoadInterrupted;
126 } else {
127 const result = await loadContinueConfigFromJson(
128 ide,
129 workspaceConfigs,
130 ideSettings,
131 ideInfo,
132 uniqueId,
133 llmLogger,
134 workOsAccessToken,
135 overrideConfigJson,
136 );
137 newConfig = result.config;
138 errors = result.errors;
139 configLoadInterrupted = result.configLoadInterrupted;
140 }
141
142 if (configLoadInterrupted || !newConfig) {
143 return { errors, config: newConfig, configLoadInterrupted: true };
144 }
145
146 // TODO using config result but result with non-fatal errors is an antipattern?
147 // Remove ability have undefined errors, just have an array
148 errors = [...(errors ?? [])];
149
150 // Load rules and always include the RulesContextProvider
151 const { rules, errors: rulesErrors } = await loadRules(ide);
152 errors.push(...rulesErrors);
153 newConfig.rules.unshift(...rules);
154 newConfig.contextProviders.push(new RulesContextProvider({}));
155
156 // Add current file as context if setting is enabled
157 if (
158 newConfig.experimental?.useCurrentFileAsContext === true &&
159 !newConfig.contextProviders.find(
160 (c) =>
161 c.description.title === CurrentFileContextProvider.description.title,
162 )
163 ) {
164 newConfig.contextProviders.push(new CurrentFileContextProvider({}));
165 }
166
167 // Add rules from colocated rules.md files in the codebase
168 const { rules: codebaseRules, errors: codebaseRulesErrors } =
169 await loadCodebaseRules(ide);
170 newConfig.rules.unshift(...codebaseRules);
171 errors.push(...codebaseRulesErrors);
172
173 // Rectify model selections for each role
174 newConfig = rectifySelectedModelsFromGlobalContext(newConfig, profileId);
175
176 // Add things from MCP servers
177 const mcpManager = MCPManagerSingleton.getInstance();
178 const mcpServerStatuses = mcpManager.getStatuses();
179
180 // Slightly hacky just need connection's client to make slash command for now
181 const serializableStatuses = mcpServerStatuses.map((server) => {
182 const { client, ...rest } = server;
183 return rest;
184 });
185 newConfig.mcpServerStatuses = serializableStatuses;
186
187 for (const server of mcpServerStatuses) {
188 if (server.status === "connected") {
189 const serverTools: Tool[] = server.tools.map((tool) => ({
190 displayTitle: server.name + " " + tool.name,
191 function: {
192 description: tool.description,
193 name: getMCPToolName(server, tool),
194 parameters: tool.inputSchema,
195 },
196 faviconUrl: server.faviconUrl,
197 readonly: false,
198 type: "function" as const,
199 uri: encodeMCPToolUri(server.id, tool.name),
200 group: server.name,
201 originalFunctionName: tool.name,
202 }));
203 newConfig.tools.push(...serverTools);
204
205 const serverSlashCommands: SlashCommandDescWithSource[] =
206 server.prompts.map((prompt) => ({
207 name: prompt.name,
208 description: prompt.description ?? "MCP Prompt",
209 source: "mcp-prompt",
210 isLegacy: false,
211 mcpServerName: server.name, // Used in client to retrieve prompt
212 mcpArgs: prompt.arguments,
213 }));
214 newConfig.slashCommands.push(...serverSlashCommands);
215
216 const submenuItems = server.resources
217 .map((resource) => ({
218 title: resource.name,
219 description: resource.description ?? resource.name,
220 id: resource.uri,
221 icon: server.faviconUrl,
222 }))
223 .concat(
224 server.resourceTemplates.map((template) => ({
225 title: template.name,
226 description: template.description ?? template.name,
227 id: template.uriTemplate,
228 icon: server.faviconUrl,
229 })),
230 );
231 if (submenuItems.length > 0) {
232 const serverContextProvider = new MCPContextProvider({
233 submenuItems,
234 mcpId: server.id,
235 serverName: server.name,
236 });
237 newConfig.contextProviders.push(serverContextProvider);
238 }
239 }
240 }
241
242 newConfig.tools.push(
243 ...getConfigDependentToolDefinitions({
244 rules: newConfig.rules,
245 enableExperimentalTools:
246 newConfig.experimental?.enableExperimentalTools ?? false,
247 }),
248 );
249
250 // Detect duplicate tool names
251 const counts: Record<string, number> = {};
252 newConfig.tools.forEach((tool) => {
253 if (counts[tool.function.name]) {
254 counts[tool.function.name] = counts[tool.function.name] + 1;
255 } else {
256 counts[tool.function.name] = 1;
257 }
258 });
259
260 Object.entries(counts).forEach(([toolName, count]) => {
261 if (count > 1) {
262 errors!.push({
263 fatal: false,
264 message: `Duplicate (${count}) tools named "${toolName}" detected. Permissions will conflict and usage may be unpredictable`,
265 });
266 }
267 });
268
269 const ruleCounts: Record<string, number> = {};
270 newConfig.rules.forEach((rule) => {
271 if (rule.name) {
272 if (ruleCounts[rule.name]) {
273 ruleCounts[rule.name] = ruleCounts[rule.name] + 1;
274 } else {
275 ruleCounts[rule.name] = 1;
276 }
277 }
278 });
279
280 Object.entries(ruleCounts).forEach(([ruleName, count]) => {
281 if (count > 1) {
282 errors!.push({
283 fatal: false,
284 message: `Duplicate (${count}) rules named "${ruleName}" detected. This may cause unexpected behavior`,
285 });
286 }
287 });
288
289 newConfig.allowAnonymousTelemetry =
290 newConfig.allowAnonymousTelemetry && (await ide.isTelemetryEnabled());
291
292 // Setup telemetry only after (and if) we know it is enabled
293 await Telemetry.setup(
294 newConfig.allowAnonymousTelemetry ?? true,
295 await ide.getUniqueId(),
296 ideInfo,
297 );
298
299 // TODO: pass config to pre-load non-system TTS models
300 await TTS.setup();
301
302 // Set up control plane proxy if configured
303 const controlPlane = (newConfig as any).controlPlane;
304 const useOnPremProxy =
305 controlPlane?.useContinueForTeamsProxy === false && controlPlane?.proxyUrl;
306
307 const env = await getControlPlaneEnv(ideSettingsPromise);
308 let controlPlaneProxyUrl: string = useOnPremProxy
309 ? controlPlane?.proxyUrl
310 : env.DEFAULT_CONTROL_PLANE_PROXY_URL;
311
312 if (!controlPlaneProxyUrl.endsWith("/")) {
313 controlPlaneProxyUrl += "/";
314 }
315 const controlPlaneProxyInfo = {
316 profileId,
317 controlPlaneProxyUrl,
318 workOsAccessToken,
319 };
320
321 if (newConfig.analytics) {
322 // await TeamAnalytics.setup(
323 // newConfig.analytics,
324 // uniqueId,
325 // ideInfo.extensionVersion,
326 // controlPlaneClient,
327 // controlPlaneProxyInfo,
328 // );
329 } else {
330 await TeamAnalytics.shutdown();
331 }
332
333 newConfig = await injectControlPlaneProxyInfo(
334 newConfig,
335 controlPlaneProxyInfo,
336 );
337
338 return { config: newConfig, errors, configLoadInterrupted: false };
339}
340
341// Pass ControlPlaneProxyInfo to objects that need it
342async function injectControlPlaneProxyInfo(
343 config: ContinueConfig,
344 info: ControlPlaneProxyInfo,
345): Promise<ContinueConfig> {
346 Object.keys(config.modelsByRole).forEach((key) => {
347 config.modelsByRole[key as ModelRole].forEach((model) => {
348 if (model.providerName === "continue-proxy") {
349 (model as ContinueProxy).controlPlaneProxyInfo = info;
350 }
351 });
352 });
353
354 Object.keys(config.selectedModelByRole).forEach((key) => {
355 const model = config.selectedModelByRole[key as ModelRole];
356 if (model?.providerName === "continue-proxy") {
357 (model as ContinueProxy).controlPlaneProxyInfo = info;
358 }
359 });
360
361 config.modelsByRole.chat.forEach((model) => {
362 if (model.providerName === "continue-proxy") {
363 (model as ContinueProxy).controlPlaneProxyInfo = info;
364 }
365 });
366
367 return config;
368}
369
370async function getWorkspaceConfigs(ide: IDE): Promise<ContinueRcJson[]> {
371 const ideInfo = await ide.getIdeInfo();
372 let workspaceConfigs: ContinueRcJson[] = [];
373
374 try {
375 workspaceConfigs = await ide.getWorkspaceConfigs();
376
377 // Config is sent over the wire from JB so we need to parse it
378 if (ideInfo.ideType === "jetbrains") {
379 workspaceConfigs = (workspaceConfigs as any).map(JSON.parse);
380 }
381 } catch (e) {
382 console.debug("Failed to load workspace configs: ", e);
383 }
384
385 return workspaceConfigs;
386}