Elffuss BraidHub

kikocis/continue public

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