Elffuss BraidHub

kikocis/continue public

627d7d0d1f85 · 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 { CodebaseRulesCache } 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 codebaseRulesCache = CodebaseRulesCache.getInstance();
169 newConfig.rules.unshift(...codebaseRulesCache.rules);
170 errors.push(...codebaseRulesCache.errors);
171
172 // Rectify model selections for each role
173 newConfig = rectifySelectedModelsFromGlobalContext(newConfig, profileId);
174
175 // Add things from MCP servers
176 const mcpManager = MCPManagerSingleton.getInstance();
177 const mcpServerStatuses = mcpManager.getStatuses();
178
179 // Slightly hacky just need connection's client to make slash command for now
180 const serializableStatuses = mcpServerStatuses.map((server) => {
181 const { client, ...rest } = server;
182 return rest;
183 });
184 newConfig.mcpServerStatuses = serializableStatuses;
185
186 for (const server of mcpServerStatuses) {
187 if (server.status === "connected") {
188 const serverTools: Tool[] = server.tools.map((tool) => ({
189 displayTitle: server.name + " " + tool.name,
190 function: {
191 description: tool.description,
192 name: getMCPToolName(server, tool),
193 parameters: tool.inputSchema,
194 },
195 faviconUrl: server.faviconUrl,
196 readonly: false,
197 type: "function" as const,
198 uri: encodeMCPToolUri(server.id, tool.name),
199 group: server.name,
200 originalFunctionName: tool.name,
201 }));
202 newConfig.tools.push(...serverTools);
203
204 const serverSlashCommands: SlashCommandDescWithSource[] =
205 server.prompts.map((prompt) => ({
206 name: prompt.name,
207 description: prompt.description ?? "MCP Prompt",
208 source: "mcp-prompt",
209 isLegacy: false,
210 mcpServerName: server.name, // Used in client to retrieve prompt
211 mcpArgs: prompt.arguments,
212 }));
213 newConfig.slashCommands.push(...serverSlashCommands);
214
215 const submenuItems = server.resources
216 .map((resource) => ({
217 title: resource.name,
218 description: resource.description ?? resource.name,
219 id: resource.uri,
220 icon: server.faviconUrl,
221 }))
222 .concat(
223 server.resourceTemplates.map((template) => ({
224 title: template.name,
225 description: template.description ?? template.name,
226 id: template.uriTemplate,
227 icon: server.faviconUrl,
228 })),
229 );
230 if (submenuItems.length > 0) {
231 const serverContextProvider = new MCPContextProvider({
232 submenuItems,
233 mcpId: server.id,
234 serverName: server.name,
235 });
236 newConfig.contextProviders.push(serverContextProvider);
237 }
238 }
239 }
240
241 newConfig.tools.push(
242 ...getConfigDependentToolDefinitions({
243 rules: newConfig.rules,
244 enableExperimentalTools:
245 newConfig.experimental?.enableExperimentalTools ?? false,
246 }),
247 );
248
249 // Detect duplicate tool names
250 const counts: Record<string, number> = {};
251 newConfig.tools.forEach((tool) => {
252 if (counts[tool.function.name]) {
253 counts[tool.function.name] = counts[tool.function.name] + 1;
254 } else {
255 counts[tool.function.name] = 1;
256 }
257 });
258
259 Object.entries(counts).forEach(([toolName, count]) => {
260 if (count > 1) {
261 errors!.push({
262 fatal: false,
263 message: `Duplicate (${count}) tools named "${toolName}" detected. Permissions will conflict and usage may be unpredictable`,
264 });
265 }
266 });
267
268 const ruleCounts: Record<string, number> = {};
269 newConfig.rules.forEach((rule) => {
270 if (rule.name) {
271 if (ruleCounts[rule.name]) {
272 ruleCounts[rule.name] = ruleCounts[rule.name] + 1;
273 } else {
274 ruleCounts[rule.name] = 1;
275 }
276 }
277 });
278
279 Object.entries(ruleCounts).forEach(([ruleName, count]) => {
280 if (count > 1) {
281 errors!.push({
282 fatal: false,
283 message: `Duplicate (${count}) rules named "${ruleName}" detected. This may cause unexpected behavior`,
284 });
285 }
286 });
287
288 newConfig.allowAnonymousTelemetry =
289 newConfig.allowAnonymousTelemetry && (await ide.isTelemetryEnabled());
290
291 // Setup telemetry only after (and if) we know it is enabled
292 await Telemetry.setup(
293 newConfig.allowAnonymousTelemetry ?? true,
294 await ide.getUniqueId(),
295 ideInfo,
296 );
297
298 // TODO: pass config to pre-load non-system TTS models
299 await TTS.setup();
300
301 // Set up control plane proxy if configured
302 const controlPlane = (newConfig as any).controlPlane;
303 const useOnPremProxy =
304 controlPlane?.useContinueForTeamsProxy === false && controlPlane?.proxyUrl;
305
306 const env = await getControlPlaneEnv(ideSettingsPromise);
307 let controlPlaneProxyUrl: string = useOnPremProxy
308 ? controlPlane?.proxyUrl
309 : env.DEFAULT_CONTROL_PLANE_PROXY_URL;
310
311 if (!controlPlaneProxyUrl.endsWith("/")) {
312 controlPlaneProxyUrl += "/";
313 }
314 const controlPlaneProxyInfo = {
315 profileId,
316 controlPlaneProxyUrl,
317 workOsAccessToken,
318 };
319
320 if (newConfig.analytics) {
321 // await TeamAnalytics.setup(
322 // newConfig.analytics,
323 // uniqueId,
324 // ideInfo.extensionVersion,
325 // controlPlaneClient,
326 // controlPlaneProxyInfo,
327 // );
328 } else {
329 await TeamAnalytics.shutdown();
330 }
331
332 newConfig = await injectControlPlaneProxyInfo(
333 newConfig,
334 controlPlaneProxyInfo,
335 );
336
337 return { config: newConfig, errors, configLoadInterrupted: false };
338}
339
340// Pass ControlPlaneProxyInfo to objects that need it
341async function injectControlPlaneProxyInfo(
342 config: ContinueConfig,
343 info: ControlPlaneProxyInfo,
344): Promise<ContinueConfig> {
345 Object.keys(config.modelsByRole).forEach((key) => {
346 config.modelsByRole[key as ModelRole].forEach((model) => {
347 if (model.providerName === "continue-proxy") {
348 (model as ContinueProxy).controlPlaneProxyInfo = info;
349 }
350 });
351 });
352
353 Object.keys(config.selectedModelByRole).forEach((key) => {
354 const model = config.selectedModelByRole[key as ModelRole];
355 if (model?.providerName === "continue-proxy") {
356 (model as ContinueProxy).controlPlaneProxyInfo = info;
357 }
358 });
359
360 config.modelsByRole.chat.forEach((model) => {
361 if (model.providerName === "continue-proxy") {
362 (model as ContinueProxy).controlPlaneProxyInfo = info;
363 }
364 });
365
366 return config;
367}
368
369async function getWorkspaceConfigs(ide: IDE): Promise<ContinueRcJson[]> {
370 const ideInfo = await ide.getIdeInfo();
371 let workspaceConfigs: ContinueRcJson[] = [];
372
373 try {
374 workspaceConfigs = await ide.getWorkspaceConfigs();
375
376 // Config is sent over the wire from JB so we need to parse it
377 if (ideInfo.ideType === "jetbrains") {
378 workspaceConfigs = (workspaceConfigs as any).map(JSON.parse);
379 }
380 } catch (e) {
381 console.debug("Failed to load workspace configs: ", e);
382 }
383
384 return workspaceConfigs;
385}