Elffuss BraidHub

kikocis/continue public

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