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