Elffuss BraidHub

kikocis/continue public

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