Elffuss BraidHub

kikocis/continue public

ccbc6f34a529 · 31.4 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 filepaths = data.fileUris;
605 if (!prevFilepaths.filepaths.length) {
606 prevFilepaths.filepaths = filepaths;
607 }
608
609 // If there is a removal, including if the number of tabs is the same (which can happen with temp tabs)
610 if (filepaths.length <= prevFilepaths.filepaths.length) {
611 // Remove files from cache that are no longer open (i.e. in the cache but not in the list of opened tabs)
612 for (const [key, _] of openedFilesLruCache.entriesDescending()) {
613 if (!filepaths.includes(key)) {
614 openedFilesLruCache.delete(key);
615 }
616 }
617 }
618
619 prevFilepaths.filepaths = filepaths;
620 } catch (e) {
621 console.error(
622 `didChangeVisibleTextEditors: failed to update openedFilesLruCache`,
623 );
624 }
625
626 if (data.uris) {
627 this.messenger.send("didCloseFiles", {
628 uris: data.uris,
629 });
630 }
631 });
632
633 on("files/opened", async ({ data: { uris } }) => {
634 if (uris) {
635 for (const filepath of uris) {
636 try {
637 const ignore = await shouldIgnore(filepath, this.ide);
638 if (!ignore) {
639 // Set the active file as most recently used (need to force recency update by deleting and re-adding)
640 if (openedFilesLruCache.has(filepath)) {
641 openedFilesLruCache.delete(filepath);
642 }
643 openedFilesLruCache.set(filepath, filepath);
644 }
645 } catch (e) {
646 console.error(
647 `files/opened: failed to update openedFiles cache for ${filepath}`,
648 );
649 }
650 }
651 }
652 });
653
654 // Docs, etc. indexing
655 on("indexing/reindex", async (msg) => {
656 if (msg.data.type === "docs") {
657 void this.docsService.reindexDoc(msg.data.id);
658 }
659 });
660 on("indexing/abort", async (msg) => {
661 if (msg.data.type === "docs") {
662 this.docsService.abort(msg.data.id);
663 }
664 });
665 on("indexing/setPaused", async (msg) => {
666 if (msg.data.type === "docs") {
667 }
668 });
669 on("docs/initStatuses", async (msg) => {
670 void this.docsService.initStatuses();
671 });
672 on("docs/getDetails", async (msg) => {
673 return await this.docsService.getDetails(msg.data.startUrl);
674 });
675
676 on("didChangeSelectedProfile", async (msg) => {
677 if (msg.data.id) {
678 await this.configHandler.setSelectedProfileId(msg.data.id);
679 }
680 });
681
682 on("didChangeSelectedOrg", async (msg) => {
683 if (msg.data.id) {
684 await this.configHandler.setSelectedOrgId(
685 msg.data.id,
686 msg.data.profileId || undefined,
687 );
688 }
689 });
690
691 on("didChangeControlPlaneSessionInfo", async (msg) => {
692 this.messenger.send("sessionUpdate", {
693 sessionInfo: msg.data.sessionInfo,
694 });
695 await this.configHandler.updateControlPlaneSessionInfo(
696 msg.data.sessionInfo,
697 );
698 });
699
700 on("auth/getAuthUrl", async (msg) => {
701 const url = await getAuthUrlForTokenPage(
702 ideSettingsPromise,
703 msg.data.useOnboarding,
704 );
705 return { url };
706 });
707
708 on("tools/call", async ({ data: { toolCall } }) => {
709 const { config } = await this.configHandler.loadConfig();
710 if (!config) {
711 throw new Error("Config not loaded");
712 }
713
714 const tool = config.tools.find(
715 (t) => t.function.name === toolCall.function.name,
716 );
717
718 if (!tool) {
719 throw new Error(`Tool ${toolCall.function.name} not found`);
720 }
721
722 if (!config.selectedModelByRole.chat) {
723 throw new Error("No chat model selected");
724 }
725
726 // Define a callback for streaming output updates
727 const onPartialOutput = (params: {
728 toolCallId: string;
729 contextItems: ContextItem[];
730 }) => {
731 this.messenger.send("toolCallPartialOutput", params);
732 };
733
734 return await callTool(tool, toolCall.function.arguments, {
735 config,
736 ide: this.ide,
737 llm: config.selectedModelByRole.chat,
738 fetch: (url, init) =>
739 fetchwithRequestOptions(url, init, config.requestOptions),
740 tool,
741 toolCallId: toolCall.id,
742 onPartialOutput,
743 });
744 });
745
746 on("isItemTooBig", async ({ data: { item } }) => {
747 return this.isItemTooBig(item);
748 });
749
750 // Process state handlers
751 on("process/markAsBackgrounded", async ({ data: { toolCallId } }) => {
752 markProcessAsBackgrounded(toolCallId);
753 });
754
755 on(
756 "process/isBackgrounded",
757 async ({ data: { toolCallId }, messageId }) => {
758 const isBackgrounded = isProcessBackgrounded(toolCallId);
759 return isBackgrounded; // Return true to indicate the message was handled successfully
760 },
761 );
762
763 on("mdm/setLicenseKey", ({ data: { licenseKey } }) => {
764 const isValid = setMdmLicenseKey(licenseKey);
765 return isValid;
766 });
767 }
768
769 private async isItemTooBig(item: ContextItemWithId) {
770 const { config } = await this.configHandler.loadConfig();
771 if (!config) {
772 return false;
773 }
774
775 const llm = config?.selectedModelByRole.chat;
776 if (!llm) {
777 throw new Error("No chat model selected");
778 }
779
780 const tokens = countTokens(item.content, llm.model);
781
782 if (tokens > llm.contextLength - llm.completionOptions!.maxTokens!) {
783 return true;
784 }
785
786 return false;
787 }
788
789 private handleAddAutocompleteModel(
790 msg: Message<{
791 model: ModelDescription;
792 }>,
793 ) {
794 const model = msg.data.model;
795 editConfigFile(
796 (config) => {
797 return {
798 ...config,
799 tabAutocompleteModel: model,
800 };
801 },
802 (config) => ({
803 ...config,
804 models: [
805 ...(config.models ?? []),
806 {
807 name: model.title,
808 provider: model.provider,
809 model: model.model,
810 apiKey: model.apiKey,
811 roles: ["autocomplete"],
812 apiBase: model.apiBase,
813 },
814 ],
815 }),
816 );
817 void this.configHandler.reloadConfig();
818 }
819
820 private async handleFilesChanged({
821 data,
822 }: Message<{
823 uris?: string[];
824 }>) {
825 if (data?.uris?.length) {
826 const diffCache = GitDiffCache.getInstance(getDiffFn(this.ide));
827 diffCache.invalidate();
828 walkDirCache.invalidate(); // safe approach for now - TODO - only invalidate on relevant changes
829 for (const uri of data.uris) {
830 const currentProfileUri =
831 this.configHandler.currentProfile?.profileDescription.uri ?? "";
832
833 if (URI.equal(uri, currentProfileUri)) {
834 // Trigger a toast notification to provide UI feedback that config has been updated
835 const showToast =
836 this.globalContext.get("showConfigUpdateToast") ?? true;
837 if (showToast) {
838 const selection = await this.ide.showToast(
839 "info",
840 "Config updated",
841 "Don't show again",
842 );
843 if (selection === "Don't show again") {
844 this.globalContext.update("showConfigUpdateToast", false);
845 }
846 }
847 await this.configHandler.reloadConfig();
848 continue;
849 }
850
851 if (
852 uri.endsWith(".continuerc.json") ||
853 uri.endsWith(".prompt") ||
854 uri.endsWith(SYSTEM_PROMPT_DOT_FILE) ||
855 (uri.includes(".continue") && uri.endsWith(".yaml"))
856 ) {
857 await this.configHandler.reloadConfig();
858 } else if (
859 uri.endsWith(".continueignore") ||
860 uri.endsWith(".gitignore")
861 ) {
862 // Reindex the workspaces
863 this.invoke("index/forceReIndex", {
864 shouldClearIndexes: true,
865 });
866 } else {
867 const { config } = await this.configHandler.loadConfig();
868 if (config && !config.disableIndexing) {
869 // Reindex the file
870 const ignore = await shouldIgnore(uri, this.ide);
871 if (!ignore) {
872 await this.codeBaseIndexer.refreshCodebaseIndexFiles([uri]);
873 }
874 }
875 }
876 }
877 }
878 }
879
880 private async handleListModels(msg: Message<{ title: string }>) {
881 const { config } = await this.configHandler.loadConfig();
882 if (!config) {
883 return [];
884 }
885
886 const model =
887 config.modelsByRole.chat.find(
888 (model) => model.title === msg.data.title,
889 ) ??
890 config.modelsByRole.chat.find((model) =>
891 model.title?.startsWith(msg.data.title),
892 );
893
894 try {
895 if (model) {
896 return await model.listModels();
897 } else {
898 if (msg.data.title === "Ollama") {
899 const models = await new Ollama({ model: "" }).listModels();
900 return models;
901 } else {
902 return undefined;
903 }
904 }
905 } catch (e) {
906 console.debug(`Error listing Ollama models: ${e}`);
907 return undefined;
908 }
909 }
910
911 private async handleCompleteOnboarding(msg: Message<{ mode: string }>) {
912 const mode = msg.data.mode;
913
914 if (mode === "Custom") {
915 return;
916 }
917
918 let editConfigYamlCallback: (config: ConfigYaml) => ConfigYaml;
919
920 switch (mode) {
921 case "Local":
922 editConfigYamlCallback = setupLocalConfig;
923 break;
924
925 case "Quickstart":
926 editConfigYamlCallback = setupQuickstartConfig;
927 break;
928
929 case "Best":
930 editConfigYamlCallback = setupBestConfig;
931 break;
932
933 default:
934 console.error(`Invalid mode: ${mode}`);
935 editConfigYamlCallback = (config) => config;
936 }
937
938 editConfigFile((c) => c, editConfigYamlCallback);
939
940 void this.configHandler.reloadConfig();
941 }
942
943 private getContextItems = async (
944 msg: Message<{
945 name: string;
946 query: string;
947 fullInput: string;
948 selectedCode: RangeInFile[];
949 }>,
950 ) => {
951 const { config } = await this.configHandler.loadConfig();
952 if (!config) {
953 return [];
954 }
955
956 const { name, query, fullInput, selectedCode } = msg.data;
957
958 const llm = (await this.configHandler.loadConfig()).config
959 ?.selectedModelByRole.chat;
960
961 if (!llm) {
962 throw new Error("No chat model selected");
963 }
964
965 const provider =
966 config.contextProviders?.find(
967 (provider) => provider.description.title === name,
968 ) ??
969 [
970 // user doesn't need these in their config.json for the shortcuts to work
971 // option+enter
972 new CurrentFileContextProvider({}),
973 // cmd+enter
974 new CodebaseContextProvider({}),
975 ].find((provider) => provider.description.title === name);
976 if (!provider) {
977 return [];
978 }
979
980 try {
981 const id: ContextItemId = {
982 providerTitle: provider.description.title,
983 itemId: uuidv4(),
984 };
985
986 const items = await provider.getContextItems(query, {
987 config,
988 llm,
989 embeddingsProvider: config.selectedModelByRole.embed,
990 fullInput,
991 ide: this.ide,
992 selectedCode,
993 reranker: config.selectedModelByRole.rerank,
994 fetch: (url, init) =>
995 fetchwithRequestOptions(url, init, config.requestOptions),
996 });
997
998 void Telemetry.capture(
999 "useContextProvider",
1000 {
1001 name: provider.description.title,
1002 },
1003 true,
1004 );
1005
1006 return items.map((item) => ({
1007 ...item,
1008 id,
1009 }));
1010 } catch (e) {
1011 let knownError = false;
1012
1013 if (e instanceof Error) {
1014 // After removing transformers JS embeddings provider from jetbrains
1015 // Should no longer see this error
1016 // if (e.message.toLowerCase().includes("embeddings provider")) {
1017 // knownError = true;
1018 // const toastOption = "See Docs";
1019 // void this.ide
1020 // .showToast(
1021 // "error",
1022 // `Set up an embeddings model to use @${name}`,
1023 // toastOption,
1024 // )
1025 // .then((userSelection) => {
1026 // if (userSelection === toastOption) {
1027 // void this.ide.openUrl(
1028 // "https://docs.continue.dev/customize/model-roles/embeddings",
1029 // );
1030 // }
1031 // });
1032 // }
1033 }
1034 if (!knownError) {
1035 void this.ide.showToast(
1036 "error",
1037 `Error getting context items from ${name}: ${e}`,
1038 );
1039 }
1040 return [];
1041 }
1042 };
1043}