Elffuss BraidHub

kikocis/continue public

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