Elffuss BraidHub

kikocis/continue public

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