Elffuss BraidHub

kikocis/continue public

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