Elffuss BraidHub

kikocis/continue public

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