Elffuss BraidHub

kikocis/continue public

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