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