Elffuss BraidHub

kikocis/continue public

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