Elffuss BraidHub

kikocis/continue public

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