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