Elffuss BraidHub

kikocis/continue public

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