Elffuss BraidHub

kikocis/continue public

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