Elffuss BraidHub

kikocis/continue public

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