Elffuss BraidHub

kikocis/continue public

b68735bd51e5 · 18.6 KiBRawPermalink
1import { ConfigResult, ConfigValidationError } 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 EventEmitter from "node:events";
15import {
16 AuthType,
17 ControlPlaneSessionInfo,
18} from "../control-plane/AuthTypes.js";
19import { getControlPlaneEnv } from "../control-plane/env.js";
20import { logger } from "../util/logger.js";
21import { Telemetry } from "../util/posthog.js";
22import {
23 ASSISTANTS,
24 getAllDotContinueDefinitionFiles,
25 LoadAssistantFilesOptions,
26} from "./loadLocalAssistants.js";
27import LocalProfileLoader from "./profile/LocalProfileLoader.js";
28import PlatformProfileLoader from "./profile/PlatformProfileLoader.js";
29import {
30 OrganizationDescription,
31 OrgWithProfiles,
32 ProfileDescription,
33 ProfileLifecycleManager,
34 SerializedOrgWithProfiles,
35} from "./ProfileLifecycleManager.js";
36
37export type { ProfileDescription };
38
39type ConfigUpdateFunction = (payload: ConfigResult<ContinueConfig>) => void;
40
41export class ConfigHandler {
42 controlPlaneClient: ControlPlaneClient;
43 private readonly globalContext = new GlobalContext();
44 private globalLocalProfileManager: ProfileLifecycleManager;
45
46 private organizations: OrgWithProfiles[] = [];
47 currentProfile: ProfileLifecycleManager | null;
48 currentOrg: OrgWithProfiles;
49 totalConfigReloads: number = 0;
50
51 public isInitialized: Promise<void>;
52 private initter: EventEmitter;
53
54 cascadeAbortController: AbortController;
55 private abortCascade() {
56 this.cascadeAbortController.abort();
57 this.cascadeAbortController = new AbortController();
58 }
59
60 constructor(
61 private readonly ide: IDE,
62 private ideSettingsPromise: Promise<IdeSettings>,
63 private llmLogger: ILLMLogger,
64 sessionInfoPromise: Promise<ControlPlaneSessionInfo | undefined>,
65 ) {
66 this.ide = ide;
67 this.ideSettingsPromise = ideSettingsPromise;
68
69 this.controlPlaneClient = new ControlPlaneClient(
70 sessionInfoPromise,
71 ideSettingsPromise,
72 this.ide.getIdeInfo(),
73 );
74
75 // This profile manager will always be available
76 this.globalLocalProfileManager = new ProfileLifecycleManager(
77 new LocalProfileLoader(
78 ide,
79 ideSettingsPromise,
80 this.controlPlaneClient,
81 this.llmLogger,
82 ),
83 this.ide,
84 );
85
86 // Just to be safe, always force a default personal org with local profile manager
87 this.currentProfile = this.globalLocalProfileManager;
88 const personalOrg: OrgWithProfiles = {
89 currentProfile: this.globalLocalProfileManager,
90 profiles: [this.globalLocalProfileManager],
91 ...this.PERSONAL_ORG_DESC,
92 };
93
94 this.currentOrg = personalOrg;
95 this.organizations = [personalOrg];
96
97 this.initter = new EventEmitter();
98 this.isInitialized = new Promise((resolve) => {
99 this.initter.on("init", resolve);
100 });
101
102 this.cascadeAbortController = new AbortController();
103 void this.cascadeInit("Config handler initialization");
104 }
105
106 private workspaceDirs: string[] | null = null;
107 async getWorkspaceId() {
108 if (!this.workspaceDirs) {
109 this.workspaceDirs = await this.ide.getWorkspaceDirs();
110 }
111 return this.workspaceDirs.join("&");
112 }
113
114 async getProfileKey(orgId: string) {
115 const workspaceId = await this.getWorkspaceId();
116 return `${workspaceId}:::${orgId}`;
117 }
118
119 private async cascadeInit(reason: string) {
120 const signal = this.cascadeAbortController.signal;
121 this.workspaceDirs = null; // forces workspace dirs reload
122
123 try {
124 const { orgs, errors } = await this.getOrgs();
125
126 // Figure out selected org
127 const workspaceId = await this.getWorkspaceId();
128 const selectedOrgs =
129 this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {};
130 const currentSelection = selectedOrgs[workspaceId];
131
132 const firstNonPersonal = orgs.find(
133 (org) => org.id !== this.PERSONAL_ORG_DESC.id,
134 );
135 const fallback = firstNonPersonal ?? orgs[0];
136 // note, ignoring case of zero orgs since should never happen
137
138 let selectedOrg: OrgWithProfiles;
139 if (currentSelection) {
140 const match = orgs.find((org) => org.id === currentSelection);
141 if (match) {
142 selectedOrg = match;
143 } else {
144 selectedOrg = fallback;
145 }
146 } else {
147 selectedOrg = fallback;
148 }
149
150 if (signal.aborted) {
151 return; // local only case, no`fetch to throw abort error
152 }
153
154 this.globalContext.update("lastSelectedOrgIdForWorkspace", {
155 ...selectedOrgs,
156 [workspaceId]: selectedOrg.id,
157 });
158
159 this.organizations = orgs;
160 this.currentOrg = selectedOrg;
161 this.currentProfile = selectedOrg.currentProfile;
162
163 await this.reloadConfig(reason, errors);
164 } catch (e) {
165 if (signal.aborted) {
166 return;
167 } else {
168 this.initter.emit("init"); // Error case counts as init
169 throw e;
170 }
171 }
172 }
173
174 private async getOrgs(): Promise<{
175 orgs: OrgWithProfiles[];
176 errors?: ConfigValidationError[];
177 }> {
178 const errors: ConfigValidationError[] = [];
179 const isSignedIn = await this.controlPlaneClient.isSignedIn();
180 if (isSignedIn) {
181 try {
182 const orgDescs = await this.controlPlaneClient.listOrganizations();
183 const orgs = await Promise.all([
184 this.getPersonalHubOrg(),
185 ...orgDescs.map((org) => this.getNonPersonalHubOrg(org)),
186 ]);
187 // TODO make try/catch more granular here, to catch specific org errors
188 return { orgs };
189 } catch (e) {
190 errors.push({
191 fatal: false,
192 message: `Error loading Continue Hub assistants${e instanceof Error ? ":\n" + e.message : ""}`,
193 });
194 }
195 }
196 // Load local org if not signed in or hub orgs fail
197 try {
198 const orgs = [await this.getLocalOrg()];
199 return { orgs };
200 } catch (e) {
201 errors.push({
202 fatal: true,
203 message: `Error loading local assistants${e instanceof Error ? ":\n" + e.message : ""}`,
204 });
205 return {
206 orgs: [],
207 errors,
208 };
209 }
210 }
211
212 getSerializedOrgs(): SerializedOrgWithProfiles[] {
213 return this.organizations.map((org) => ({
214 iconUrl: org.iconUrl,
215 id: org.id,
216 name: org.name,
217 slug: org.slug,
218 profiles: org.profiles.map((profile) => profile.profileDescription),
219 selectedProfileId: org.currentProfile?.profileDescription.id || null,
220 }));
221 }
222
223 private async getHubProfiles(orgScopeId: string | null) {
224 const assistants = await this.controlPlaneClient.listAssistants(orgScopeId);
225
226 return await Promise.all(
227 assistants.map(async (assistant) => {
228 const profileLoader = await PlatformProfileLoader.create({
229 configResult: {
230 ...assistant.configResult,
231 config: assistant.configResult.config,
232 },
233 ownerSlug: assistant.ownerSlug,
234 packageSlug: assistant.packageSlug,
235 iconUrl: assistant.iconUrl,
236 versionSlug: assistant.configResult.config?.version ?? "latest",
237 controlPlaneClient: this.controlPlaneClient,
238 ide: this.ide,
239 ideSettingsPromise: this.ideSettingsPromise,
240 llmLogger: this.llmLogger,
241 rawYaml: assistant.rawYaml,
242 orgScopeId: orgScopeId,
243 });
244
245 return new ProfileLifecycleManager(profileLoader, this.ide);
246 }),
247 );
248 }
249
250 private async getNonPersonalHubOrg(
251 org: OrganizationDescription,
252 ): Promise<OrgWithProfiles> {
253 const localProfiles = await this.getLocalProfiles({
254 includeGlobal: false,
255 includeWorkspace: true,
256 });
257 const profiles = [...(await this.getHubProfiles(org.id)), ...localProfiles];
258 return this.rectifyProfilesForOrg(org, profiles);
259 }
260
261 private PERSONAL_ORG_DESC: OrganizationDescription = {
262 iconUrl: "",
263 id: "personal",
264 name: "Personal",
265 slug: undefined,
266 };
267 private async getPersonalHubOrg() {
268 const localProfiles = await this.getLocalProfiles({
269 includeGlobal: true,
270 includeWorkspace: true,
271 });
272 const hubProfiles = await this.getHubProfiles(null);
273 const profiles = [...hubProfiles, ...localProfiles];
274 return this.rectifyProfilesForOrg(this.PERSONAL_ORG_DESC, profiles);
275 }
276
277 private async getLocalOrg() {
278 const localProfiles = await this.getLocalProfiles({
279 includeGlobal: true,
280 includeWorkspace: true,
281 });
282 return this.rectifyProfilesForOrg(this.PERSONAL_ORG_DESC, localProfiles);
283 }
284
285 private async rectifyProfilesForOrg(
286 org: OrganizationDescription,
287 profiles: ProfileLifecycleManager[],
288 ): Promise<OrgWithProfiles> {
289 const profileKey = await this.getProfileKey(org.id);
290 const selectedProfiles =
291 this.globalContext.get("lastSelectedProfileForWorkspace") ?? {};
292
293 const currentSelection = selectedProfiles[profileKey];
294
295 const firstNonLocal = profiles.find(
296 (profile) => profile.profileDescription.profileType !== "local",
297 );
298 const fallback =
299 firstNonLocal ?? (profiles.length > 0 ? profiles[0] : null);
300
301 let currentProfile: ProfileLifecycleManager | null;
302 if (currentSelection) {
303 const match = profiles.find(
304 (profile) => profile.profileDescription.id === currentSelection,
305 );
306 if (match) {
307 currentProfile = match;
308 } else {
309 currentProfile = fallback;
310 }
311 } else {
312 currentProfile = fallback;
313 }
314
315 if (currentProfile) {
316 this.globalContext.update("lastSelectedProfileForWorkspace", {
317 ...selectedProfiles,
318 [profileKey]: currentProfile.profileDescription.id,
319 });
320 }
321
322 return {
323 ...org,
324 profiles,
325 currentProfile,
326 };
327 }
328
329 async getLocalProfiles(options: LoadAssistantFilesOptions) {
330 /**
331 * Users can define as many local assistants as they want in a `.continue/assistants` folder
332 */
333
334 // Local customization disabled for on-premise deployments
335 const env = await getControlPlaneEnv(this.ide.getIdeSettings());
336 if (env.AUTH_TYPE === AuthType.OnPrem) {
337 return [];
338 }
339
340 const localProfiles: ProfileLifecycleManager[] = [];
341
342 if (options.includeGlobal) {
343 localProfiles.push(this.globalLocalProfileManager);
344 }
345
346 if (options.includeWorkspace) {
347 const assistantFiles = await getAllDotContinueDefinitionFiles(
348 this.ide,
349 options,
350 ASSISTANTS,
351 );
352 const profiles = assistantFiles.map((assistant) => {
353 return new LocalProfileLoader(
354 this.ide,
355 this.ideSettingsPromise,
356 this.controlPlaneClient,
357 this.llmLogger,
358 assistant,
359 );
360 });
361 const localAssistantProfiles = profiles.map(
362 (profile) => new ProfileLifecycleManager(profile, this.ide),
363 );
364 localProfiles.push(...localAssistantProfiles);
365 }
366
367 return localProfiles;
368 }
369
370 //////////////////
371 // External actions that can cause a cascading config refresh
372 // Should not be used internally
373 //////////////////
374 async refreshAll(reason?: string) {
375 await this.cascadeInit(reason ?? "External refresh all");
376 }
377
378 // Ide settings change: refresh session and cascade refresh from the top
379 async updateIdeSettings(ideSettings: IdeSettings) {
380 this.ideSettingsPromise = Promise.resolve(ideSettings);
381 this.abortCascade();
382 await this.cascadeInit("IDE settings update");
383 }
384
385 // Session change: refresh session and cascade refresh from the top
386 async updateControlPlaneSessionInfo(
387 sessionInfo: ControlPlaneSessionInfo | undefined,
388 ) {
389 const currentSession = await this.controlPlaneClient.sessionInfoPromise;
390 const newSession = sessionInfo;
391
392 let reload = false;
393 if (newSession) {
394 if (currentSession) {
395 if (
396 newSession.AUTH_TYPE !== AuthType.OnPrem &&
397 currentSession.AUTH_TYPE !== AuthType.OnPrem
398 ) {
399 if (newSession.account.id !== currentSession.account.id) {
400 // session id change (non-on-prem)
401 reload = true;
402 }
403 }
404 } else {
405 // log in
406 reload = true;
407 }
408 } else {
409 if (currentSession) {
410 // log out
411 reload = true;
412 }
413 }
414
415 if (reload) {
416 this.controlPlaneClient = new ControlPlaneClient(
417 Promise.resolve(sessionInfo),
418 this.ideSettingsPromise,
419 this.ide.getIdeInfo(),
420 );
421 this.abortCascade();
422 await this.cascadeInit("Control plane session info update");
423 }
424 return reload;
425 }
426
427 // Org id: check id validity, save selection, switch and reload
428 async setSelectedOrgId(orgId: string, profileId?: string) {
429 if (orgId === this.currentOrg.id) {
430 return;
431 }
432 const org = this.organizations.find((org) => org.id === orgId);
433 if (!org) {
434 throw new Error(`Org ${orgId} not found`);
435 }
436
437 const workspaceId = await this.getWorkspaceId();
438 const selectedOrgs =
439 this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {};
440 this.globalContext.update("lastSelectedOrgIdForWorkspace", {
441 ...selectedOrgs,
442 [workspaceId]: org.id,
443 });
444
445 this.currentOrg = org;
446
447 if (profileId) {
448 await this.setSelectedProfileId(profileId);
449 } else {
450 this.currentProfile = org.currentProfile;
451 await this.reloadConfig("Selected org changed");
452 }
453 }
454
455 // Profile id: check id validity, save selection, switch and reload
456 async setSelectedProfileId(profileId: string) {
457 if (
458 this.currentProfile &&
459 profileId === this.currentProfile.profileDescription.id
460 ) {
461 return;
462 }
463 const profile = this.currentOrg.profiles.find(
464 (profile) => profile.profileDescription.id === profileId,
465 );
466 if (!profile) {
467 throw new Error(`Profile ${profileId} not found in current org`);
468 }
469
470 const profileKey = await this.getProfileKey(this.currentOrg.id);
471 const selectedProfiles =
472 this.globalContext.get("lastSelectedProfileForWorkspace") ?? {};
473 this.globalContext.update("lastSelectedProfileForWorkspace", {
474 ...selectedProfiles,
475 [profileKey]: profileId,
476 });
477
478 this.currentProfile = profile;
479 await this.reloadConfig("Selected profile changed");
480 }
481
482 // Bottom level of cascade: refresh the current profile
483 // IMPORTANT - must always refresh when switching profiles
484 // Because of e.g. MCP singleton and docs service using things from config
485 // Could improve this
486 async reloadConfig(reason: string, injectErrors?: ConfigValidationError[]) {
487 const startTime = performance.now();
488 this.totalConfigReloads += 1;
489 // console.log(`Reloading config (#${this.totalConfigLoads}): ${reason}`); // Uncomment to see config loading logs
490 if (!this.currentProfile) {
491 return {
492 config: undefined,
493 errors: [
494 { message: "Current profile not found", fatal: true },
495 ...(injectErrors ?? []),
496 ],
497 configLoadInterrupted: true,
498 };
499 }
500
501 for (const org of this.organizations) {
502 for (const profile of org.profiles) {
503 if (
504 profile.profileDescription.id !==
505 this.currentProfile.profileDescription.id
506 ) {
507 profile.clearConfig();
508 }
509 }
510 }
511
512 const {
513 config,
514 errors = [],
515 configLoadInterrupted,
516 } = await this.currentProfile.reloadConfig(this.additionalContextProviders);
517
518 if (injectErrors) {
519 errors.unshift(...injectErrors);
520 }
521
522 this.notifyConfigListeners({ config, errors, configLoadInterrupted });
523
524 this.initter.emit("init");
525
526 // Track config loading telemetry
527 const endTime = performance.now();
528 const duration = endTime - startTime;
529 void Telemetry.capture("config_reload", {
530 duration,
531 reason,
532 totalConfigLoads: this.totalConfigReloads,
533 configLoadInterrupted,
534 });
535
536 return {
537 config,
538 errors: errors.length ? errors : undefined,
539 configLoadInterrupted,
540 };
541 }
542
543 // Listeners setup - can listen to current profile updates
544 private notifyConfigListeners(result: ConfigResult<ContinueConfig>) {
545 for (const listener of this.updateListeners) {
546 listener(result);
547 }
548 }
549
550 private updateListeners: ConfigUpdateFunction[] = [];
551
552 onConfigUpdate(listener: ConfigUpdateFunction) {
553 this.updateListeners.push(listener);
554 }
555
556 // Methods for loading (without reloading) config
557 // Serialized for passing to GUI
558 // Load for just awaiting current config load promise for the profile
559 async getSerializedConfig(): Promise<
560 ConfigResult<BrowserSerializedContinueConfig>
561 > {
562 if (!this.currentProfile) {
563 return {
564 config: undefined,
565 errors: [{ message: "Current profile not found", fatal: true }],
566 configLoadInterrupted: true,
567 };
568 }
569 return await this.currentProfile.getSerializedConfig(
570 this.additionalContextProviders,
571 );
572 }
573
574 async loadConfig(): Promise<ConfigResult<ContinueConfig>> {
575 if (!this.currentProfile) {
576 return {
577 config: undefined,
578 errors: [{ message: "Current profile not found", fatal: true }],
579 configLoadInterrupted: true,
580 };
581 }
582 await this.isInitialized;
583 const config = await this.currentProfile.loadConfig(
584 this.additionalContextProviders,
585 );
586
587 if (config.errors?.length) {
588 logger.warn("Errors loading config: ", config.errors);
589 }
590 return config;
591 }
592
593 async openConfigProfile(
594 profileId?: string,
595 element?: { sourceFile?: string },
596 ) {
597 let openProfileId = profileId || this.currentProfile?.profileDescription.id;
598 if (!openProfileId) {
599 return;
600 }
601 const profile = this.currentOrg.profiles.find(
602 (p) => p.profileDescription.id === openProfileId,
603 );
604
605 if (profile?.profileDescription.profileType === "local") {
606 const configFile = element?.sourceFile ?? profile.profileDescription.uri;
607 await this.ide.openFile(configFile);
608 } else {
609 const env = await getControlPlaneEnv(this.ide.getIdeSettings());
610 await this.ide.openUrl(`${env.APP_URL}${openProfileId}`);
611 }
612 }
613
614 // Ancient method of adding custom providers through vs code
615 private additionalContextProviders: IContextProvider[] = [];
616 registerCustomContextProvider(contextProvider: IContextProvider) {
617 this.additionalContextProviders.push(contextProvider);
618 void this.reloadConfig("Custom context provider registered");
619 }
620 /**
621 * Retrieves the titles of additional context providers that are of type "submenu".
622 *
623 * @returns {string[]} An array of titles of the additional context providers that have a description type of "submenu".
624 */
625 getAdditionalSubmenuContextProviders(): string[] {
626 return this.additionalContextProviders
627 .filter((provider) => provider.description.type === "submenu")
628 .map((provider) => provider.description.title);
629 }
630}