Elffuss BraidHub

kikocis/continue public

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