Elffuss BraidHub

kikocis/continue public

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