Elffuss BraidHub

kikocis/continue public

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