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