Elffuss BraidHub

kikocis/continue public

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