Elffuss BraidHub

kikocis/continue public

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