Elffuss BraidHub

kikocis/continue public

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