Elffuss BraidHub

kikocis/continue public

c04584525d2e · 41.9 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
970 on("didChangeSelectedProfile", async (msg) => {
971 if (msg.data.id) {
972 await this.configHandler.setSelectedProfileId(msg.data.id);
973 }
974 });
975
976 on("didChangeSelectedOrg", async (msg) => {
977 if (msg.data.id) {
978 await this.configHandler.setSelectedOrgId(
979 msg.data.id,
980 msg.data.profileId || undefined,
981 );
982 }
983 });
984
985 on("didChangeControlPlaneSessionInfo", async (msg) => {
986 this.messenger.send("sessionUpdate", {
987 sessionInfo: msg.data.sessionInfo,
988 });
989 await this.configHandler.updateControlPlaneSessionInfo(
990 msg.data.sessionInfo,
991 );
992 });
993
994 on("auth/getAuthUrl", async (msg) => {
995 const url = await getAuthUrlForTokenPage(
996 ideSettingsPromise,
997 msg.data.useOnboarding,
998 );
999 return { url };
1000 });
1001
1002 on("tools/call", async ({ data: { toolCall } }) =>
1003 this.handleToolCall(toolCall),
1004 );
1005
1006 on("isItemTooBig", async ({ data: { item } }) => {
1007 return this.isItemTooBig(item);
1008 });
1009
1010 // Process state handlers
1011 on("process/markAsBackgrounded", async ({ data: { toolCallId } }) => {
1012 markProcessAsBackgrounded(toolCallId);
1013 });
1014
1015 on(
1016 "process/isBackgrounded",
1017 async ({ data: { toolCallId }, messageId }) => {
1018 const isBackgrounded = isProcessBackgrounded(toolCallId);
1019 return isBackgrounded; // Return true to indicate the message was handled successfully
1020 },
1021 );
1022
1023 on("mdm/setLicenseKey", ({ data: { licenseKey } }) => {
1024 const isValid = setMdmLicenseKey(licenseKey);
1025 return isValid;
1026 });
1027 }
1028
1029 private async handleToolCall(toolCall: ToolCall) {
1030 const { config } = await this.configHandler.loadConfig();
1031 if (!config) {
1032 throw new Error("Config not loaded");
1033 }
1034
1035 const tool = config.tools.find(
1036 (t) => t.function.name === toolCall.function.name,
1037 );
1038
1039 if (!tool) {
1040 throw new Error(`Tool ${toolCall.function.name} not found`);
1041 }
1042
1043 if (!config.selectedModelByRole.chat) {
1044 throw new Error("No chat model selected");
1045 }
1046
1047 // Define a callback for streaming output updates
1048 const onPartialOutput = (params: {
1049 toolCallId: string;
1050 contextItems: ContextItem[];
1051 }) => {
1052 this.messenger.send("toolCallPartialOutput", params);
1053 };
1054
1055 const result = await callTool(tool, toolCall, {
1056 config,
1057 ide: this.ide,
1058 llm: config.selectedModelByRole.chat,
1059 fetch: (url, init) =>
1060 fetchwithRequestOptions(url, init, config.requestOptions),
1061 tool,
1062 toolCallId: toolCall.id,
1063 onPartialOutput,
1064 codeBaseIndexer: this.codeBaseIndexer,
1065 });
1066
1067 return result;
1068 }
1069
1070 private async isItemTooBig(item: ContextItemWithId) {
1071 const { config } = await this.configHandler.loadConfig();
1072 if (!config) {
1073 return false;
1074 }
1075
1076 const llm = config?.selectedModelByRole.chat;
1077 if (!llm) {
1078 throw new Error("No chat model selected");
1079 }
1080
1081 const tokens = countTokens(item.content, llm.model);
1082
1083 if (tokens > llm.contextLength - llm.completionOptions!.maxTokens!) {
1084 return true;
1085 }
1086
1087 return false;
1088 }
1089
1090 private handleAddAutocompleteModel(
1091 msg: Message<{
1092 model: ModelDescription;
1093 }>,
1094 ) {
1095 const model = msg.data.model;
1096 editConfigFile(
1097 (config) => {
1098 return {
1099 ...config,
1100 tabAutocompleteModel: model,
1101 };
1102 },
1103 (config) => ({
1104 ...config,
1105 models: [
1106 ...(config.models ?? []),
1107 {
1108 name: model.title,
1109 provider: model.provider,
1110 model: model.model,
1111 apiKey: model.apiKey,
1112 roles: ["autocomplete"],
1113 apiBase: model.apiBase,
1114 },
1115 ],
1116 }),
1117 );
1118 void this.configHandler.reloadConfig("Autocomplete model added");
1119 }
1120
1121 private async handleFilesChanged({
1122 data,
1123 }: Message<{
1124 uris?: string[];
1125 }>): Promise<void> {
1126 if (data?.uris?.length) {
1127 const diffCache = GitDiffCache.getInstance(getDiffFn(this.ide));
1128 diffCache.invalidate();
1129 walkDirCache.invalidate(); // safe approach for now - TODO - only invalidate on relevant changes
1130 for (const uri of data.uris) {
1131 const currentProfileUri =
1132 this.configHandler.currentProfile?.profileDescription.uri ?? "";
1133
1134 if (URI.equal(uri, currentProfileUri)) {
1135 // Trigger a toast notification to provide UI feedback that config has been updated
1136 const showToast =
1137 this.globalContext.get("showConfigUpdateToast") ?? true;
1138 if (showToast) {
1139 const selection = await this.ide.showToast(
1140 "info",
1141 "Config updated",
1142 "Don't show again",
1143 );
1144 if (selection === "Don't show again") {
1145 this.globalContext.update("showConfigUpdateToast", false);
1146 }
1147 }
1148 await this.configHandler.reloadConfig(
1149 "Current profile config file updated",
1150 );
1151 continue;
1152 }
1153
1154 if (
1155 uri.endsWith(".continuerc.json") ||
1156 uri.endsWith(".prompt") ||
1157 uri.endsWith(SYSTEM_PROMPT_DOT_FILE) ||
1158 (uri.includes(".continue") &&
1159 (uri.endsWith(".yaml") || uri.endsWith("yml"))) ||
1160 BLOCK_TYPES.some((blockType) =>
1161 uri.includes(`.continue/${blockType}`),
1162 )
1163 ) {
1164 await this.configHandler.reloadConfig(
1165 "Config-related file updated: continuerc, prompt, local block, etc",
1166 );
1167 } else if (uri.endsWith(RULES_MARKDOWN_FILENAME)) {
1168 try {
1169 const codebaseRulesCache = CodebaseRulesCache.getInstance();
1170 void codebaseRulesCache.update(this.ide, uri).then(() => {
1171 void this.configHandler.reloadConfig("Codebase rule update");
1172 });
1173 } catch (e) {
1174 Logger.error(`Failed to update codebase rule: ${e}`);
1175 }
1176 } else if (
1177 uri.endsWith(".continueignore") ||
1178 uri.endsWith(".gitignore")
1179 ) {
1180 // Reindex the workspaces
1181 this.invoke("index/forceReIndex", {
1182 shouldClearIndexes: true,
1183 });
1184 } else {
1185 const { config } = await this.configHandler.loadConfig();
1186 if (config && !config.disableIndexing) {
1187 // Reindex the file
1188 const ignore = await shouldIgnore(uri, this.ide);
1189 if (!ignore) {
1190 await this.codeBaseIndexer.refreshCodebaseIndexFiles([uri]);
1191 }
1192 }
1193 }
1194 }
1195 }
1196 }
1197
1198 private async handleListModels(msg: Message<{ title: string }>) {
1199 const { config } = await this.configHandler.loadConfig();
1200 if (!config) {
1201 return [];
1202 }
1203
1204 const model =
1205 config.modelsByRole.chat.find(
1206 (model) => model.title === msg.data.title,
1207 ) ??
1208 config.modelsByRole.chat.find((model) =>
1209 model.title?.startsWith(msg.data.title),
1210 );
1211
1212 try {
1213 if (model) {
1214 return await model.listModels();
1215 } else {
1216 if (msg.data.title === "Ollama") {
1217 const models = await new Ollama({ model: "" }).listModels();
1218 return models;
1219 } else {
1220 return undefined;
1221 }
1222 }
1223 } catch (e) {
1224 console.debug(`Error listing Ollama models: ${e}`);
1225 return undefined;
1226 }
1227 }
1228
1229 private async handleCompleteOnboarding(
1230 msg: Message<CompleteOnboardingPayload>,
1231 ) {
1232 const { mode, provider, apiKey } = msg.data;
1233
1234 let editConfigYamlCallback: (config: ConfigYaml) => ConfigYaml;
1235
1236 switch (mode) {
1237 case OnboardingModes.LOCAL:
1238 editConfigYamlCallback = setupLocalConfig;
1239 break;
1240
1241 case OnboardingModes.API_KEY:
1242 if (provider && apiKey) {
1243 editConfigYamlCallback = (config: ConfigYaml) =>
1244 setupProviderConfig(config, provider, apiKey);
1245 } else {
1246 editConfigYamlCallback = setupQuickstartConfig;
1247 }
1248 break;
1249
1250 default:
1251 Logger.error(`Invalid mode: ${mode}`);
1252 editConfigYamlCallback = (config) => config;
1253 }
1254
1255 editConfigFile((c) => c, editConfigYamlCallback);
1256
1257 void this.configHandler.reloadConfig("Onboarding completed");
1258 }
1259
1260 private getContextItems = async (
1261 msg: Message<{
1262 name: string;
1263 query: string;
1264 fullInput: string;
1265 selectedCode: RangeInFile[];
1266 isInAgentMode: boolean;
1267 }>,
1268 ) => {
1269 const { config } = await this.configHandler.loadConfig();
1270 if (!config) {
1271 return [];
1272 }
1273
1274 const { name, query, fullInput, selectedCode } = msg.data;
1275
1276 const llm = (await this.configHandler.loadConfig()).config
1277 ?.selectedModelByRole.chat;
1278
1279 if (!llm) {
1280 throw new Error("No chat model selected");
1281 }
1282
1283 const provider = config.contextProviders?.find(
1284 (provider) => provider.description.title === name,
1285 );
1286 if (!provider) {
1287 return [];
1288 }
1289
1290 try {
1291 void Telemetry.capture("context_provider_get_context_items", {
1292 name: provider.description.title,
1293 });
1294
1295 const items = await provider.getContextItems(query, {
1296 config,
1297 llm,
1298 embeddingsProvider: config.selectedModelByRole.embed,
1299 fullInput,
1300 ide: this.ide,
1301 selectedCode,
1302 reranker: config.selectedModelByRole.rerank,
1303 fetch: (url, init) =>
1304 fetchwithRequestOptions(url, init, config.requestOptions),
1305 isInAgentMode: msg.data.isInAgentMode,
1306 });
1307
1308 void Telemetry.capture(
1309 "useContextProvider",
1310 {
1311 name: provider.description.title,
1312 },
1313 true,
1314 );
1315
1316 return items.map((item) => {
1317 const id: ContextItemId = {
1318 providerTitle: provider.description.title,
1319 itemId: uuidv4(),
1320 };
1321
1322 return { ...item, id };
1323 });
1324 } catch (e) {
1325 let knownError = false;
1326
1327 if (e instanceof Error) {
1328 // After removing transformers JS embeddings provider from jetbrains
1329 // Should no longer see this error
1330 // if (e.message.toLowerCase().includes("embeddings provider")) {
1331 // knownError = true;
1332 // const toastOption = "See Docs";
1333 // void this.ide
1334 // .showToast(
1335 // "error",
1336 // `Set up an embeddings model to use @${name}`,
1337 // toastOption,
1338 // )
1339 // .then((userSelection) => {
1340 // if (userSelection === toastOption) {
1341 // void this.ide.openUrl(
1342 // "https://docs.continue.dev/customize/model-roles/embeddings",
1343 // );
1344 // }
1345 // });
1346 // }
1347 }
1348 if (!knownError) {
1349 void this.ide.showToast(
1350 "error",
1351 `Error getting context items from ${name}: ${e}`,
1352 );
1353 }
1354 return [];
1355 }
1356 };
1357}