Elffuss BraidHub

kikocis/continue public

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