Elffuss BraidHub

kikocis/continue public

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