Elffuss BraidHub

kikocis/continue public

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