Elffuss BraidHub

kikocis/continue public

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