Elffuss BraidHub

kikocis/continue public

2d2c10bf01a5 · 14.7 KiBRawPermalink
1import { ConfigResult } from "@continuedev/config-yaml";
2
3import {
4 ControlPlaneClient,
5 ControlPlaneSessionInfo,
6} from "../control-plane/client.js";
7import { getControlPlaneEnv } from "../control-plane/env.js";
8import {
9 BrowserSerializedContinueConfig,
10 ContinueConfig,
11 IContextProvider,
12 IDE,
13 IdeSettings,
14 ILLMLogger,
15} from "../index.js";
16import { GlobalContext } from "../util/GlobalContext.js";
17
18import { logger } from "../util/logger.js";
19import {
20 ASSISTANTS,
21 getAllDotContinueYamlFiles,
22 LoadAssistantFilesOptions,
23} from "./loadLocalAssistants.js";
24import LocalProfileLoader from "./profile/LocalProfileLoader.js";
25import PlatformProfileLoader from "./profile/PlatformProfileLoader.js";
26import {
27 OrganizationDescription,
28 OrgWithProfiles,
29 ProfileDescription,
30 ProfileLifecycleManager,
31 SerializedOrgWithProfiles,
32} from "./ProfileLifecycleManager.js";
33
34export type { ProfileDescription };
35
36type ConfigUpdateFunction = (payload: ConfigResult<ContinueConfig>) => void;
37
38export class ConfigHandler {
39 controlPlaneClient: ControlPlaneClient;
40 private readonly globalContext = new GlobalContext();
41 private globalLocalProfileManager: ProfileLifecycleManager;
42
43 private organizations: OrgWithProfiles[] = [];
44 currentProfile: ProfileLifecycleManager | null;
45 currentOrg: OrgWithProfiles;
46
47 constructor(
48 private readonly ide: IDE,
49 private ideSettingsPromise: Promise<IdeSettings>,
50 private llmLogger: ILLMLogger,
51 sessionInfoPromise: Promise<ControlPlaneSessionInfo | undefined>,
52 ) {
53 this.ide = ide;
54 this.ideSettingsPromise = ideSettingsPromise;
55 this.controlPlaneClient = new ControlPlaneClient(
56 sessionInfoPromise,
57 ideSettingsPromise,
58 );
59
60 // This profile manager will always be available
61 this.globalLocalProfileManager = new ProfileLifecycleManager(
62 new LocalProfileLoader(
63 ide,
64 ideSettingsPromise,
65 this.controlPlaneClient,
66 this.llmLogger,
67 ),
68 this.ide,
69 );
70
71 // Just to be safe, always force a default personal org with local profile manager
72 this.currentProfile = this.globalLocalProfileManager;
73 const personalOrg: OrgWithProfiles = {
74 currentProfile: this.globalLocalProfileManager,
75 profiles: [this.globalLocalProfileManager],
76 ...this.PERSONAL_ORG_DESC,
77 };
78
79 this.currentOrg = personalOrg;
80 this.organizations = [personalOrg];
81
82 void this.cascadeInit();
83 }
84
85 private workspaceDirs: string[] | null = null;
86 async getWorkspaceId() {
87 if (!this.workspaceDirs) {
88 this.workspaceDirs = await this.ide.getWorkspaceDirs();
89 }
90 return this.workspaceDirs.join("&");
91 }
92
93 async getProfileKey(orgId: string) {
94 const workspaceId = await this.getWorkspaceId();
95 return `${workspaceId}:::${orgId}`;
96 }
97
98 private async cascadeInit() {
99 this.workspaceDirs = null; // forces workspace dirs reload
100
101 const orgs = await this.getOrgs();
102
103 // Figure out selected org
104 const workspaceId = await this.getWorkspaceId();
105 const selectedOrgs =
106 this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {};
107 const currentSelection = selectedOrgs[workspaceId];
108
109 const firstNonPersonal = orgs.find(
110 (org) => org.id !== this.PERSONAL_ORG_DESC.id,
111 );
112 const fallback = firstNonPersonal ?? orgs[0];
113 // note, ignoring case of zero orgs since should never happen
114
115 let selectedOrg: OrgWithProfiles;
116 if (!currentSelection) {
117 selectedOrg = fallback;
118 } else {
119 const match = orgs.find((org) => org.id === currentSelection);
120 if (match) {
121 selectedOrg = match;
122 } else {
123 selectedOrg = fallback;
124 }
125 }
126
127 this.globalContext.update("lastSelectedOrgIdForWorkspace", {
128 ...selectedOrgs,
129 [workspaceId]: selectedOrg.id,
130 });
131
132 this.organizations = orgs;
133 this.currentOrg = selectedOrg;
134 this.currentProfile = selectedOrg.currentProfile;
135 await this.reloadConfig();
136 }
137
138 private async getOrgs(): Promise<OrgWithProfiles[]> {
139 const userId = await this.controlPlaneClient.userId;
140 if (userId) {
141 const orgDescs = await this.controlPlaneClient.listOrganizations();
142 const personalHubOrg = await this.getPersonalHubOrg();
143 const hubOrgs = await Promise.all(
144 orgDescs.map((org) => this.getNonPersonalHubOrg(org)),
145 );
146 return [...hubOrgs, personalHubOrg];
147 } else {
148 return [await this.getLocalOrg()];
149 }
150 }
151
152 getSerializedOrgs(): SerializedOrgWithProfiles[] {
153 return this.organizations.map((org) => ({
154 iconUrl: org.iconUrl,
155 id: org.id,
156 name: org.name,
157 slug: org.slug,
158 profiles: org.profiles.map((profile) => profile.profileDescription),
159 selectedProfileId: org.currentProfile?.profileDescription.id || null,
160 }));
161 }
162
163 private async getHubProfiles(orgScopeId: string | null) {
164 const assistants = await this.controlPlaneClient.listAssistants(orgScopeId);
165
166 return await Promise.all(
167 assistants.map(async (assistant) => {
168 const profileLoader = await PlatformProfileLoader.create({
169 configResult: {
170 ...assistant.configResult,
171 config: assistant.configResult.config,
172 },
173 ownerSlug: assistant.ownerSlug,
174 packageSlug: assistant.packageSlug,
175 iconUrl: assistant.iconUrl,
176 versionSlug: assistant.configResult.config?.version ?? "latest",
177 controlPlaneClient: this.controlPlaneClient,
178 ide: this.ide,
179 ideSettingsPromise: this.ideSettingsPromise,
180 llmLogger: this.llmLogger,
181 rawYaml: assistant.rawYaml,
182 orgScopeId: orgScopeId,
183 });
184
185 return new ProfileLifecycleManager(profileLoader, this.ide);
186 }),
187 );
188 }
189
190 private async getNonPersonalHubOrg(
191 org: OrganizationDescription,
192 ): Promise<OrgWithProfiles> {
193 const localProfiles = await this.getLocalProfiles({
194 includeGlobal: false,
195 includeWorkspace: true,
196 });
197 const profiles = [...(await this.getHubProfiles(org.id)), ...localProfiles];
198 return this.rectifyProfilesForOrg(org, profiles);
199 }
200
201 private PERSONAL_ORG_DESC: OrganizationDescription = {
202 iconUrl: "",
203 id: "personal",
204 name: "Personal",
205 slug: undefined,
206 };
207 private async getPersonalHubOrg() {
208 const localProfiles = await this.getLocalProfiles({
209 includeGlobal: true,
210 includeWorkspace: true,
211 });
212 const hubProfiles = await this.getHubProfiles(null);
213 const profiles = [...hubProfiles, ...localProfiles];
214 return this.rectifyProfilesForOrg(this.PERSONAL_ORG_DESC, profiles);
215 }
216
217 private async getLocalOrg() {
218 const localProfiles = await this.getLocalProfiles({
219 includeGlobal: true,
220 includeWorkspace: true,
221 });
222 return this.rectifyProfilesForOrg(this.PERSONAL_ORG_DESC, localProfiles);
223 }
224
225 private async rectifyProfilesForOrg(
226 org: OrganizationDescription,
227 profiles: ProfileLifecycleManager[],
228 ): Promise<OrgWithProfiles> {
229 const profileKey = await this.getProfileKey(org.id);
230 const selectedProfiles =
231 this.globalContext.get("lastSelectedProfileForWorkspace") ?? {};
232
233 const currentSelection = selectedProfiles[profileKey];
234
235 const firstNonLocal = profiles.find(
236 (profile) => profile.profileDescription.profileType !== "local",
237 );
238 const fallback =
239 firstNonLocal ?? (profiles.length > 0 ? profiles[0] : null);
240
241 let currentProfile: ProfileLifecycleManager | null;
242 if (!currentSelection) {
243 currentProfile = fallback;
244 } else {
245 const match = profiles.find(
246 (profile) => profile.profileDescription.id === currentSelection,
247 );
248 if (match) {
249 currentProfile = match;
250 } else {
251 currentProfile = fallback;
252 }
253 }
254
255 if (currentProfile) {
256 this.globalContext.update("lastSelectedProfileForWorkspace", {
257 ...selectedProfiles,
258 [profileKey]: currentProfile.profileDescription.id,
259 });
260 }
261
262 return {
263 ...org,
264 profiles,
265 currentProfile,
266 };
267 }
268
269 async getLocalProfiles(options: LoadAssistantFilesOptions) {
270 /**
271 * Users can define as many local assistants as they want in a `.continue/assistants` folder
272 */
273 const localProfiles: ProfileLifecycleManager[] = [];
274
275 if (options.includeGlobal) {
276 localProfiles.push(this.globalLocalProfileManager);
277 }
278
279 if (options.includeWorkspace) {
280 const assistantFiles = await getAllDotContinueYamlFiles(
281 this.ide,
282 options,
283 ASSISTANTS,
284 );
285 const profiles = assistantFiles.map((assistant) => {
286 return new LocalProfileLoader(
287 this.ide,
288 this.ideSettingsPromise,
289 this.controlPlaneClient,
290 this.llmLogger,
291 assistant,
292 );
293 });
294 const localAssistantProfiles = profiles.map(
295 (profile) => new ProfileLifecycleManager(profile, this.ide),
296 );
297 localProfiles.push(...localAssistantProfiles);
298 }
299
300 return localProfiles;
301 }
302
303 //////////////////
304 // External actions that can cause a cascading config refresh
305 // Should not be used internally
306 //////////////////
307 async refreshAll() {
308 await this.cascadeInit();
309 }
310
311 // Ide settings change: refresh session and cascade refresh from the top
312 async updateIdeSettings(ideSettings: IdeSettings) {
313 this.ideSettingsPromise = Promise.resolve(ideSettings);
314 await this.cascadeInit();
315 }
316
317 // Session change: refresh session and cascade refresh from the top
318 async updateControlPlaneSessionInfo(
319 sessionInfo: ControlPlaneSessionInfo | undefined,
320 ) {
321 this.controlPlaneClient = new ControlPlaneClient(
322 Promise.resolve(sessionInfo),
323 this.ideSettingsPromise,
324 );
325 await this.cascadeInit();
326 }
327
328 // Org id: check id validity, save selection, switch and reload
329 async setSelectedOrgId(orgId: string, profileId?: string) {
330 if (orgId === this.currentOrg.id) {
331 return;
332 }
333 const org = this.organizations.find((org) => org.id === orgId);
334 if (!org) {
335 throw new Error(`Org ${orgId} not found`);
336 }
337
338 const workspaceId = await this.getWorkspaceId();
339 const selectedOrgs =
340 this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {};
341 this.globalContext.update("lastSelectedOrgIdForWorkspace", {
342 ...selectedOrgs,
343 [workspaceId]: org.id,
344 });
345
346 this.currentOrg = org;
347
348 if (profileId) {
349 await this.setSelectedProfileId(profileId);
350 } else {
351 this.currentProfile = org.currentProfile;
352 await this.reloadConfig();
353 }
354 }
355
356 // Profile id: check id validity, save selection, switch and reload
357 async setSelectedProfileId(profileId: string) {
358 if (
359 this.currentProfile &&
360 profileId === this.currentProfile.profileDescription.id
361 ) {
362 return;
363 }
364 const profile = this.currentOrg.profiles.find(
365 (profile) => profile.profileDescription.id === profileId,
366 );
367 if (!profile) {
368 throw new Error(`Profile ${profileId} not found in current org`);
369 }
370
371 const profileKey = await this.getProfileKey(this.currentOrg.id);
372 const selectedProfiles =
373 this.globalContext.get("lastSelectedProfileForWorkspace") ?? {};
374 this.globalContext.update("lastSelectedProfileForWorkspace", {
375 ...selectedProfiles,
376 [profileKey]: profileId,
377 });
378
379 this.currentProfile = profile;
380 await this.reloadConfig();
381 }
382
383 // Bottom level of cascade: refresh the current profile
384 // IMPORTANT - must always refresh when switching profiles
385 // Because of e.g. MCP singleton and docs service using things from config
386 // Could improve this
387 async reloadConfig() {
388 if (!this.currentProfile) {
389 return {
390 config: undefined,
391 errors: [],
392 configLoadInterrupted: true,
393 };
394 }
395
396 for (const org of this.organizations) {
397 for (const profile of org.profiles) {
398 if (
399 profile.profileDescription.id !==
400 this.currentProfile.profileDescription.id
401 ) {
402 profile.clearConfig();
403 }
404 }
405 }
406
407 const { config, errors, configLoadInterrupted } =
408 await this.currentProfile.reloadConfig(this.additionalContextProviders);
409
410 this.notifyConfigListeners({ config, errors, configLoadInterrupted });
411 return { config, errors, configLoadInterrupted };
412 }
413
414 // Listeners setup - can listen to current profile updates
415 private notifyConfigListeners(result: ConfigResult<ContinueConfig>) {
416 for (const listener of this.updateListeners) {
417 listener(result);
418 }
419 }
420
421 private updateListeners: ConfigUpdateFunction[] = [];
422
423 onConfigUpdate(listener: ConfigUpdateFunction) {
424 this.updateListeners.push(listener);
425 }
426
427 // Methods for loading (without reloading) config
428 // Serialized for passing to GUI
429 // Load for just awaiting current config load promise for the profile
430 async getSerializedConfig(): Promise<
431 ConfigResult<BrowserSerializedContinueConfig>
432 > {
433 if (!this.currentProfile) {
434 return {
435 config: undefined,
436 errors: [],
437 configLoadInterrupted: true,
438 };
439 }
440 return await this.currentProfile.getSerializedConfig(
441 this.additionalContextProviders,
442 );
443 }
444
445 async loadConfig(): Promise<ConfigResult<ContinueConfig>> {
446 if (!this.currentProfile) {
447 return {
448 config: undefined,
449 errors: [],
450 configLoadInterrupted: true,
451 };
452 }
453 const config = await this.currentProfile.loadConfig(
454 this.additionalContextProviders,
455 );
456
457 if (config.errors?.length) {
458 logger.warn("Errors loading config: ", config.errors);
459 }
460 return config;
461 }
462
463 async openConfigProfile(profileId?: string) {
464 let openProfileId = profileId || this.currentProfile?.profileDescription.id;
465 if (!openProfileId) {
466 return;
467 }
468 const profile = this.currentOrg.profiles.find(
469 (p) => p.profileDescription.id === openProfileId,
470 );
471 if (profile?.profileDescription.profileType === "local") {
472 await this.ide.openFile(profile.profileDescription.uri);
473 } else {
474 const env = await getControlPlaneEnv(this.ide.getIdeSettings());
475 await this.ide.openUrl(`${env.APP_URL}${openProfileId}`);
476 }
477 }
478
479 // Ancient method of adding custom providers through vs code
480 private additionalContextProviders: IContextProvider[] = [];
481 registerCustomContextProvider(contextProvider: IContextProvider) {
482 this.additionalContextProviders.push(contextProvider);
483 void this.reloadConfig();
484 }
485 /**
486 * Retrieves the titles of additional context providers that are of type "submenu".
487 *
488 * @returns {string[]} An array of titles of the additional context providers that have a description type of "submenu".
489 */
490 getAdditionalSubmenuContextProviders(): string[] {
491 return this.additionalContextProviders
492 .filter((provider) => provider.description.type === "submenu")
493 .map((provider) => provider.description.title);
494 }
495}