Elffuss BraidHub

kikocis/continue public

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