Elffuss BraidHub

kikocis/continue public

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