Elffuss BraidHub

kikocis/continue public

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