Elffuss BraidHub

kikocis/continue public

6d66081d22d3 · 14.9 KiBRawPermalink
1import { ConfigResult } from "@continuedev/config-yaml";
2
3import { ControlPlaneClient } from "../control-plane/client.js";
4import {
5 BrowserSerializedContinueConfig,
6 ContinueConfig,
7 IContextProvider,
8 IDE,
9 IdeSettings,
10 ILLMLogger,
11} from "../index.js";
12import { GlobalContext } from "../util/GlobalContext.js";
13
14import {
15 AuthType,
16 ControlPlaneSessionInfo,
17} from "../control-plane/AuthTypes.js";
18import { getControlPlaneEnv } from "../control-plane/env.js";
19import { logger } from "../util/logger.js";
20import {
21 ASSISTANTS,
22 getAllDotContinueDefinitionFiles,
23 LoadAssistantFilesOptions,
24} from "./loadLocalAssistants.js";
25import LocalProfileLoader from "./profile/LocalProfileLoader.js";
26import PlatformProfileLoader from "./profile/PlatformProfileLoader.js";
27import {
28 OrganizationDescription,
29 OrgWithProfiles,
30 ProfileDescription,
31 ProfileLifecycleManager,
32 SerializedOrgWithProfiles,
33} from "./ProfileLifecycleManager.js";
34
35export type { ProfileDescription };
36
37type ConfigUpdateFunction = (payload: ConfigResult<ContinueConfig>) => void;
38
39export class ConfigHandler {
40 controlPlaneClient: ControlPlaneClient;
41 private readonly globalContext = new GlobalContext();
42 private globalLocalProfileManager: ProfileLifecycleManager;
43
44 private organizations: OrgWithProfiles[] = [];
45 currentProfile: ProfileLifecycleManager | null;
46 currentOrg: OrgWithProfiles;
47
48 constructor(
49 private readonly ide: IDE,
50 private ideSettingsPromise: Promise<IdeSettings>,
51 private llmLogger: ILLMLogger,
52 sessionInfoPromise: Promise<ControlPlaneSessionInfo | undefined>,
53 ) {
54 this.ide = ide;
55 this.ideSettingsPromise = ideSettingsPromise;
56 this.controlPlaneClient = new ControlPlaneClient(
57 sessionInfoPromise,
58 ideSettingsPromise,
59 );
60
61 // This profile manager will always be available
62 this.globalLocalProfileManager = new ProfileLifecycleManager(
63 new LocalProfileLoader(
64 ide,
65 ideSettingsPromise,
66 this.controlPlaneClient,
67 this.llmLogger,
68 ),
69 this.ide,
70 );
71
72 // Just to be safe, always force a default personal org with local profile manager
73 this.currentProfile = this.globalLocalProfileManager;
74 const personalOrg: OrgWithProfiles = {
75 currentProfile: this.globalLocalProfileManager,
76 profiles: [this.globalLocalProfileManager],
77 ...this.PERSONAL_ORG_DESC,
78 };
79
80 this.currentOrg = personalOrg;
81 this.organizations = [personalOrg];
82
83 void this.cascadeInit();
84 }
85
86 private workspaceDirs: string[] | null = null;
87 async getWorkspaceId() {
88 if (!this.workspaceDirs) {
89 this.workspaceDirs = await this.ide.getWorkspaceDirs();
90 }
91 return this.workspaceDirs.join("&");
92 }
93
94 async getProfileKey(orgId: string) {
95 const workspaceId = await this.getWorkspaceId();
96 return `${workspaceId}:::${orgId}`;
97 }
98
99 private async cascadeInit() {
100 this.workspaceDirs = null; // forces workspace dirs reload
101
102 const orgs = await this.getOrgs();
103
104 // Figure out selected org
105 const workspaceId = await this.getWorkspaceId();
106 const selectedOrgs =
107 this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {};
108 const currentSelection = selectedOrgs[workspaceId];
109
110 const firstNonPersonal = orgs.find(
111 (org) => org.id !== this.PERSONAL_ORG_DESC.id,
112 );
113 const fallback = firstNonPersonal ?? orgs[0];
114 // note, ignoring case of zero orgs since should never happen
115
116 let selectedOrg: OrgWithProfiles;
117 if (!currentSelection) {
118 selectedOrg = fallback;
119 } else {
120 const match = orgs.find((org) => org.id === currentSelection);
121 if (match) {
122 selectedOrg = match;
123 } else {
124 selectedOrg = fallback;
125 }
126 }
127
128 this.globalContext.update("lastSelectedOrgIdForWorkspace", {
129 ...selectedOrgs,
130 [workspaceId]: selectedOrg.id,
131 });
132
133 this.organizations = orgs;
134 this.currentOrg = selectedOrg;
135 this.currentProfile = selectedOrg.currentProfile;
136 await this.reloadConfig();
137 }
138
139 private async getOrgs(): Promise<OrgWithProfiles[]> {
140 if (await this.controlPlaneClient.isSignedIn()) {
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
274 // Local customization disabled for on-premise deployments
275 const env = await getControlPlaneEnv(this.ide.getIdeSettings());
276 if (env.AUTH_TYPE === AuthType.OnPrem) {
277 return [];
278 }
279
280 const localProfiles: ProfileLifecycleManager[] = [];
281
282 if (options.includeGlobal) {
283 localProfiles.push(this.globalLocalProfileManager);
284 }
285
286 if (options.includeWorkspace) {
287 const assistantFiles = await getAllDotContinueDefinitionFiles(
288 this.ide,
289 options,
290 ASSISTANTS,
291 );
292 const profiles = assistantFiles.map((assistant) => {
293 return new LocalProfileLoader(
294 this.ide,
295 this.ideSettingsPromise,
296 this.controlPlaneClient,
297 this.llmLogger,
298 assistant,
299 );
300 });
301 const localAssistantProfiles = profiles.map(
302 (profile) => new ProfileLifecycleManager(profile, this.ide),
303 );
304 localProfiles.push(...localAssistantProfiles);
305 }
306
307 return localProfiles;
308 }
309
310 //////////////////
311 // External actions that can cause a cascading config refresh
312 // Should not be used internally
313 //////////////////
314 async refreshAll() {
315 await this.cascadeInit();
316 }
317
318 // Ide settings change: refresh session and cascade refresh from the top
319 async updateIdeSettings(ideSettings: IdeSettings) {
320 this.ideSettingsPromise = Promise.resolve(ideSettings);
321 await this.cascadeInit();
322 }
323
324 // Session change: refresh session and cascade refresh from the top
325 async updateControlPlaneSessionInfo(
326 sessionInfo: ControlPlaneSessionInfo | undefined,
327 ) {
328 this.controlPlaneClient = new ControlPlaneClient(
329 Promise.resolve(sessionInfo),
330 this.ideSettingsPromise,
331 );
332 await this.cascadeInit();
333 }
334
335 // Org id: check id validity, save selection, switch and reload
336 async setSelectedOrgId(orgId: string, profileId?: string) {
337 if (orgId === this.currentOrg.id) {
338 return;
339 }
340 const org = this.organizations.find((org) => org.id === orgId);
341 if (!org) {
342 throw new Error(`Org ${orgId} not found`);
343 }
344
345 const workspaceId = await this.getWorkspaceId();
346 const selectedOrgs =
347 this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {};
348 this.globalContext.update("lastSelectedOrgIdForWorkspace", {
349 ...selectedOrgs,
350 [workspaceId]: org.id,
351 });
352
353 this.currentOrg = org;
354
355 if (profileId) {
356 await this.setSelectedProfileId(profileId);
357 } else {
358 this.currentProfile = org.currentProfile;
359 await this.reloadConfig();
360 }
361 }
362
363 // Profile id: check id validity, save selection, switch and reload
364 async setSelectedProfileId(profileId: string) {
365 if (
366 this.currentProfile &&
367 profileId === this.currentProfile.profileDescription.id
368 ) {
369 return;
370 }
371 const profile = this.currentOrg.profiles.find(
372 (profile) => profile.profileDescription.id === profileId,
373 );
374 if (!profile) {
375 throw new Error(`Profile ${profileId} not found in current org`);
376 }
377
378 const profileKey = await this.getProfileKey(this.currentOrg.id);
379 const selectedProfiles =
380 this.globalContext.get("lastSelectedProfileForWorkspace") ?? {};
381 this.globalContext.update("lastSelectedProfileForWorkspace", {
382 ...selectedProfiles,
383 [profileKey]: profileId,
384 });
385
386 this.currentProfile = profile;
387 await this.reloadConfig();
388 }
389
390 // Bottom level of cascade: refresh the current profile
391 // IMPORTANT - must always refresh when switching profiles
392 // Because of e.g. MCP singleton and docs service using things from config
393 // Could improve this
394 async reloadConfig() {
395 if (!this.currentProfile) {
396 return {
397 config: undefined,
398 errors: [],
399 configLoadInterrupted: true,
400 };
401 }
402
403 for (const org of this.organizations) {
404 for (const profile of org.profiles) {
405 if (
406 profile.profileDescription.id !==
407 this.currentProfile.profileDescription.id
408 ) {
409 profile.clearConfig();
410 }
411 }
412 }
413
414 const { config, errors, configLoadInterrupted } =
415 await this.currentProfile.reloadConfig(this.additionalContextProviders);
416
417 this.notifyConfigListeners({ config, errors, configLoadInterrupted });
418 return { config, errors, configLoadInterrupted };
419 }
420
421 // Listeners setup - can listen to current profile updates
422 private notifyConfigListeners(result: ConfigResult<ContinueConfig>) {
423 for (const listener of this.updateListeners) {
424 listener(result);
425 }
426 }
427
428 private updateListeners: ConfigUpdateFunction[] = [];
429
430 onConfigUpdate(listener: ConfigUpdateFunction) {
431 this.updateListeners.push(listener);
432 }
433
434 // Methods for loading (without reloading) config
435 // Serialized for passing to GUI
436 // Load for just awaiting current config load promise for the profile
437 async getSerializedConfig(): Promise<
438 ConfigResult<BrowserSerializedContinueConfig>
439 > {
440 if (!this.currentProfile) {
441 return {
442 config: undefined,
443 errors: [],
444 configLoadInterrupted: true,
445 };
446 }
447 return await this.currentProfile.getSerializedConfig(
448 this.additionalContextProviders,
449 );
450 }
451
452 async loadConfig(): Promise<ConfigResult<ContinueConfig>> {
453 if (!this.currentProfile) {
454 return {
455 config: undefined,
456 errors: [],
457 configLoadInterrupted: true,
458 };
459 }
460 const config = await this.currentProfile.loadConfig(
461 this.additionalContextProviders,
462 );
463
464 if (config.errors?.length) {
465 logger.warn("Errors loading config: ", config.errors);
466 }
467 return config;
468 }
469
470 async openConfigProfile(profileId?: string) {
471 let openProfileId = profileId || this.currentProfile?.profileDescription.id;
472 if (!openProfileId) {
473 return;
474 }
475 const profile = this.currentOrg.profiles.find(
476 (p) => p.profileDescription.id === openProfileId,
477 );
478 if (profile?.profileDescription.profileType === "local") {
479 await this.ide.openFile(profile.profileDescription.uri);
480 } else {
481 const env = await getControlPlaneEnv(this.ide.getIdeSettings());
482 await this.ide.openUrl(`${env.APP_URL}${openProfileId}`);
483 }
484 }
485
486 // Ancient method of adding custom providers through vs code
487 private additionalContextProviders: IContextProvider[] = [];
488 registerCustomContextProvider(contextProvider: IContextProvider) {
489 this.additionalContextProviders.push(contextProvider);
490 void this.reloadConfig();
491 }
492 /**
493 * Retrieves the titles of additional context providers that are of type "submenu".
494 *
495 * @returns {string[]} An array of titles of the additional context providers that have a description type of "submenu".
496 */
497 getAdditionalSubmenuContextProviders(): string[] {
498 return this.additionalContextProviders
499 .filter((provider) => provider.description.type === "submenu")
500 .map((provider) => provider.description.title);
501 }
502}