Elffuss BraidHub

kikocis/continue public

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