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