Elffuss BraidHub

kikocis/continue public

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