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