Elffuss BraidHub

kikocis/continue public

7bdcbb7e117f · 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, {
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 codeBaseIndexer: this.codeBaseIndexer,
714 });
715 });
716
717 on("isItemTooBig", async ({ data: { item } }) => {
718 return this.isItemTooBig(item);
719 });
720
721 // Process state handlers
722 on("process/markAsBackgrounded", async ({ data: { toolCallId } }) => {
723 markProcessAsBackgrounded(toolCallId);
724 });
725
726 on(
727 "process/isBackgrounded",
728 async ({ data: { toolCallId }, messageId }) => {
729 const isBackgrounded = isProcessBackgrounded(toolCallId);
730 return isBackgrounded; // Return true to indicate the message was handled successfully
731 },
732 );
733
734 on("mdm/setLicenseKey", ({ data: { licenseKey } }) => {
735 const isValid = setMdmLicenseKey(licenseKey);
736 return isValid;
737 });
738 }
739
740 private async isItemTooBig(item: ContextItemWithId) {
741 const { config } = await this.configHandler.loadConfig();
742 if (!config) {
743 return false;
744 }
745
746 const llm = config?.selectedModelByRole.chat;
747 if (!llm) {
748 throw new Error("No chat model selected");
749 }
750
751 const tokens = countTokens(item.content, llm.model);
752
753 if (tokens > llm.contextLength - llm.completionOptions!.maxTokens!) {
754 return true;
755 }
756
757 return false;
758 }
759
760 private handleAddAutocompleteModel(
761 msg: Message<{
762 model: ModelDescription;
763 }>,
764 ) {
765 const model = msg.data.model;
766 editConfigFile(
767 (config) => {
768 return {
769 ...config,
770 tabAutocompleteModel: model,
771 };
772 },
773 (config) => ({
774 ...config,
775 models: [
776 ...(config.models ?? []),
777 {
778 name: model.title,
779 provider: model.provider,
780 model: model.model,
781 apiKey: model.apiKey,
782 roles: ["autocomplete"],
783 apiBase: model.apiBase,
784 },
785 ],
786 }),
787 );
788 void this.configHandler.reloadConfig();
789 }
790
791 private async handleFilesChanged({
792 data,
793 }: Message<{
794 uris?: string[];
795 }>) {
796 if (data?.uris?.length) {
797 const diffCache = GitDiffCache.getInstance(getDiffFn(this.ide));
798 diffCache.invalidate();
799 walkDirCache.invalidate(); // safe approach for now - TODO - only invalidate on relevant changes
800 for (const uri of data.uris) {
801 const currentProfileUri =
802 this.configHandler.currentProfile?.profileDescription.uri ?? "";
803
804 if (URI.equal(uri, currentProfileUri)) {
805 // Trigger a toast notification to provide UI feedback that config has been updated
806 const showToast =
807 this.globalContext.get("showConfigUpdateToast") ?? true;
808 if (showToast) {
809 const selection = await this.ide.showToast(
810 "info",
811 "Config updated",
812 "Don't show again",
813 );
814 if (selection === "Don't show again") {
815 this.globalContext.update("showConfigUpdateToast", false);
816 }
817 }
818 await this.configHandler.reloadConfig();
819 continue;
820 }
821
822 if (
823 uri.endsWith(".continuerc.json") ||
824 uri.endsWith(".prompt") ||
825 uri.endsWith(SYSTEM_PROMPT_DOT_FILE) ||
826 (uri.includes(".continue") && uri.endsWith(".yaml"))
827 ) {
828 await this.configHandler.reloadConfig();
829 } else if (
830 uri.endsWith(".continueignore") ||
831 uri.endsWith(".gitignore")
832 ) {
833 // Reindex the workspaces
834 this.invoke("index/forceReIndex", {
835 shouldClearIndexes: true,
836 });
837 } else {
838 const { config } = await this.configHandler.loadConfig();
839 if (config && !config.disableIndexing) {
840 // Reindex the file
841 const ignore = await shouldIgnore(uri, this.ide);
842 if (!ignore) {
843 await this.codeBaseIndexer.refreshCodebaseIndexFiles([uri]);
844 }
845 }
846 }
847 }
848 }
849 }
850
851 private async handleListModels(msg: Message<{ title: string }>) {
852 const { config } = await this.configHandler.loadConfig();
853 if (!config) {
854 return [];
855 }
856
857 const model =
858 config.modelsByRole.chat.find(
859 (model) => model.title === msg.data.title,
860 ) ??
861 config.modelsByRole.chat.find((model) =>
862 model.title?.startsWith(msg.data.title),
863 );
864
865 try {
866 if (model) {
867 return await model.listModels();
868 } else {
869 if (msg.data.title === "Ollama") {
870 const models = await new Ollama({ model: "" }).listModels();
871 return models;
872 } else {
873 return undefined;
874 }
875 }
876 } catch (e) {
877 console.debug(`Error listing Ollama models: ${e}`);
878 return undefined;
879 }
880 }
881
882 private async handleCompleteOnboarding(
883 msg: Message<CompleteOnboardingPayload>,
884 ) {
885 const { mode, provider, apiKey } = msg.data;
886
887 let editConfigYamlCallback: (config: ConfigYaml) => ConfigYaml;
888
889 switch (mode) {
890 case OnboardingModes.LOCAL:
891 editConfigYamlCallback = setupLocalConfig;
892 break;
893
894 case OnboardingModes.API_KEY:
895 if (provider && apiKey) {
896 editConfigYamlCallback = (config: ConfigYaml) =>
897 setupProviderConfig(config, provider, apiKey);
898 } else {
899 editConfigYamlCallback = setupQuickstartConfig;
900 }
901 break;
902
903 default:
904 console.error(`Invalid mode: ${mode}`);
905 editConfigYamlCallback = (config) => config;
906 }
907
908 editConfigFile((c) => c, editConfigYamlCallback);
909
910 void this.configHandler.reloadConfig();
911 }
912
913 private getContextItems = async (
914 msg: Message<{
915 name: string;
916 query: string;
917 fullInput: string;
918 selectedCode: RangeInFile[];
919 }>,
920 ) => {
921 const { config } = await this.configHandler.loadConfig();
922 if (!config) {
923 return [];
924 }
925
926 const { name, query, fullInput, selectedCode } = msg.data;
927
928 const llm = (await this.configHandler.loadConfig()).config
929 ?.selectedModelByRole.chat;
930
931 if (!llm) {
932 throw new Error("No chat model selected");
933 }
934
935 const provider =
936 config.contextProviders?.find(
937 (provider) => provider.description.title === name,
938 ) ??
939 [
940 // user doesn't need these in their config.json for the shortcuts to work
941 // option+enter
942 new CurrentFileContextProvider({}),
943 // cmd+enter
944 new CodebaseContextProvider({}),
945 ].find((provider) => provider.description.title === name);
946 if (!provider) {
947 return [];
948 }
949
950 try {
951 const id: ContextItemId = {
952 providerTitle: provider.description.title,
953 itemId: uuidv4(),
954 };
955
956 const items = await provider.getContextItems(query, {
957 config,
958 llm,
959 embeddingsProvider: config.selectedModelByRole.embed,
960 fullInput,
961 ide: this.ide,
962 selectedCode,
963 reranker: config.selectedModelByRole.rerank,
964 fetch: (url, init) =>
965 fetchwithRequestOptions(url, init, config.requestOptions),
966 });
967
968 void Telemetry.capture(
969 "useContextProvider",
970 {
971 name: provider.description.title,
972 },
973 true,
974 );
975
976 return items.map((item) => ({
977 ...item,
978 id,
979 }));
980 } catch (e) {
981 let knownError = false;
982
983 if (e instanceof Error) {
984 // After removing transformers JS embeddings provider from jetbrains
985 // Should no longer see this error
986 // if (e.message.toLowerCase().includes("embeddings provider")) {
987 // knownError = true;
988 // const toastOption = "See Docs";
989 // void this.ide
990 // .showToast(
991 // "error",
992 // `Set up an embeddings model to use @${name}`,
993 // toastOption,
994 // )
995 // .then((userSelection) => {
996 // if (userSelection === toastOption) {
997 // void this.ide.openUrl(
998 // "https://docs.continue.dev/customize/model-roles/embeddings",
999 // );
1000 // }
1001 // });
1002 // }
1003 }
1004 if (!knownError) {
1005 void this.ide.showToast(
1006 "error",
1007 `Error getting context items from ${name}: ${e}`,
1008 );
1009 }
1010 return [];
1011 }
1012 };
1013}