Elffuss BraidHub

kikocis/continue public

35c0ed0a3308 · 35.5 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 ContextItemId,
42 ContextItemWithId,
43 IdeSettings,
44 ModelDescription,
45 Position,
46 RangeInFile,
47 ToolCall,
48 type ContextItem,
49 type IDE,
50} from ".";
51
52import { BLOCK_TYPES, ConfigYaml } from "@continuedev/config-yaml";
53import { getDiffFn, GitDiffCache } from "./autocomplete/snippets/gitDiffCache";
54import { stringifyMcpPrompt } from "./commands/slash/mcpSlashCommand";
55import { isLocalDefinitionFile } from "./config/loadLocalAssistants";
56import {
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 overridePrompt: undefined,
562 abortController,
563 });
564 });
565
566 on("cancelApply", async (msg) => {
567 const abortManager = ApplyAbortManager.getInstance();
568 abortManager.clear(); // for now abort all streams
569 });
570
571 on("onboarding/complete", this.handleCompleteOnboarding.bind(this));
572
573 on("addAutocompleteModel", this.handleAddAutocompleteModel.bind(this));
574
575 on("stats/getTokensPerDay", async (msg) => {
576 const rows = await DevDataSqliteDb.getTokensPerDay();
577 return rows;
578 });
579 on("stats/getTokensPerModel", async (msg) => {
580 const rows = await DevDataSqliteDb.getTokensPerModel();
581 return rows;
582 });
583
584 on("index/forceReIndex", async ({ data }) => {
585 const { config } = await this.configHandler.loadConfig();
586 if (!config || config.disableIndexing) {
587 return; // TODO silent in case of commands?
588 }
589 walkDirCache.invalidate();
590 if (data?.shouldClearIndexes) {
591 await this.codeBaseIndexer.clearIndexes();
592 }
593
594 const dirs = data?.dirs ?? (await this.ide.getWorkspaceDirs());
595 await this.codeBaseIndexer.refreshCodebaseIndex(dirs);
596 });
597 on("index/setPaused", (msg) => {
598 this.globalContext.update("indexingPaused", msg.data);
599 // Update using the new setter instead of token
600 this.codeBaseIndexer.paused = msg.data;
601 });
602 on("index/indexingProgressBarInitialized", async (msg) => {
603 // Triggered when progress bar is initialized.
604 // If a non-default state has been stored, update the indexing display to that state
605 const currentState = this.codeBaseIndexer.currentIndexingState;
606
607 if (currentState.status !== "loading") {
608 void this.messenger.request("indexProgress", currentState);
609 }
610 });
611
612 // File changes - TODO - remove remaining logic for these from IDEs where possible
613 on("files/changed", this.handleFilesChanged.bind(this));
614 const refreshIfNotIgnored = async (uris: string[]) => {
615 const toRefresh: string[] = [];
616 for (const uri of uris) {
617 const ignore = await shouldIgnore(uri, this.ide);
618 if (!ignore) {
619 toRefresh.push(uri);
620 }
621 }
622 if (toRefresh.length > 0) {
623 this.messenger.send("refreshSubmenuItems", {
624 providers: ["file"],
625 });
626 const { config } = await this.configHandler.loadConfig();
627 if (config && !config.disableIndexing) {
628 await this.codeBaseIndexer.refreshCodebaseIndexFiles(toRefresh);
629 }
630 }
631 };
632
633 on("files/created", async ({ data }) => {
634 if (data?.uris?.length) {
635 walkDirCache.invalidate();
636 void refreshIfNotIgnored(data.uris);
637
638 if (hasRulesFiles(data.uris)) {
639 await this.configHandler.reloadConfig();
640 }
641
642 // If it's a local assistant being created, we want to reload all assistants so it shows up in the list
643 let localAssistantCreated = false;
644 for (const uri of data.uris) {
645 if (isLocalDefinitionFile(uri)) {
646 localAssistantCreated = true;
647 }
648 }
649 if (localAssistantCreated) {
650 await this.configHandler.refreshAll();
651 }
652 }
653 });
654
655 on("files/deleted", async ({ data }) => {
656 if (data?.uris?.length) {
657 walkDirCache.invalidate();
658 void refreshIfNotIgnored(data.uris);
659
660 if (hasRulesFiles(data.uris)) {
661 await this.configHandler.reloadConfig();
662 }
663 }
664 });
665
666 on("files/closed", async ({ data }) => {
667 try {
668 const fileUris = await this.ide.getOpenFiles();
669 if (fileUris) {
670 const filepaths = fileUris.map((uri) => uri.toString());
671
672 if (!prevFilepaths.filepaths.length) {
673 prevFilepaths.filepaths = filepaths;
674 }
675
676 // If there is a removal, including if the number of tabs is the same (which can happen with temp tabs)
677 if (filepaths.length <= prevFilepaths.filepaths.length) {
678 // Remove files from cache that are no longer open (i.e. in the cache but not in the list of opened tabs)
679 for (const [key, _] of openedFilesLruCache.entriesDescending()) {
680 if (!filepaths.includes(key)) {
681 openedFilesLruCache.delete(key);
682 }
683 }
684 }
685 prevFilepaths.filepaths = filepaths;
686 }
687 } catch (e) {
688 console.error(
689 `didChangeVisibleTextEditors: failed to update openedFilesLruCache`,
690 );
691 }
692
693 if (data.uris) {
694 this.messenger.send("didCloseFiles", {
695 uris: data.uris,
696 });
697 }
698 });
699
700 on("files/opened", async ({ data: { uris } }) => {
701 if (uris) {
702 for (const filepath of uris) {
703 try {
704 const ignore = await shouldIgnore(filepath, this.ide);
705 if (!ignore) {
706 // Set the active file as most recently used (need to force recency update by deleting and re-adding)
707 if (openedFilesLruCache.has(filepath)) {
708 openedFilesLruCache.delete(filepath);
709 }
710 openedFilesLruCache.set(filepath, filepath);
711 }
712 } catch (e) {
713 console.error(
714 `files/opened: failed to update openedFiles cache for ${filepath}`,
715 );
716 }
717 }
718 }
719 });
720
721 on("files/smallEdit", async ({ data }) => {
722 const EDIT_AGGREGATION_OPTIONS = {
723 deltaT: 1.0,
724 deltaL: 5,
725 maxEdits: 500,
726 maxDuration: 120.0,
727 contextSize: 5,
728 };
729
730 EditAggregator.getInstance(
731 EDIT_AGGREGATION_OPTIONS,
732 (
733 beforeAfterdiff: BeforeAfterDiff,
734 cursorPosBeforeEdit: Position,
735 cursorPosAfterPrevEdit: Position,
736 ) => {
737 void processSmallEdit(
738 beforeAfterdiff,
739 cursorPosBeforeEdit,
740 cursorPosAfterPrevEdit,
741 data.configHandler,
742 data.getDefsFromLspFunction,
743 this.ide,
744 );
745 },
746 );
747
748 const workspaceDir =
749 data.actions.length > 0 ? data.actions[0].workspaceDir : undefined;
750
751 // Store the latest context data
752 const instance = EditAggregator.getInstance();
753 (instance as any).latestContextData = {
754 configHandler: data.configHandler,
755 getDefsFromLspFunction: data.getDefsFromLspFunction,
756 recentlyEditedRanges: data.recentlyEditedRanges,
757 recentlyVisitedRanges: data.recentlyVisitedRanges,
758 workspaceDir: workspaceDir,
759 };
760
761 // queueMicrotask prevents blocking the UI thread during typing
762 queueMicrotask(() => {
763 void EditAggregator.getInstance().processEdits(data.actions);
764 });
765 });
766
767 // Docs, etc. indexing
768 on("indexing/reindex", async (msg) => {
769 if (msg.data.type === "docs") {
770 void this.docsService.reindexDoc(msg.data.id);
771 }
772 });
773 on("indexing/abort", async (msg) => {
774 if (msg.data.type === "docs") {
775 this.docsService.abort(msg.data.id);
776 }
777 });
778 on("indexing/setPaused", async (msg) => {
779 if (msg.data.type === "docs") {
780 }
781 });
782 on("docs/initStatuses", async (msg) => {
783 void this.docsService.initStatuses();
784 });
785 on("docs/getDetails", async (msg) => {
786 return await this.docsService.getDetails(msg.data.startUrl);
787 });
788
789 on("didChangeSelectedProfile", async (msg) => {
790 if (msg.data.id) {
791 await this.configHandler.setSelectedProfileId(msg.data.id);
792 }
793 });
794
795 on("didChangeSelectedOrg", async (msg) => {
796 if (msg.data.id) {
797 await this.configHandler.setSelectedOrgId(
798 msg.data.id,
799 msg.data.profileId || undefined,
800 );
801 }
802 });
803
804 on("didChangeControlPlaneSessionInfo", async (msg) => {
805 this.messenger.send("sessionUpdate", {
806 sessionInfo: msg.data.sessionInfo,
807 });
808 await this.configHandler.updateControlPlaneSessionInfo(
809 msg.data.sessionInfo,
810 );
811 });
812
813 on("auth/getAuthUrl", async (msg) => {
814 const url = await getAuthUrlForTokenPage(
815 ideSettingsPromise,
816 msg.data.useOnboarding,
817 );
818 return { url };
819 });
820
821 on("tools/call", async ({ data: { toolCall } }) =>
822 this.handleToolCall(toolCall),
823 );
824
825 on("isItemTooBig", async ({ data: { item } }) => {
826 return this.isItemTooBig(item);
827 });
828
829 // Process state handlers
830 on("process/markAsBackgrounded", async ({ data: { toolCallId } }) => {
831 markProcessAsBackgrounded(toolCallId);
832 });
833
834 on(
835 "process/isBackgrounded",
836 async ({ data: { toolCallId }, messageId }) => {
837 const isBackgrounded = isProcessBackgrounded(toolCallId);
838 return isBackgrounded; // Return true to indicate the message was handled successfully
839 },
840 );
841
842 on("mdm/setLicenseKey", ({ data: { licenseKey } }) => {
843 const isValid = setMdmLicenseKey(licenseKey);
844 return isValid;
845 });
846 }
847
848 private async handleToolCall(toolCall: ToolCall) {
849 const { config } = await this.configHandler.loadConfig();
850 if (!config) {
851 throw new Error("Config not loaded");
852 }
853
854 const tool = config.tools.find(
855 (t) => t.function.name === toolCall.function.name,
856 );
857
858 if (!tool) {
859 throw new Error(`Tool ${toolCall.function.name} not found`);
860 }
861
862 if (!config.selectedModelByRole.chat) {
863 throw new Error("No chat model selected");
864 }
865
866 // Define a callback for streaming output updates
867 const onPartialOutput = (params: {
868 toolCallId: string;
869 contextItems: ContextItem[];
870 }) => {
871 this.messenger.send("toolCallPartialOutput", params);
872 };
873
874 const result = await callTool(tool, toolCall, {
875 config,
876 ide: this.ide,
877 llm: config.selectedModelByRole.chat,
878 fetch: (url, init) =>
879 fetchwithRequestOptions(url, init, config.requestOptions),
880 tool,
881 toolCallId: toolCall.id,
882 onPartialOutput,
883 codeBaseIndexer: this.codeBaseIndexer,
884 });
885
886 return result;
887 }
888
889 private async isItemTooBig(item: ContextItemWithId) {
890 const { config } = await this.configHandler.loadConfig();
891 if (!config) {
892 return false;
893 }
894
895 const llm = config?.selectedModelByRole.chat;
896 if (!llm) {
897 throw new Error("No chat model selected");
898 }
899
900 const tokens = countTokens(item.content, llm.model);
901
902 if (tokens > llm.contextLength - llm.completionOptions!.maxTokens!) {
903 return true;
904 }
905
906 return false;
907 }
908
909 private handleAddAutocompleteModel(
910 msg: Message<{
911 model: ModelDescription;
912 }>,
913 ) {
914 const model = msg.data.model;
915 editConfigFile(
916 (config) => {
917 return {
918 ...config,
919 tabAutocompleteModel: model,
920 };
921 },
922 (config) => ({
923 ...config,
924 models: [
925 ...(config.models ?? []),
926 {
927 name: model.title,
928 provider: model.provider,
929 model: model.model,
930 apiKey: model.apiKey,
931 roles: ["autocomplete"],
932 apiBase: model.apiBase,
933 },
934 ],
935 }),
936 );
937 void this.configHandler.reloadConfig();
938 }
939
940 private async handleFilesChanged({
941 data,
942 }: Message<{
943 uris?: string[];
944 }>): Promise<void> {
945 if (data?.uris?.length) {
946 const diffCache = GitDiffCache.getInstance(getDiffFn(this.ide));
947 diffCache.invalidate();
948 walkDirCache.invalidate(); // safe approach for now - TODO - only invalidate on relevant changes
949 for (const uri of data.uris) {
950 const currentProfileUri =
951 this.configHandler.currentProfile?.profileDescription.uri ?? "";
952
953 if (URI.equal(uri, currentProfileUri)) {
954 // Trigger a toast notification to provide UI feedback that config has been updated
955 const showToast =
956 this.globalContext.get("showConfigUpdateToast") ?? true;
957 if (showToast) {
958 const selection = await this.ide.showToast(
959 "info",
960 "Config updated",
961 "Don't show again",
962 );
963 if (selection === "Don't show again") {
964 this.globalContext.update("showConfigUpdateToast", false);
965 }
966 }
967 await this.configHandler.reloadConfig();
968 continue;
969 }
970
971 if (
972 uri.endsWith(".continuerc.json") ||
973 uri.endsWith(".prompt") ||
974 uri.endsWith(SYSTEM_PROMPT_DOT_FILE) ||
975 (uri.includes(".continue") && uri.endsWith(".yaml")) ||
976 uri.endsWith(RULES_MARKDOWN_FILENAME) ||
977 BLOCK_TYPES.some(
978 (blockType) =>
979 uri.includes(`.continue/${blockType}`) ||
980 uri.includes(`.continue\\${blockType}`),
981 )
982 ) {
983 await this.configHandler.reloadConfig();
984 } else if (
985 uri.endsWith(".continueignore") ||
986 uri.endsWith(".gitignore")
987 ) {
988 // Reindex the workspaces
989 this.invoke("index/forceReIndex", {
990 shouldClearIndexes: true,
991 });
992 } else {
993 const { config } = await this.configHandler.loadConfig();
994 if (config && !config.disableIndexing) {
995 // Reindex the file
996 const ignore = await shouldIgnore(uri, this.ide);
997 if (!ignore) {
998 await this.codeBaseIndexer.refreshCodebaseIndexFiles([uri]);
999 }
1000 }
1001 }
1002 }
1003 }
1004 }
1005
1006 private async handleListModels(msg: Message<{ title: string }>) {
1007 const { config } = await this.configHandler.loadConfig();
1008 if (!config) {
1009 return [];
1010 }
1011
1012 const model =
1013 config.modelsByRole.chat.find(
1014 (model) => model.title === msg.data.title,
1015 ) ??
1016 config.modelsByRole.chat.find((model) =>
1017 model.title?.startsWith(msg.data.title),
1018 );
1019
1020 try {
1021 if (model) {
1022 return await model.listModels();
1023 } else {
1024 if (msg.data.title === "Ollama") {
1025 const models = await new Ollama({ model: "" }).listModels();
1026 return models;
1027 } else {
1028 return undefined;
1029 }
1030 }
1031 } catch (e) {
1032 console.debug(`Error listing Ollama models: ${e}`);
1033 return undefined;
1034 }
1035 }
1036
1037 private async handleCompleteOnboarding(
1038 msg: Message<CompleteOnboardingPayload>,
1039 ) {
1040 const { mode, provider, apiKey } = msg.data;
1041
1042 let editConfigYamlCallback: (config: ConfigYaml) => ConfigYaml;
1043
1044 switch (mode) {
1045 case OnboardingModes.LOCAL:
1046 editConfigYamlCallback = setupLocalConfig;
1047 break;
1048
1049 case OnboardingModes.API_KEY:
1050 if (provider && apiKey) {
1051 editConfigYamlCallback = (config: ConfigYaml) =>
1052 setupProviderConfig(config, provider, apiKey);
1053 } else {
1054 editConfigYamlCallback = setupQuickstartConfig;
1055 }
1056 break;
1057
1058 default:
1059 console.error(`Invalid mode: ${mode}`);
1060 editConfigYamlCallback = (config) => config;
1061 }
1062
1063 editConfigFile((c) => c, editConfigYamlCallback);
1064
1065 void this.configHandler.reloadConfig();
1066 }
1067
1068 private getContextItems = async (
1069 msg: Message<{
1070 name: string;
1071 query: string;
1072 fullInput: string;
1073 selectedCode: RangeInFile[];
1074 isInAgentMode: boolean;
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 void Telemetry.capture("context_provider_get_context_items", {
1106 name: provider.description.title,
1107 });
1108
1109 const items = await provider.getContextItems(query, {
1110 config,
1111 llm,
1112 embeddingsProvider: config.selectedModelByRole.embed,
1113 fullInput,
1114 ide: this.ide,
1115 selectedCode,
1116 reranker: config.selectedModelByRole.rerank,
1117 fetch: (url, init) =>
1118 fetchwithRequestOptions(url, init, config.requestOptions),
1119 isInAgentMode: msg.data.isInAgentMode,
1120 });
1121
1122 void Telemetry.capture(
1123 "useContextProvider",
1124 {
1125 name: provider.description.title,
1126 },
1127 true,
1128 );
1129
1130 return items.map((item) => {
1131 const id: ContextItemId = {
1132 providerTitle: provider.description.title,
1133 itemId: uuidv4(),
1134 };
1135
1136 return { ...item, 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}