Elffuss BraidHub

kikocis/continue public

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