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