Elffuss BraidHub

kikocis/continue public

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