Elffuss BraidHub

kikocis/continue public

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