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