Elffuss BraidHub

kikocis/continue public

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