Elffuss BraidHub

kikocis/continue public

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