Elffuss BraidHub

kikocis/continue public

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