| 1 | import { fetchwithRequestOptions } from "@continuedev/fetch"; |
| 2 | import * as URI from "uri-js"; |
| 3 | import { v4 as uuidv4 } from "uuid"; |
| 4 | |
| 5 | import { CompletionProvider } from "./autocomplete/CompletionProvider"; |
| 6 | import { ConfigHandler } from "./config/ConfigHandler"; |
| 7 | import { SYSTEM_PROMPT_DOT_FILE } from "./config/getWorkspaceContinueRuleDotFiles"; |
| 8 | import { addModel, deleteModel } from "./config/util"; |
| 9 | import CodebaseContextProvider from "./context/providers/CodebaseContextProvider"; |
| 10 | import CurrentFileContextProvider from "./context/providers/CurrentFileContextProvider"; |
| 11 | import { recentlyEditedFilesCache } from "./context/retrieval/recentlyEditedFilesCache"; |
| 12 | import { ContinueServerClient } from "./continueServer/stubs/client"; |
| 13 | import { getAuthUrlForTokenPage } from "./control-plane/auth/index"; |
| 14 | import { getControlPlaneEnv } from "./control-plane/env"; |
| 15 | import { DevDataSqliteDb } from "./data/devdataSqlite"; |
| 16 | import { DataLogger } from "./data/log"; |
| 17 | import { CodebaseIndexer } from "./indexing/CodebaseIndexer"; |
| 18 | import DocsService from "./indexing/docs/DocsService"; |
| 19 | import { countTokens } from "./llm/countTokens"; |
| 20 | import Ollama from "./llm/llms/Ollama"; |
| 21 | import { createNewPromptFileV2 } from "./promptFiles/v2/createNewPromptFile"; |
| 22 | import { callTool } from "./tools/callTool"; |
| 23 | import { ChatDescriber } from "./util/chatDescriber"; |
| 24 | import { clipboardCache } from "./util/clipboardCache"; |
| 25 | import { GlobalContext } from "./util/GlobalContext"; |
| 26 | import historyManager from "./util/history"; |
| 27 | import { editConfigFile, migrateV1DevDataFiles } from "./util/paths"; |
| 28 | import { Telemetry } from "./util/posthog"; |
| 29 | import { |
| 30 | isProcessBackgrounded, |
| 31 | markProcessAsBackgrounded, |
| 32 | } from "./util/processTerminalBackgroundStates"; |
| 33 | import { getSymbolsForManyFiles } from "./util/treeSitter"; |
| 34 | import { TTS } from "./util/tts"; |
| 35 | |
| 36 | import { |
| 37 | CompleteOnboardingPayload, |
| 38 | ContextItemWithId, |
| 39 | IdeSettings, |
| 40 | ModelDescription, |
| 41 | RangeInFile, |
| 42 | type ContextItem, |
| 43 | type ContextItemId, |
| 44 | type IDE, |
| 45 | } from "."; |
| 46 | |
| 47 | import { ConfigYaml } from "@continuedev/config-yaml"; |
| 48 | import { getDiffFn, GitDiffCache } from "./autocomplete/snippets/gitDiffCache"; |
| 49 | import { isLocalAssistantFile } from "./config/loadLocalAssistants"; |
| 50 | import { |
| 51 | setupLocalConfig, |
| 52 | setupProviderConfig, |
| 53 | setupQuickstartConfig, |
| 54 | } from "./config/onboarding"; |
| 55 | import { createNewWorkspaceBlockFile } from "./config/workspace/workspaceBlocks"; |
| 56 | import { MCPManagerSingleton } from "./context/mcp/MCPManagerSingleton"; |
| 57 | import { setMdmLicenseKey } from "./control-plane/mdm/mdm"; |
| 58 | import { streamDiffLines } from "./edit/streamDiffLines"; |
| 59 | import { shouldIgnore } from "./indexing/shouldIgnore"; |
| 60 | import { walkDirCache } from "./indexing/walkDir"; |
| 61 | import { LLMLogger } from "./llm/logger"; |
| 62 | import { llmStreamChat } from "./llm/streamChat"; |
| 63 | import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; |
| 64 | import { OnboardingModes } from "./protocol/core"; |
| 65 | import type { IMessenger, Message } from "./protocol/messenger"; |
| 66 | import { StreamAbortManager } from "./util/abortManager"; |
| 67 | |
| 68 | export class Core { |
| 69 | configHandler: ConfigHandler; |
| 70 | codeBaseIndexer: CodebaseIndexer; |
| 71 | completionProvider: CompletionProvider; |
| 72 | private docsService: DocsService; |
| 73 | private globalContext = new GlobalContext(); |
| 74 | llmLogger = new LLMLogger(); |
| 75 | |
| 76 | private messageAbortControllers = new Map<string, AbortController>(); |
| 77 | private addMessageAbortController(id: string): AbortController { |
| 78 | const controller = new AbortController(); |
| 79 | this.messageAbortControllers.set(id, controller); |
| 80 | controller.signal.addEventListener("abort", () => { |
| 81 | this.messageAbortControllers.delete(id); |
| 82 | }); |
| 83 | return controller; |
| 84 | } |
| 85 | private abortById(messageId: string) { |
| 86 | this.messageAbortControllers.get(messageId)?.abort(); |
| 87 | } |
| 88 | |
| 89 | invoke<T extends keyof ToCoreProtocol>( |
| 90 | messageType: T, |
| 91 | data: ToCoreProtocol[T][0], |
| 92 | ): ToCoreProtocol[T][1] { |
| 93 | return this.messenger.invoke(messageType, data); |
| 94 | } |
| 95 | |
| 96 | send<T extends keyof FromCoreProtocol>( |
| 97 | messageType: T, |
| 98 | data: FromCoreProtocol[T][0], |
| 99 | messageId?: string, |
| 100 | ): string { |
| 101 | return this.messenger.send(messageType, data, messageId); |
| 102 | } |
| 103 | |
| 104 | // TODO: It shouldn't actually need an IDE type, because this can happen |
| 105 | // through the messenger (it does in the case of any non-VS Code IDEs already) |
| 106 | constructor( |
| 107 | private readonly messenger: IMessenger<ToCoreProtocol, FromCoreProtocol>, |
| 108 | private readonly ide: IDE, |
| 109 | ) { |
| 110 | // Ensure .continue directory is created |
| 111 | migrateV1DevDataFiles(); |
| 112 | |
| 113 | const ideInfoPromise = messenger.request("getIdeInfo", undefined); |
| 114 | const ideSettingsPromise = messenger.request("getIdeSettings", undefined); |
| 115 | const sessionInfoPromise = messenger.request("getControlPlaneSessionInfo", { |
| 116 | silent: true, |
| 117 | useOnboarding: false, |
| 118 | }); |
| 119 | |
| 120 | this.configHandler = new ConfigHandler( |
| 121 | this.ide, |
| 122 | ideSettingsPromise, |
| 123 | this.llmLogger, |
| 124 | sessionInfoPromise, |
| 125 | ); |
| 126 | |
| 127 | this.docsService = DocsService.createSingleton( |
| 128 | this.configHandler, |
| 129 | this.ide, |
| 130 | this.messenger, |
| 131 | ); |
| 132 | |
| 133 | MCPManagerSingleton.getInstance().onConnectionsRefreshed = async () => { |
| 134 | await this.configHandler.reloadConfig(); |
| 135 | }; |
| 136 | |
| 137 | this.codeBaseIndexer = new CodebaseIndexer( |
| 138 | this.configHandler, |
| 139 | this.ide, |
| 140 | this.messenger, |
| 141 | this.globalContext.get("indexingPaused"), |
| 142 | ); |
| 143 | |
| 144 | this.configHandler.onConfigUpdate(async (result) => { |
| 145 | const serializedResult = await this.configHandler.getSerializedConfig(); |
| 146 | this.messenger.send("configUpdate", { |
| 147 | result: serializedResult, |
| 148 | profileId: |
| 149 | this.configHandler.currentProfile?.profileDescription.id || null, |
| 150 | organizations: this.configHandler.getSerializedOrgs(), |
| 151 | selectedOrgId: this.configHandler.currentOrg.id, |
| 152 | }); |
| 153 | |
| 154 | // update additional submenu context providers registered via VSCode API |
| 155 | const additionalProviders = |
| 156 | this.configHandler.getAdditionalSubmenuContextProviders(); |
| 157 | if (additionalProviders.length > 0) { |
| 158 | this.messenger.send("refreshSubmenuItems", { |
| 159 | providers: additionalProviders, |
| 160 | }); |
| 161 | } |
| 162 | }); |
| 163 | |
| 164 | // Dev Data Logger |
| 165 | const dataLogger = DataLogger.getInstance(); |
| 166 | dataLogger.core = this; |
| 167 | dataLogger.ideInfoPromise = ideInfoPromise; |
| 168 | dataLogger.ideSettingsPromise = ideSettingsPromise; |
| 169 | |
| 170 | void ideSettingsPromise.then((ideSettings) => { |
| 171 | const continueServerClient = new ContinueServerClient( |
| 172 | ideSettings.remoteConfigServerUrl, |
| 173 | ideSettings.userToken, |
| 174 | ); |
| 175 | |
| 176 | // Index on initialization |
| 177 | void this.ide.getWorkspaceDirs().then(async (dirs) => { |
| 178 | // Respect pauseCodebaseIndexOnStart user settings |
| 179 | if (ideSettings.pauseCodebaseIndexOnStart) { |
| 180 | this.codeBaseIndexer.paused = true; |
| 181 | void this.messenger.request("indexProgress", { |
| 182 | progress: 0, |
| 183 | desc: "Initial Indexing Skipped", |
| 184 | status: "paused", |
| 185 | }); |
| 186 | return; |
| 187 | } |
| 188 | |
| 189 | void this.codeBaseIndexer.refreshCodebaseIndex(dirs); |
| 190 | }); |
| 191 | }); |
| 192 | |
| 193 | const getLlm = async () => { |
| 194 | const { config } = await this.configHandler.loadConfig(); |
| 195 | if (!config) { |
| 196 | return undefined; |
| 197 | } |
| 198 | return config.selectedModelByRole.autocomplete ?? undefined; |
| 199 | }; |
| 200 | this.completionProvider = new CompletionProvider( |
| 201 | this.configHandler, |
| 202 | ide, |
| 203 | getLlm, |
| 204 | (e) => {}, |
| 205 | (..._) => Promise.resolve([]), |
| 206 | ); |
| 207 | |
| 208 | this.registerMessageHandlers(ideSettingsPromise); |
| 209 | } |
| 210 | |
| 211 | /* eslint-disable max-lines-per-function */ |
| 212 | private registerMessageHandlers(ideSettingsPromise: Promise<IdeSettings>) { |
| 213 | const on = this.messenger.on.bind(this.messenger); |
| 214 | |
| 215 | // Note, VsCode's in-process messenger doesn't do anything with this |
| 216 | // It will only show for jetbrains |
| 217 | this.messenger.onError((message, err) => { |
| 218 | void Telemetry.capture("core_messenger_error", { |
| 219 | message: err.message, |
| 220 | stack: err.stack, |
| 221 | }); |
| 222 | |
| 223 | // just to prevent duplicate error messages in jetbrains (same logic in webview protocol) |
| 224 | if ( |
| 225 | ["llm/streamChat", "chatDescriber/describe"].includes( |
| 226 | message.messageType, |
| 227 | ) |
| 228 | ) { |
| 229 | return; |
| 230 | } else { |
| 231 | void this.ide.showToast("error", err.message); |
| 232 | } |
| 233 | }); |
| 234 | |
| 235 | on("abort", (msg) => { |
| 236 | this.abortById(msg.data ?? msg.messageId); |
| 237 | }); |
| 238 | |
| 239 | on("ping", (msg) => { |
| 240 | if (msg.data !== "ping") { |
| 241 | throw new Error("ping message incorrect"); |
| 242 | } |
| 243 | return "pong"; |
| 244 | }); |
| 245 | |
| 246 | // History |
| 247 | on("history/list", (msg) => { |
| 248 | return historyManager.list(msg.data); |
| 249 | }); |
| 250 | |
| 251 | on("history/delete", (msg) => { |
| 252 | historyManager.delete(msg.data.id); |
| 253 | }); |
| 254 | |
| 255 | on("history/load", (msg) => { |
| 256 | return historyManager.load(msg.data.id); |
| 257 | }); |
| 258 | |
| 259 | on("history/save", (msg) => { |
| 260 | historyManager.save(msg.data); |
| 261 | }); |
| 262 | |
| 263 | on("history/clear", (msg) => { |
| 264 | historyManager.clearAll(); |
| 265 | }); |
| 266 | |
| 267 | on("devdata/log", async (msg) => { |
| 268 | void DataLogger.getInstance().logDevData(msg.data); |
| 269 | }); |
| 270 | |
| 271 | on("config/addModel", (msg) => { |
| 272 | const model = msg.data.model; |
| 273 | addModel(model, msg.data.role); |
| 274 | void this.configHandler.reloadConfig(); |
| 275 | }); |
| 276 | |
| 277 | on("config/deleteModel", (msg) => { |
| 278 | deleteModel(msg.data.title); |
| 279 | void this.configHandler.reloadConfig(); |
| 280 | }); |
| 281 | |
| 282 | on("config/newPromptFile", async (msg) => { |
| 283 | const { config } = await this.configHandler.loadConfig(); |
| 284 | await createNewPromptFileV2(this.ide, config?.experimental?.promptPath); |
| 285 | await this.configHandler.reloadConfig(); |
| 286 | }); |
| 287 | |
| 288 | on("config/addLocalWorkspaceBlock", async (msg) => { |
| 289 | await createNewWorkspaceBlockFile(this.ide, msg.data.blockType); |
| 290 | await this.configHandler.reloadConfig(); |
| 291 | }); |
| 292 | |
| 293 | on("config/openProfile", async (msg) => { |
| 294 | await this.configHandler.openConfigProfile(msg.data.profileId); |
| 295 | }); |
| 296 | |
| 297 | on("config/reload", async (msg) => { |
| 298 | void this.configHandler.reloadConfig(); |
| 299 | return await this.configHandler.getSerializedConfig(); |
| 300 | }); |
| 301 | |
| 302 | on("config/ideSettingsUpdate", async (msg) => { |
| 303 | await this.configHandler.updateIdeSettings(msg.data); |
| 304 | }); |
| 305 | |
| 306 | on("config/refreshProfiles", async (msg) => { |
| 307 | const { selectOrgId, selectProfileId } = msg.data ?? {}; |
| 308 | await this.configHandler.refreshAll(); |
| 309 | if (selectOrgId) { |
| 310 | await this.configHandler.setSelectedOrgId(selectOrgId, selectProfileId); |
| 311 | } else if (selectProfileId) { |
| 312 | await this.configHandler.setSelectedProfileId(selectProfileId); |
| 313 | } |
| 314 | }); |
| 315 | |
| 316 | on("config/updateSharedConfig", async (msg) => { |
| 317 | const newSharedConfig = this.globalContext.updateSharedConfig(msg.data); |
| 318 | await this.configHandler.reloadConfig(); |
| 319 | return newSharedConfig; |
| 320 | }); |
| 321 | |
| 322 | on("config/updateSelectedModel", async (msg) => { |
| 323 | const newSelectedModels = this.globalContext.updateSelectedModel( |
| 324 | msg.data.profileId, |
| 325 | msg.data.role, |
| 326 | msg.data.title, |
| 327 | ); |
| 328 | await this.configHandler.reloadConfig(); |
| 329 | return newSelectedModels; |
| 330 | }); |
| 331 | |
| 332 | on("controlPlane/openUrl", async (msg) => { |
| 333 | const env = await getControlPlaneEnv(this.ide.getIdeSettings()); |
| 334 | let url = `${env.APP_URL}${msg.data.path}`; |
| 335 | if (msg.data.orgSlug) { |
| 336 | url += `?org=${msg.data.orgSlug}`; |
| 337 | } |
| 338 | await this.messenger.request("openUrl", url); |
| 339 | }); |
| 340 | |
| 341 | on("controlPlane/getFreeTrialStatus", async (msg) => { |
| 342 | return this.configHandler.controlPlaneClient.getFreeTrialStatus(); |
| 343 | }); |
| 344 | |
| 345 | on("mcp/reloadServer", async (msg) => { |
| 346 | await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id); |
| 347 | }); |
| 348 | // Context providers |
| 349 | on("context/addDocs", async (msg) => { |
| 350 | void this.docsService.indexAndAdd(msg.data); |
| 351 | }); |
| 352 | |
| 353 | on("context/removeDocs", async (msg) => { |
| 354 | await this.docsService.delete(msg.data.startUrl); |
| 355 | }); |
| 356 | |
| 357 | on("context/indexDocs", async (msg) => { |
| 358 | await this.docsService.syncDocsWithPrompt(msg.data.reIndex); |
| 359 | }); |
| 360 | |
| 361 | on("context/loadSubmenuItems", async (msg) => { |
| 362 | const { config } = await this.configHandler.loadConfig(); |
| 363 | if (!config) { |
| 364 | return []; |
| 365 | } |
| 366 | |
| 367 | try { |
| 368 | const items = await config.contextProviders |
| 369 | ?.find((provider) => provider.description.title === msg.data.title) |
| 370 | ?.loadSubmenuItems({ |
| 371 | config, |
| 372 | ide: this.ide, |
| 373 | fetch: (url, init) => |
| 374 | fetchwithRequestOptions(url, init, config.requestOptions), |
| 375 | }); |
| 376 | return items || []; |
| 377 | } catch (e) { |
| 378 | console.error(e); |
| 379 | return []; |
| 380 | } |
| 381 | }); |
| 382 | |
| 383 | on("context/getContextItems", this.getContextItems.bind(this)); |
| 384 | |
| 385 | on("context/getSymbolsForFiles", async (msg) => { |
| 386 | const { uris } = msg.data; |
| 387 | return await getSymbolsForManyFiles(uris, this.ide); |
| 388 | }); |
| 389 | |
| 390 | on("config/getSerializedProfileInfo", async (msg) => { |
| 391 | return { |
| 392 | result: await this.configHandler.getSerializedConfig(), |
| 393 | profileId: |
| 394 | this.configHandler.currentProfile?.profileDescription.id ?? null, |
| 395 | organizations: this.configHandler.getSerializedOrgs(), |
| 396 | selectedOrgId: this.configHandler.currentOrg.id, |
| 397 | }; |
| 398 | }); |
| 399 | |
| 400 | on("clipboardCache/add", (msg) => { |
| 401 | const added = clipboardCache.add(uuidv4(), msg.data.content); |
| 402 | if (added) { |
| 403 | this.messenger.send("refreshSubmenuItems", { |
| 404 | providers: ["clipboard"], |
| 405 | }); |
| 406 | } |
| 407 | }); |
| 408 | |
| 409 | on("llm/streamChat", (msg) => { |
| 410 | const abortController = this.addMessageAbortController(msg.messageId); |
| 411 | return llmStreamChat( |
| 412 | this.configHandler, |
| 413 | abortController, |
| 414 | msg, |
| 415 | this.ide, |
| 416 | this.messenger, |
| 417 | ); |
| 418 | }); |
| 419 | |
| 420 | on("llm/complete", async (msg) => { |
| 421 | const { config } = await this.configHandler.loadConfig(); |
| 422 | const model = config?.selectedModelByRole.chat; |
| 423 | if (!model) { |
| 424 | throw new Error("No chat model selected"); |
| 425 | } |
| 426 | const abortController = this.addMessageAbortController(msg.messageId); |
| 427 | |
| 428 | const completion = await model.complete( |
| 429 | msg.data.prompt, |
| 430 | abortController.signal, |
| 431 | msg.data.completionOptions, |
| 432 | ); |
| 433 | return completion; |
| 434 | }); |
| 435 | on("llm/listModels", this.handleListModels.bind(this)); |
| 436 | |
| 437 | // Provide messenger to utils so they can interact with GUI + state |
| 438 | TTS.messenger = this.messenger; |
| 439 | ChatDescriber.messenger = this.messenger; |
| 440 | |
| 441 | on("tts/kill", async () => { |
| 442 | void TTS.kill(); |
| 443 | }); |
| 444 | |
| 445 | on("chatDescriber/describe", async (msg) => { |
| 446 | const currentModel = (await this.configHandler.loadConfig()).config |
| 447 | ?.selectedModelByRole.chat; |
| 448 | |
| 449 | if (!currentModel) { |
| 450 | throw new Error("No chat model selected"); |
| 451 | } |
| 452 | |
| 453 | return await ChatDescriber.describe(currentModel, {}, msg.data.text); |
| 454 | }); |
| 455 | |
| 456 | // Autocomplete |
| 457 | on("autocomplete/complete", async (msg) => { |
| 458 | const outcome = |
| 459 | await this.completionProvider.provideInlineCompletionItems( |
| 460 | msg.data, |
| 461 | undefined, |
| 462 | ); |
| 463 | return outcome ? [outcome.completion] : []; |
| 464 | }); |
| 465 | on("autocomplete/accept", async (msg) => { |
| 466 | this.completionProvider.accept(msg.data.completionId); |
| 467 | }); |
| 468 | on("autocomplete/cancel", async (msg) => { |
| 469 | this.completionProvider.cancel(); |
| 470 | }); |
| 471 | |
| 472 | on("streamDiffLines", async (msg) => { |
| 473 | const { config } = await this.configHandler.loadConfig(); |
| 474 | if (!config) { |
| 475 | throw new Error("Failed to load config"); |
| 476 | } |
| 477 | |
| 478 | const { data } = msg; |
| 479 | |
| 480 | // Title can be an edit, chat, or apply model |
| 481 | // Fall back to chat |
| 482 | const llm = |
| 483 | config.modelsByRole.edit.find((m) => m.title === data.modelTitle) ?? |
| 484 | config.modelsByRole.apply.find((m) => m.title === data.modelTitle) ?? |
| 485 | config.modelsByRole.chat.find((m) => m.title === data.modelTitle) ?? |
| 486 | config.selectedModelByRole.chat; |
| 487 | |
| 488 | if (!llm) { |
| 489 | throw new Error("No model selected"); |
| 490 | } |
| 491 | |
| 492 | return streamDiffLines({ |
| 493 | highlighted: data.highlighted, |
| 494 | prefix: data.prefix, |
| 495 | suffix: data.suffix, |
| 496 | llm, |
| 497 | // rules included for edit, NOT apply |
| 498 | rulesToInclude: data.includeRulesInSystemMessage |
| 499 | ? config.rules |
| 500 | : undefined, |
| 501 | input: data.input, |
| 502 | language: data.language, |
| 503 | onlyOneInsertion: false, |
| 504 | overridePrompt: undefined, |
| 505 | abortControllerId: data.fileUri ?? "current-file-stream", // not super important since currently cancelling apply will cancel all streams it's one file at a time |
| 506 | }); |
| 507 | }); |
| 508 | |
| 509 | on("cancelApply", async (msg) => { |
| 510 | const abortManager = StreamAbortManager.getInstance(); |
| 511 | abortManager.clear(); |
| 512 | }); |
| 513 | |
| 514 | on("onboarding/complete", this.handleCompleteOnboarding.bind(this)); |
| 515 | |
| 516 | on("addAutocompleteModel", this.handleAddAutocompleteModel.bind(this)); |
| 517 | |
| 518 | on("stats/getTokensPerDay", async (msg) => { |
| 519 | const rows = await DevDataSqliteDb.getTokensPerDay(); |
| 520 | return rows; |
| 521 | }); |
| 522 | on("stats/getTokensPerModel", async (msg) => { |
| 523 | const rows = await DevDataSqliteDb.getTokensPerModel(); |
| 524 | return rows; |
| 525 | }); |
| 526 | |
| 527 | on("index/forceReIndex", async ({ data }) => { |
| 528 | const { config } = await this.configHandler.loadConfig(); |
| 529 | if (!config || config.disableIndexing) { |
| 530 | return; // TODO silent in case of commands? |
| 531 | } |
| 532 | walkDirCache.invalidate(); |
| 533 | if (data?.shouldClearIndexes) { |
| 534 | await this.codeBaseIndexer.clearIndexes(); |
| 535 | } |
| 536 | |
| 537 | const dirs = data?.dirs ?? (await this.ide.getWorkspaceDirs()); |
| 538 | await this.codeBaseIndexer.refreshCodebaseIndex(dirs); |
| 539 | }); |
| 540 | on("index/setPaused", (msg) => { |
| 541 | this.globalContext.update("indexingPaused", msg.data); |
| 542 | // Update using the new setter instead of token |
| 543 | this.codeBaseIndexer.paused = msg.data; |
| 544 | }); |
| 545 | on("index/indexingProgressBarInitialized", async (msg) => { |
| 546 | // Triggered when progress bar is initialized. |
| 547 | // If a non-default state has been stored, update the indexing display to that state |
| 548 | const currentState = this.codeBaseIndexer.currentIndexingState; |
| 549 | |
| 550 | if (currentState.status !== "loading") { |
| 551 | void this.messenger.request("indexProgress", currentState); |
| 552 | } |
| 553 | }); |
| 554 | |
| 555 | // File changes - TODO - remove remaining logic for these from IDEs where possible |
| 556 | on("files/changed", this.handleFilesChanged.bind(this)); |
| 557 | const refreshIfNotIgnored = async (uris: string[]) => { |
| 558 | const toRefresh: string[] = []; |
| 559 | for (const uri of uris) { |
| 560 | const ignore = await shouldIgnore(uri, this.ide); |
| 561 | if (!ignore) { |
| 562 | toRefresh.push(uri); |
| 563 | } |
| 564 | } |
| 565 | if (toRefresh.length > 0) { |
| 566 | this.messenger.send("refreshSubmenuItems", { |
| 567 | providers: ["file"], |
| 568 | }); |
| 569 | const { config } = await this.configHandler.loadConfig(); |
| 570 | if (config && !config.disableIndexing) { |
| 571 | await this.codeBaseIndexer.refreshCodebaseIndexFiles(toRefresh); |
| 572 | } |
| 573 | } |
| 574 | }; |
| 575 | |
| 576 | on("files/created", async ({ data }) => { |
| 577 | if (data?.uris?.length) { |
| 578 | walkDirCache.invalidate(); |
| 579 | void refreshIfNotIgnored(data.uris); |
| 580 | |
| 581 | // Check for rules.md files being created |
| 582 | let rulesFileCreated = false; |
| 583 | for (const uri of data.uris) { |
| 584 | const parts = uri.split("/"); |
| 585 | const filename = parts[parts.length - 1]; |
| 586 | if (filename === "rules.md") { |
| 587 | rulesFileCreated = true; |
| 588 | break; |
| 589 | } |
| 590 | } |
| 591 | if (rulesFileCreated) { |
| 592 | await this.configHandler.reloadConfig(); |
| 593 | } |
| 594 | |
| 595 | // If it's a local assistant being created, we want to reload all assistants so it shows up in the list |
| 596 | let localAssistantCreated = false; |
| 597 | for (const uri of data.uris) { |
| 598 | if (isLocalAssistantFile(uri)) { |
| 599 | localAssistantCreated = true; |
| 600 | } |
| 601 | } |
| 602 | if (localAssistantCreated) { |
| 603 | await this.configHandler.refreshAll(); |
| 604 | } |
| 605 | } |
| 606 | }); |
| 607 | |
| 608 | on("files/deleted", async ({ data }) => { |
| 609 | if (data?.uris?.length) { |
| 610 | walkDirCache.invalidate(); |
| 611 | void refreshIfNotIgnored(data.uris); |
| 612 | |
| 613 | // Check for rules.md files being deleted |
| 614 | let rulesFileDeleted = false; |
| 615 | for (const uri of data.uris) { |
| 616 | const parts = uri.split("/"); |
| 617 | const filename = parts[parts.length - 1]; |
| 618 | if (filename === "rules.md") { |
| 619 | rulesFileDeleted = true; |
| 620 | break; |
| 621 | } |
| 622 | } |
| 623 | if (rulesFileDeleted) { |
| 624 | await this.configHandler.reloadConfig(); |
| 625 | } |
| 626 | } |
| 627 | }); |
| 628 | |
| 629 | on("files/closed", async ({ data }) => { |
| 630 | if (data.uris) { |
| 631 | this.messenger.send("didCloseFiles", { |
| 632 | uris: data.uris, |
| 633 | }); |
| 634 | } |
| 635 | }); |
| 636 | |
| 637 | on("files/opened", async () => {}); |
| 638 | |
| 639 | // Docs, etc. indexing |
| 640 | on("indexing/reindex", async (msg) => { |
| 641 | if (msg.data.type === "docs") { |
| 642 | void this.docsService.reindexDoc(msg.data.id); |
| 643 | } |
| 644 | }); |
| 645 | on("indexing/abort", async (msg) => { |
| 646 | if (msg.data.type === "docs") { |
| 647 | this.docsService.abort(msg.data.id); |
| 648 | } |
| 649 | }); |
| 650 | on("indexing/setPaused", async (msg) => { |
| 651 | if (msg.data.type === "docs") { |
| 652 | } |
| 653 | }); |
| 654 | on("docs/initStatuses", async (msg) => { |
| 655 | void this.docsService.initStatuses(); |
| 656 | }); |
| 657 | on("docs/getDetails", async (msg) => { |
| 658 | return await this.docsService.getDetails(msg.data.startUrl); |
| 659 | }); |
| 660 | |
| 661 | on("didChangeSelectedProfile", async (msg) => { |
| 662 | if (msg.data.id) { |
| 663 | await this.configHandler.setSelectedProfileId(msg.data.id); |
| 664 | } |
| 665 | }); |
| 666 | |
| 667 | on("didChangeSelectedOrg", async (msg) => { |
| 668 | if (msg.data.id) { |
| 669 | await this.configHandler.setSelectedOrgId( |
| 670 | msg.data.id, |
| 671 | msg.data.profileId || undefined, |
| 672 | ); |
| 673 | } |
| 674 | }); |
| 675 | |
| 676 | on("didChangeControlPlaneSessionInfo", async (msg) => { |
| 677 | this.messenger.send("sessionUpdate", { |
| 678 | sessionInfo: msg.data.sessionInfo, |
| 679 | }); |
| 680 | await this.configHandler.updateControlPlaneSessionInfo( |
| 681 | msg.data.sessionInfo, |
| 682 | ); |
| 683 | }); |
| 684 | |
| 685 | on("auth/getAuthUrl", async (msg) => { |
| 686 | const url = await getAuthUrlForTokenPage( |
| 687 | ideSettingsPromise, |
| 688 | msg.data.useOnboarding, |
| 689 | ); |
| 690 | return { url }; |
| 691 | }); |
| 692 | |
| 693 | on("didChangeActiveTextEditor", async ({ data: { filepath } }) => { |
| 694 | try { |
| 695 | const ignore = await shouldIgnore(filepath, this.ide); |
| 696 | if (!ignore) { |
| 697 | recentlyEditedFilesCache.set(filepath, filepath); |
| 698 | } |
| 699 | } catch (e) { |
| 700 | console.error( |
| 701 | `didChangeActiveTextEditor: failed to update recentlyEditedFiles cache for ${filepath}`, |
| 702 | ); |
| 703 | } |
| 704 | }); |
| 705 | |
| 706 | on("tools/call", async ({ data: { toolCall } }) => { |
| 707 | const { config } = await this.configHandler.loadConfig(); |
| 708 | if (!config) { |
| 709 | throw new Error("Config not loaded"); |
| 710 | } |
| 711 | |
| 712 | const tool = config.tools.find( |
| 713 | (t) => t.function.name === toolCall.function.name, |
| 714 | ); |
| 715 | |
| 716 | if (!tool) { |
| 717 | throw new Error(`Tool ${toolCall.function.name} not found`); |
| 718 | } |
| 719 | |
| 720 | if (!config.selectedModelByRole.chat) { |
| 721 | throw new Error("No chat model selected"); |
| 722 | } |
| 723 | |
| 724 | // Define a callback for streaming output updates |
| 725 | const onPartialOutput = (params: { |
| 726 | toolCallId: string; |
| 727 | contextItems: ContextItem[]; |
| 728 | }) => { |
| 729 | this.messenger.send("toolCallPartialOutput", params); |
| 730 | }; |
| 731 | |
| 732 | return await callTool(tool, toolCall, { |
| 733 | config, |
| 734 | ide: this.ide, |
| 735 | llm: config.selectedModelByRole.chat, |
| 736 | fetch: (url, init) => |
| 737 | fetchwithRequestOptions(url, init, config.requestOptions), |
| 738 | tool, |
| 739 | toolCallId: toolCall.id, |
| 740 | onPartialOutput, |
| 741 | }); |
| 742 | }); |
| 743 | |
| 744 | on("isItemTooBig", async ({ data: { item } }) => { |
| 745 | return this.isItemTooBig(item); |
| 746 | }); |
| 747 | |
| 748 | // Process state handlers |
| 749 | on("process/markAsBackgrounded", async ({ data: { toolCallId } }) => { |
| 750 | markProcessAsBackgrounded(toolCallId); |
| 751 | }); |
| 752 | |
| 753 | on( |
| 754 | "process/isBackgrounded", |
| 755 | async ({ data: { toolCallId }, messageId }) => { |
| 756 | const isBackgrounded = isProcessBackgrounded(toolCallId); |
| 757 | return isBackgrounded; // Return true to indicate the message was handled successfully |
| 758 | }, |
| 759 | ); |
| 760 | |
| 761 | on("mdm/setLicenseKey", ({ data: { licenseKey } }) => { |
| 762 | const isValid = setMdmLicenseKey(licenseKey); |
| 763 | return isValid; |
| 764 | }); |
| 765 | } |
| 766 | |
| 767 | private async isItemTooBig(item: ContextItemWithId) { |
| 768 | const { config } = await this.configHandler.loadConfig(); |
| 769 | if (!config) { |
| 770 | return false; |
| 771 | } |
| 772 | |
| 773 | const llm = config?.selectedModelByRole.chat; |
| 774 | if (!llm) { |
| 775 | throw new Error("No chat model selected"); |
| 776 | } |
| 777 | |
| 778 | const tokens = countTokens(item.content, llm.model); |
| 779 | |
| 780 | if (tokens > llm.contextLength - llm.completionOptions!.maxTokens!) { |
| 781 | return true; |
| 782 | } |
| 783 | |
| 784 | return false; |
| 785 | } |
| 786 | |
| 787 | private handleAddAutocompleteModel( |
| 788 | msg: Message<{ |
| 789 | model: ModelDescription; |
| 790 | }>, |
| 791 | ) { |
| 792 | const model = msg.data.model; |
| 793 | editConfigFile( |
| 794 | (config) => { |
| 795 | return { |
| 796 | ...config, |
| 797 | tabAutocompleteModel: model, |
| 798 | }; |
| 799 | }, |
| 800 | (config) => ({ |
| 801 | ...config, |
| 802 | models: [ |
| 803 | ...(config.models ?? []), |
| 804 | { |
| 805 | name: model.title, |
| 806 | provider: model.provider, |
| 807 | model: model.model, |
| 808 | apiKey: model.apiKey, |
| 809 | roles: ["autocomplete"], |
| 810 | apiBase: model.apiBase, |
| 811 | }, |
| 812 | ], |
| 813 | }), |
| 814 | ); |
| 815 | void this.configHandler.reloadConfig(); |
| 816 | } |
| 817 | |
| 818 | private async handleFilesChanged({ |
| 819 | data, |
| 820 | }: Message<{ |
| 821 | uris?: string[]; |
| 822 | }>): Promise<void> { |
| 823 | if (data?.uris?.length) { |
| 824 | const diffCache = GitDiffCache.getInstance(getDiffFn(this.ide)); |
| 825 | diffCache.invalidate(); |
| 826 | walkDirCache.invalidate(); // safe approach for now - TODO - only invalidate on relevant changes |
| 827 | for (const uri of data.uris) { |
| 828 | const currentProfileUri = |
| 829 | this.configHandler.currentProfile?.profileDescription.uri ?? ""; |
| 830 | |
| 831 | if (URI.equal(uri, currentProfileUri)) { |
| 832 | // Trigger a toast notification to provide UI feedback that config has been updated |
| 833 | const showToast = |
| 834 | this.globalContext.get("showConfigUpdateToast") ?? true; |
| 835 | if (showToast) { |
| 836 | const selection = await this.ide.showToast( |
| 837 | "info", |
| 838 | "Config updated", |
| 839 | "Don't show again", |
| 840 | ); |
| 841 | if (selection === "Don't show again") { |
| 842 | this.globalContext.update("showConfigUpdateToast", false); |
| 843 | } |
| 844 | } |
| 845 | await this.configHandler.reloadConfig(); |
| 846 | continue; |
| 847 | } |
| 848 | |
| 849 | if ( |
| 850 | uri.endsWith(".continuerc.json") || |
| 851 | uri.endsWith(".prompt") || |
| 852 | uri.endsWith(SYSTEM_PROMPT_DOT_FILE) || |
| 853 | (uri.includes(".continue") && uri.endsWith(".yaml")) || |
| 854 | uri.endsWith("rules.md") // Add check for rules.md files |
| 855 | ) { |
| 856 | await this.configHandler.reloadConfig(); |
| 857 | } else if ( |
| 858 | uri.endsWith(".continueignore") || |
| 859 | uri.endsWith(".gitignore") |
| 860 | ) { |
| 861 | // Reindex the workspaces |
| 862 | this.invoke("index/forceReIndex", { |
| 863 | shouldClearIndexes: true, |
| 864 | }); |
| 865 | } else { |
| 866 | const { config } = await this.configHandler.loadConfig(); |
| 867 | if (config && !config.disableIndexing) { |
| 868 | // Reindex the file |
| 869 | const ignore = await shouldIgnore(uri, this.ide); |
| 870 | if (!ignore) { |
| 871 | await this.codeBaseIndexer.refreshCodebaseIndexFiles([uri]); |
| 872 | } |
| 873 | } |
| 874 | } |
| 875 | } |
| 876 | } |
| 877 | } |
| 878 | |
| 879 | private async handleListModels(msg: Message<{ title: string }>) { |
| 880 | const { config } = await this.configHandler.loadConfig(); |
| 881 | if (!config) { |
| 882 | return []; |
| 883 | } |
| 884 | |
| 885 | const model = |
| 886 | config.modelsByRole.chat.find( |
| 887 | (model) => model.title === msg.data.title, |
| 888 | ) ?? |
| 889 | config.modelsByRole.chat.find((model) => |
| 890 | model.title?.startsWith(msg.data.title), |
| 891 | ); |
| 892 | |
| 893 | try { |
| 894 | if (model) { |
| 895 | return await model.listModels(); |
| 896 | } else { |
| 897 | if (msg.data.title === "Ollama") { |
| 898 | const models = await new Ollama({ model: "" }).listModels(); |
| 899 | return models; |
| 900 | } else { |
| 901 | return undefined; |
| 902 | } |
| 903 | } |
| 904 | } catch (e) { |
| 905 | console.debug(`Error listing Ollama models: ${e}`); |
| 906 | return undefined; |
| 907 | } |
| 908 | } |
| 909 | |
| 910 | private async handleCompleteOnboarding( |
| 911 | msg: Message<CompleteOnboardingPayload>, |
| 912 | ) { |
| 913 | const { mode, provider, apiKey } = msg.data; |
| 914 | |
| 915 | let editConfigYamlCallback: (config: ConfigYaml) => ConfigYaml; |
| 916 | |
| 917 | switch (mode) { |
| 918 | case OnboardingModes.LOCAL: |
| 919 | editConfigYamlCallback = setupLocalConfig; |
| 920 | break; |
| 921 | |
| 922 | case OnboardingModes.API_KEY: |
| 923 | if (provider && apiKey) { |
| 924 | editConfigYamlCallback = (config: ConfigYaml) => |
| 925 | setupProviderConfig(config, provider, apiKey); |
| 926 | } else { |
| 927 | editConfigYamlCallback = setupQuickstartConfig; |
| 928 | } |
| 929 | break; |
| 930 | |
| 931 | default: |
| 932 | console.error(`Invalid mode: ${mode}`); |
| 933 | editConfigYamlCallback = (config) => config; |
| 934 | } |
| 935 | |
| 936 | editConfigFile((c) => c, editConfigYamlCallback); |
| 937 | |
| 938 | void this.configHandler.reloadConfig(); |
| 939 | } |
| 940 | |
| 941 | private getContextItems = async ( |
| 942 | msg: Message<{ |
| 943 | name: string; |
| 944 | query: string; |
| 945 | fullInput: string; |
| 946 | selectedCode: RangeInFile[]; |
| 947 | }>, |
| 948 | ) => { |
| 949 | const { config } = await this.configHandler.loadConfig(); |
| 950 | if (!config) { |
| 951 | return []; |
| 952 | } |
| 953 | |
| 954 | const { name, query, fullInput, selectedCode } = msg.data; |
| 955 | |
| 956 | const llm = (await this.configHandler.loadConfig()).config |
| 957 | ?.selectedModelByRole.chat; |
| 958 | |
| 959 | if (!llm) { |
| 960 | throw new Error("No chat model selected"); |
| 961 | } |
| 962 | |
| 963 | const provider = |
| 964 | config.contextProviders?.find( |
| 965 | (provider) => provider.description.title === name, |
| 966 | ) ?? |
| 967 | [ |
| 968 | // user doesn't need these in their config.json for the shortcuts to work |
| 969 | // option+enter |
| 970 | new CurrentFileContextProvider({}), |
| 971 | // cmd+enter |
| 972 | new CodebaseContextProvider({}), |
| 973 | ].find((provider) => provider.description.title === name); |
| 974 | if (!provider) { |
| 975 | return []; |
| 976 | } |
| 977 | |
| 978 | try { |
| 979 | const id: ContextItemId = { |
| 980 | providerTitle: provider.description.title, |
| 981 | itemId: uuidv4(), |
| 982 | }; |
| 983 | |
| 984 | const items = await provider.getContextItems(query, { |
| 985 | config, |
| 986 | llm, |
| 987 | embeddingsProvider: config.selectedModelByRole.embed, |
| 988 | fullInput, |
| 989 | ide: this.ide, |
| 990 | selectedCode, |
| 991 | reranker: config.selectedModelByRole.rerank, |
| 992 | fetch: (url, init) => |
| 993 | fetchwithRequestOptions(url, init, config.requestOptions), |
| 994 | }); |
| 995 | |
| 996 | void Telemetry.capture( |
| 997 | "useContextProvider", |
| 998 | { |
| 999 | name: provider.description.title, |
| 1000 | }, |
| 1001 | true, |
| 1002 | ); |
| 1003 | |
| 1004 | return items.map((item) => ({ |
| 1005 | ...item, |
| 1006 | id, |
| 1007 | })); |
| 1008 | } catch (e) { |
| 1009 | let knownError = false; |
| 1010 | |
| 1011 | if (e instanceof Error) { |
| 1012 | // After removing transformers JS embeddings provider from jetbrains |
| 1013 | // Should no longer see this error |
| 1014 | // if (e.message.toLowerCase().includes("embeddings provider")) { |
| 1015 | // knownError = true; |
| 1016 | // const toastOption = "See Docs"; |
| 1017 | // void this.ide |
| 1018 | // .showToast( |
| 1019 | // "error", |
| 1020 | // `Set up an embeddings model to use @${name}`, |
| 1021 | // toastOption, |
| 1022 | // ) |
| 1023 | // .then((userSelection) => { |
| 1024 | // if (userSelection === toastOption) { |
| 1025 | // void this.ide.openUrl( |
| 1026 | // "https://docs.continue.dev/customize/model-roles/embeddings", |
| 1027 | // ); |
| 1028 | // } |
| 1029 | // }); |
| 1030 | // } |
| 1031 | } |
| 1032 | if (!knownError) { |
| 1033 | void this.ide.showToast( |
| 1034 | "error", |
| 1035 | `Error getting context items from ${name}: ${e}`, |
| 1036 | ); |
| 1037 | } |
| 1038 | return []; |
| 1039 | } |
| 1040 | }; |
| 1041 | } |