Elffuss BraidHub

kikocis/continue public

main · 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 llmLogger: ILLMLogger,
63 initialSessionInfoPromise: Promise<ControlPlaneSessionInfo | undefined>,
64 ) {
65 this.controlPlaneClient = new ControlPlaneClient(
66 initialSessionInfoPromise,
67 this.ide,
68 );
69
70 // This profile manager will always be available
71 this.globalLocalProfileManager = new ProfileLifecycleManager(
72 new LocalProfileLoader(ide, this.controlPlaneClient, this.llmLogger),
73 this.ide,
74 );
75
76 this.currentOrg = null;
77 this.currentProfile = null;
78 this.organizations = [];
79
80 this.initter = new EventEmitter();
81 this.isInitialized = new Promise((resolve) => {
82 this.initter.on("init", resolve);
83 });
84
85 this.cascadeAbortController = new AbortController();
86 void this.cascadeInit("Config handler initialization");
87 }
88
89 private workspaceDirs: string[] | null = null;
90
91 async getWorkspaceId() {
92 if (!this.workspaceDirs) {
93 this.workspaceDirs = await this.ide.getWorkspaceDirs();
94 }
95 return this.workspaceDirs.join("&");
96 }
97
98 async getProfileKey(orgId: string) {
99 const workspaceId = await this.getWorkspaceId();
100 return `${workspaceId}:::${orgId}`;
101 }
102
103 private async cascadeInit(reason: string) {
104 const signal = this.cascadeAbortController.signal;
105 this.workspaceDirs = null; // forces workspace dirs reload
106
107 // Always update globalLocalProfileManager before recreating all the loaders
108 // during every cascadeInit so it holds the most recent controlPlaneClient.
109 this.globalLocalProfileManager = new ProfileLifecycleManager(
110 new LocalProfileLoader(this.ide, this.controlPlaneClient, this.llmLogger),
111 this.ide,
112 );
113
114 try {
115 const { orgs, errors } = await this.getOrgs();
116
117 // Figure out selected org
118 const workspaceId = await this.getWorkspaceId();
119 const selectedOrgs =
120 this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {};
121 const currentSelection = selectedOrgs[workspaceId];
122
123 const firstNonPersonal = orgs.find(
124 (org) => org.id !== this.PERSONAL_ORG_DESC.id,
125 );
126 const fallback: OrgWithProfiles | null =
127 firstNonPersonal ?? orgs[0] ?? null;
128
129 let selectedOrg: OrgWithProfiles | null;
130 if (currentSelection) {
131 const match = orgs.find((org) => org.id === currentSelection);
132 if (match) {
133 selectedOrg = match;
134 } else {
135 selectedOrg = fallback;
136 }
137 } else {
138 selectedOrg = fallback;
139 }
140
141 if (signal.aborted) {
142 return; // local only case, no`fetch to throw abort error
143 }
144
145 this.globalContext.update("lastSelectedOrgIdForWorkspace", {
146 ...selectedOrgs,
147 [workspaceId]: selectedOrg?.id,
148 });
149
150 this.organizations = orgs;
151 this.currentOrg = selectedOrg;
152 this.currentProfile = selectedOrg?.currentProfile;
153
154 await this.reloadConfig(reason, errors);
155 } catch (e) {
156 if (signal.aborted) {
157 return;
158 } else {
159 this.initter.emit("init"); // Error case counts as init
160 throw e;
161 }
162 }
163 }
164
165 private async getOrgs(): Promise<{
166 orgs: OrgWithProfiles[];
167 errors?: ConfigValidationError[];
168 }> {
169 const errors: ConfigValidationError[] = [];
170 const isSignedIn = await this.controlPlaneClient.isSignedIn();
171 if (isSignedIn) {
172 try {
173 // TODO use policy returned with org, not policy endpoint
174 const policyResponse = await this.controlPlaneClient.getPolicy();
175 PolicySingleton.getInstance().policy = policyResponse;
176 const orgDescriptions =
177 await this.controlPlaneClient.listOrganizations();
178 const orgsWithPolicy = orgDescriptions.map((d) => ({
179 ...d,
180 policy: policyResponse?.policy,
181 }));
182
183 if (policyResponse?.policy?.allowOtherOrgs === false) {
184 if (orgsWithPolicy.length === 0) {
185 return { orgs: [] };
186 } else {
187 const firstOrg = await this.getNonPersonalHubOrg(orgsWithPolicy[0]);
188 return { orgs: [firstOrg] };
189 }
190 }
191 const orgs = await Promise.all([
192 this.getPersonalHubOrg(),
193 ...orgsWithPolicy.map((org) => this.getNonPersonalHubOrg(org)),
194 ]);
195 // TODO make try/catch more granular here, to catch specific org errors
196 return { orgs };
197 } catch (e) {
198 errors.push({
199 fatal: false,
200 message: `Error loading Continue Hub assistants${e instanceof Error ? ":\n" + e.message : ""}`,
201 });
202 }
203 } else {
204 PolicySingleton.getInstance().policy = null;
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 llmLogger: this.llmLogger,
250 rawYaml: assistant.rawYaml,
251 orgScopeId: orgScopeId,
252 });
253
254 return new ProfileLifecycleManager(profileLoader, this.ide);
255 }),
256 );
257 }
258
259 private async getNonPersonalHubOrg(
260 org: OrganizationDescription,
261 ): Promise<OrgWithProfiles> {
262 const localProfiles = await this.getLocalProfiles({
263 includeGlobal: false,
264 includeWorkspace: true,
265 });
266 const profiles = [...(await this.getHubProfiles(org.id)), ...localProfiles];
267 return this.rectifyProfilesForOrg(org, profiles);
268 }
269
270 private PERSONAL_ORG_DESC: OrganizationDescription = {
271 iconUrl: "",
272 id: "personal",
273 name: "Personal",
274 slug: undefined,
275 };
276 private async getPersonalHubOrg() {
277 const localProfiles = await this.getLocalProfiles({
278 includeGlobal: true,
279 includeWorkspace: true,
280 });
281 const hubProfiles = await this.getHubProfiles(null);
282 const profiles = [...hubProfiles, ...localProfiles];
283 return this.rectifyProfilesForOrg(this.PERSONAL_ORG_DESC, profiles);
284 }
285
286 private async getLocalOrg() {
287 const localProfiles = await this.getLocalProfiles({
288 includeGlobal: true,
289 includeWorkspace: true,
290 });
291 return this.rectifyProfilesForOrg(this.PERSONAL_ORG_DESC, localProfiles);
292 }
293
294 private async rectifyProfilesForOrg(
295 org: OrganizationDescription,
296 profiles: ProfileLifecycleManager[],
297 ): Promise<OrgWithProfiles> {
298 const profileKey = await this.getProfileKey(org.id);
299 const selectedProfiles =
300 this.globalContext.get("lastSelectedProfileForWorkspace") ?? {};
301
302 const currentSelection = selectedProfiles[profileKey];
303
304 const firstNonLocal = profiles.find(
305 (profile) => profile.profileDescription.profileType !== "local",
306 );
307 const fallback =
308 firstNonLocal ?? (profiles.length > 0 ? profiles[0] : null);
309
310 let currentProfile: ProfileLifecycleManager | null;
311 if (currentSelection) {
312 const match = profiles.find(
313 (profile) => profile.profileDescription.id === currentSelection,
314 );
315 if (match) {
316 currentProfile = match;
317 } else {
318 currentProfile = fallback;
319 }
320 } else {
321 currentProfile = fallback;
322 }
323
324 if (currentProfile) {
325 this.globalContext.update("lastSelectedProfileForWorkspace", {
326 ...selectedProfiles,
327 [profileKey]: currentProfile.profileDescription.id,
328 });
329 }
330
331 return {
332 ...org,
333 profiles,
334 currentProfile,
335 };
336 }
337
338 async getLocalProfiles(options: LoadAssistantFilesOptions) {
339 /**
340 * Users can define as many local agents as they want in a `.continue/agents` (or previous .continue/assistants) folder
341 */
342
343 // Local customization disabled for on-premise deployments
344 const env = await getControlPlaneEnv(this.ide.getIdeSettings());
345 if (env.AUTH_TYPE === AuthType.OnPrem) {
346 return [];
347 }
348
349 const localProfiles: ProfileLifecycleManager[] = [];
350
351 if (options.includeGlobal) {
352 localProfiles.push(this.globalLocalProfileManager);
353 }
354
355 if (options.includeWorkspace) {
356 const assistantFiles = await getAllDotContinueDefinitionFiles(
357 this.ide,
358 options,
359 "assistants",
360 );
361 const agentFiles = await getAllDotContinueDefinitionFiles(
362 this.ide,
363 options,
364 "agents",
365 );
366 const profiles = [...assistantFiles, ...agentFiles].map((assistant) => {
367 return new LocalProfileLoader(
368 this.ide,
369 this.controlPlaneClient,
370 this.llmLogger,
371 assistant,
372 );
373 });
374 const localAssistantProfiles = profiles.map(
375 (profile) => new ProfileLifecycleManager(profile, this.ide),
376 );
377 localProfiles.push(...localAssistantProfiles);
378 }
379
380 return localProfiles;
381 }
382
383 //////////////////
384 // External actions that can cause a cascading config refresh
385 // Should not be used internally
386 //////////////////
387 async refreshAll(reason?: string) {
388 await this.cascadeInit(reason ?? "External refresh all");
389 }
390
391 // Ide settings change: refresh session and cascade refresh from the top
392 async updateIdeSettings(ideSettings: IdeSettings) {
393 this.abortCascade();
394 await this.cascadeInit("IDE settings update");
395 }
396
397 // Session change: refresh session and cascade refresh from the top
398 async updateControlPlaneSessionInfo(
399 sessionInfo: ControlPlaneSessionInfo | undefined,
400 ) {
401 const currentSession = await this.controlPlaneClient.sessionInfoPromise;
402 const newSession = sessionInfo;
403
404 let reload = false;
405 if (newSession) {
406 if (currentSession) {
407 if (
408 newSession.AUTH_TYPE !== AuthType.OnPrem &&
409 currentSession.AUTH_TYPE !== AuthType.OnPrem
410 ) {
411 if (newSession.account.id !== currentSession.account.id) {
412 // session id change (non-on-prem)
413 reload = true;
414 }
415 }
416 } else {
417 // log in
418 reload = true;
419 }
420 } else {
421 if (currentSession) {
422 // log out
423 reload = true;
424 }
425 }
426
427 if (reload) {
428 this.controlPlaneClient = new ControlPlaneClient(
429 Promise.resolve(sessionInfo),
430 this.ide,
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}