Elffuss BraidHub

kikocis/continue public

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