Elffuss BraidHub

kikocis/continue public

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