Elffuss BraidHub

kikocis/continue public

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